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/OperationKinds.h"
28 #include "clang/AST/ParentMapContext.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/DiagnosticSema.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Lex/LiteralSupport.h"
39 #include "clang/Lex/Preprocessor.h"
40 #include "clang/Sema/AnalysisBasedWarnings.h"
41 #include "clang/Sema/DeclSpec.h"
42 #include "clang/Sema/DelayedDiagnostic.h"
43 #include "clang/Sema/Designator.h"
44 #include "clang/Sema/Initialization.h"
45 #include "clang/Sema/Lookup.h"
46 #include "clang/Sema/Overload.h"
47 #include "clang/Sema/ParsedTemplate.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/ScopeInfo.h"
50 #include "clang/Sema/SemaFixItUtils.h"
51 #include "clang/Sema/SemaInternal.h"
52 #include "clang/Sema/Template.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TypeSize.h"
59 
60 using namespace clang;
61 using namespace sema;
62 
63 /// Determine whether the use of this declaration is valid, without
64 /// emitting diagnostics.
65 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
66   // See if this is an auto-typed variable whose initializer we are parsing.
67   if (ParsingInitForAutoVars.count(D))
68     return false;
69 
70   // See if this is a deleted function.
71   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
72     if (FD->isDeleted())
73       return false;
74 
75     // If the function has a deduced return type, and we can't deduce it,
76     // then we can't use it either.
77     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
78         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
79       return false;
80 
81     // See if this is an aligned allocation/deallocation function that is
82     // unavailable.
83     if (TreatUnavailableAsInvalid &&
84         isUnavailableAlignedAllocationFunction(*FD))
85       return false;
86   }
87 
88   // See if this function is unavailable.
89   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
90       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
91     return false;
92 
93   if (isa<UnresolvedUsingIfExistsDecl>(D))
94     return false;
95 
96   return true;
97 }
98 
99 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
100   // Warn if this is used but marked unused.
101   if (const auto *A = D->getAttr<UnusedAttr>()) {
102     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
103     // should diagnose them.
104     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
105         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
106       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
107       if (DC && !DC->hasAttr<UnusedAttr>())
108         S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
109     }
110   }
111 }
112 
113 /// Emit a note explaining that this function is deleted.
114 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
115   assert(Decl && Decl->isDeleted());
116 
117   if (Decl->isDefaulted()) {
118     // If the method was explicitly defaulted, point at that declaration.
119     if (!Decl->isImplicit())
120       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
121 
122     // Try to diagnose why this special member function was implicitly
123     // deleted. This might fail, if that reason no longer applies.
124     DiagnoseDeletedDefaultedFunction(Decl);
125     return;
126   }
127 
128   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
129   if (Ctor && Ctor->isInheritingConstructor())
130     return NoteDeletedInheritingConstructor(Ctor);
131 
132   Diag(Decl->getLocation(), diag::note_availability_specified_here)
133     << Decl << 1;
134 }
135 
136 /// Determine whether a FunctionDecl was ever declared with an
137 /// explicit storage class.
138 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
139   for (auto I : D->redecls()) {
140     if (I->getStorageClass() != SC_None)
141       return true;
142   }
143   return false;
144 }
145 
146 /// Check whether we're in an extern inline function and referring to a
147 /// variable or function with internal linkage (C11 6.7.4p3).
148 ///
149 /// This is only a warning because we used to silently accept this code, but
150 /// in many cases it will not behave correctly. This is not enabled in C++ mode
151 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
152 /// and so while there may still be user mistakes, most of the time we can't
153 /// prove that there are errors.
154 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
155                                                       const NamedDecl *D,
156                                                       SourceLocation Loc) {
157   // This is disabled under C++; there are too many ways for this to fire in
158   // contexts where the warning is a false positive, or where it is technically
159   // correct but benign.
160   if (S.getLangOpts().CPlusPlus)
161     return;
162 
163   // Check if this is an inlined function or method.
164   FunctionDecl *Current = S.getCurFunctionDecl();
165   if (!Current)
166     return;
167   if (!Current->isInlined())
168     return;
169   if (!Current->isExternallyVisible())
170     return;
171 
172   // Check if the decl has internal linkage.
173   if (D->getFormalLinkage() != InternalLinkage)
174     return;
175 
176   // Downgrade from ExtWarn to Extension if
177   //  (1) the supposedly external inline function is in the main file,
178   //      and probably won't be included anywhere else.
179   //  (2) the thing we're referencing is a pure function.
180   //  (3) the thing we're referencing is another inline function.
181   // This last can give us false negatives, but it's better than warning on
182   // wrappers for simple C library functions.
183   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
184   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
185   if (!DowngradeWarning && UsedFn)
186     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
187 
188   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
189                                : diag::ext_internal_in_extern_inline)
190     << /*IsVar=*/!UsedFn << D;
191 
192   S.MaybeSuggestAddingStaticToDecl(Current);
193 
194   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
195       << D;
196 }
197 
198 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
199   const FunctionDecl *First = Cur->getFirstDecl();
200 
201   // Suggest "static" on the function, if possible.
202   if (!hasAnyExplicitStorageClass(First)) {
203     SourceLocation DeclBegin = First->getSourceRange().getBegin();
204     Diag(DeclBegin, diag::note_convert_inline_to_static)
205       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
206   }
207 }
208 
209 /// Determine whether the use of this declaration is valid, and
210 /// emit any corresponding diagnostics.
211 ///
212 /// This routine diagnoses various problems with referencing
213 /// declarations that can occur when using a declaration. For example,
214 /// it might warn if a deprecated or unavailable declaration is being
215 /// used, or produce an error (and return true) if a C++0x deleted
216 /// function is being used.
217 ///
218 /// \returns true if there was an error (this declaration cannot be
219 /// referenced), false otherwise.
220 ///
221 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
222                              const ObjCInterfaceDecl *UnknownObjCClass,
223                              bool ObjCPropertyAccess,
224                              bool AvoidPartialAvailabilityChecks,
225                              ObjCInterfaceDecl *ClassReceiver) {
226   SourceLocation Loc = Locs.front();
227   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
228     // If there were any diagnostics suppressed by template argument deduction,
229     // emit them now.
230     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
231     if (Pos != SuppressedDiagnostics.end()) {
232       for (const PartialDiagnosticAt &Suppressed : Pos->second)
233         Diag(Suppressed.first, Suppressed.second);
234 
235       // Clear out the list of suppressed diagnostics, so that we don't emit
236       // them again for this specialization. However, we don't obsolete this
237       // entry from the table, because we want to avoid ever emitting these
238       // diagnostics again.
239       Pos->second.clear();
240     }
241 
242     // C++ [basic.start.main]p3:
243     //   The function 'main' shall not be used within a program.
244     if (cast<FunctionDecl>(D)->isMain())
245       Diag(Loc, diag::ext_main_used);
246 
247     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
248   }
249 
250   // See if this is an auto-typed variable whose initializer we are parsing.
251   if (ParsingInitForAutoVars.count(D)) {
252     if (isa<BindingDecl>(D)) {
253       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
254         << D->getDeclName();
255     } else {
256       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
257         << D->getDeclName() << cast<VarDecl>(D)->getType();
258     }
259     return true;
260   }
261 
262   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
263     // See if this is a deleted function.
264     if (FD->isDeleted()) {
265       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
266       if (Ctor && Ctor->isInheritingConstructor())
267         Diag(Loc, diag::err_deleted_inherited_ctor_use)
268             << Ctor->getParent()
269             << Ctor->getInheritedConstructor().getConstructor()->getParent();
270       else
271         Diag(Loc, diag::err_deleted_function_use);
272       NoteDeletedFunction(FD);
273       return true;
274     }
275 
276     // [expr.prim.id]p4
277     //   A program that refers explicitly or implicitly to a function with a
278     //   trailing requires-clause whose constraint-expression is not satisfied,
279     //   other than to declare it, is ill-formed. [...]
280     //
281     // See if this is a function with constraints that need to be satisfied.
282     // Check this before deducing the return type, as it might instantiate the
283     // definition.
284     if (FD->getTrailingRequiresClause()) {
285       ConstraintSatisfaction Satisfaction;
286       if (CheckFunctionConstraints(FD, Satisfaction, Loc))
287         // A diagnostic will have already been generated (non-constant
288         // constraint expression, for example)
289         return true;
290       if (!Satisfaction.IsSatisfied) {
291         Diag(Loc,
292              diag::err_reference_to_function_with_unsatisfied_constraints)
293             << D;
294         DiagnoseUnsatisfiedConstraint(Satisfaction);
295         return true;
296       }
297     }
298 
299     // If the function has a deduced return type, and we can't deduce it,
300     // then we can't use it either.
301     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
302         DeduceReturnType(FD, Loc))
303       return true;
304 
305     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
306       return true;
307 
308     if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
309       return true;
310   }
311 
312   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
313     // Lambdas are only default-constructible or assignable in C++2a onwards.
314     if (MD->getParent()->isLambda() &&
315         ((isa<CXXConstructorDecl>(MD) &&
316           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
317          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
318       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
319         << !isa<CXXConstructorDecl>(MD);
320     }
321   }
322 
323   auto getReferencedObjCProp = [](const NamedDecl *D) ->
324                                       const ObjCPropertyDecl * {
325     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
326       return MD->findPropertyDecl();
327     return nullptr;
328   };
329   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
330     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
331       return true;
332   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
333       return true;
334   }
335 
336   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
337   // Only the variables omp_in and omp_out are allowed in the combiner.
338   // Only the variables omp_priv and omp_orig are allowed in the
339   // initializer-clause.
340   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
341   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
342       isa<VarDecl>(D)) {
343     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
344         << getCurFunction()->HasOMPDeclareReductionCombiner;
345     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
346     return true;
347   }
348 
349   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
350   //  List-items in map clauses on this construct may only refer to the declared
351   //  variable var and entities that could be referenced by a procedure defined
352   //  at the same location
353   if (LangOpts.OpenMP && isa<VarDecl>(D) &&
354       !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
355     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
356         << getOpenMPDeclareMapperVarName();
357     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358     return true;
359   }
360 
361   if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
362     Diag(Loc, diag::err_use_of_empty_using_if_exists);
363     Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
364     return true;
365   }
366 
367   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
368                              AvoidPartialAvailabilityChecks, ClassReceiver);
369 
370   DiagnoseUnusedOfDecl(*this, D, Loc);
371 
372   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
373 
374   if (auto *VD = dyn_cast<ValueDecl>(D))
375     checkTypeSupport(VD->getType(), Loc, VD);
376 
377   if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
378     if (!Context.getTargetInfo().isTLSSupported())
379       if (const auto *VD = dyn_cast<VarDecl>(D))
380         if (VD->getTLSKind() != VarDecl::TLS_None)
381           targetDiag(*Locs.begin(), diag::err_thread_unsupported);
382   }
383 
384   if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
385       !isUnevaluatedContext()) {
386     // C++ [expr.prim.req.nested] p3
387     //   A local parameter shall only appear as an unevaluated operand
388     //   (Clause 8) within the constraint-expression.
389     Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
390         << D;
391     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
392     return true;
393   }
394 
395   return false;
396 }
397 
398 /// DiagnoseSentinelCalls - This routine checks whether a call or
399 /// message-send is to a declaration with the sentinel attribute, and
400 /// if so, it checks that the requirements of the sentinel are
401 /// satisfied.
402 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
403                                  ArrayRef<Expr *> Args) {
404   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
405   if (!attr)
406     return;
407 
408   // The number of formal parameters of the declaration.
409   unsigned numFormalParams;
410 
411   // The kind of declaration.  This is also an index into a %select in
412   // the diagnostic.
413   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
414 
415   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
416     numFormalParams = MD->param_size();
417     calleeType = CT_Method;
418   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
419     numFormalParams = FD->param_size();
420     calleeType = CT_Function;
421   } else if (isa<VarDecl>(D)) {
422     QualType type = cast<ValueDecl>(D)->getType();
423     const FunctionType *fn = nullptr;
424     if (const PointerType *ptr = type->getAs<PointerType>()) {
425       fn = ptr->getPointeeType()->getAs<FunctionType>();
426       if (!fn) return;
427       calleeType = CT_Function;
428     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
429       fn = ptr->getPointeeType()->castAs<FunctionType>();
430       calleeType = CT_Block;
431     } else {
432       return;
433     }
434 
435     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
436       numFormalParams = proto->getNumParams();
437     } else {
438       numFormalParams = 0;
439     }
440   } else {
441     return;
442   }
443 
444   // "nullPos" is the number of formal parameters at the end which
445   // effectively count as part of the variadic arguments.  This is
446   // useful if you would prefer to not have *any* formal parameters,
447   // but the language forces you to have at least one.
448   unsigned nullPos = attr->getNullPos();
449   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
450   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
451 
452   // The number of arguments which should follow the sentinel.
453   unsigned numArgsAfterSentinel = attr->getSentinel();
454 
455   // If there aren't enough arguments for all the formal parameters,
456   // the sentinel, and the args after the sentinel, complain.
457   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
458     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
459     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460     return;
461   }
462 
463   // Otherwise, find the sentinel expression.
464   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
465   if (!sentinelExpr) return;
466   if (sentinelExpr->isValueDependent()) return;
467   if (Context.isSentinelNullExpr(sentinelExpr)) return;
468 
469   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
470   // or 'NULL' if those are actually defined in the context.  Only use
471   // 'nil' for ObjC methods, where it's much more likely that the
472   // variadic arguments form a list of object pointers.
473   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
474   std::string NullValue;
475   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
476     NullValue = "nil";
477   else if (getLangOpts().CPlusPlus11)
478     NullValue = "nullptr";
479   else if (PP.isMacroDefined("NULL"))
480     NullValue = "NULL";
481   else
482     NullValue = "(void*) 0";
483 
484   if (MissingNilLoc.isInvalid())
485     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
486   else
487     Diag(MissingNilLoc, diag::warn_missing_sentinel)
488       << int(calleeType)
489       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
490   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
491 }
492 
493 SourceRange Sema::getExprRange(Expr *E) const {
494   return E ? E->getSourceRange() : SourceRange();
495 }
496 
497 //===----------------------------------------------------------------------===//
498 //  Standard Promotions and Conversions
499 //===----------------------------------------------------------------------===//
500 
501 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
502 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
503   // Handle any placeholder expressions which made it here.
504   if (E->hasPlaceholderType()) {
505     ExprResult result = CheckPlaceholderExpr(E);
506     if (result.isInvalid()) return ExprError();
507     E = result.get();
508   }
509 
510   QualType Ty = E->getType();
511   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
512 
513   if (Ty->isFunctionType()) {
514     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
515       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
516         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
517           return ExprError();
518 
519     E = ImpCastExprToType(E, Context.getPointerType(Ty),
520                           CK_FunctionToPointerDecay).get();
521   } else if (Ty->isArrayType()) {
522     // In C90 mode, arrays only promote to pointers if the array expression is
523     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
524     // type 'array of type' is converted to an expression that has type 'pointer
525     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
526     // that has type 'array of type' ...".  The relevant change is "an lvalue"
527     // (C90) to "an expression" (C99).
528     //
529     // C++ 4.2p1:
530     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
531     // T" can be converted to an rvalue of type "pointer to T".
532     //
533     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
534       ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
535                                          CK_ArrayToPointerDecay);
536       if (Res.isInvalid())
537         return ExprError();
538       E = Res.get();
539     }
540   }
541   return E;
542 }
543 
544 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
545   // Check to see if we are dereferencing a null pointer.  If so,
546   // and if not volatile-qualified, this is undefined behavior that the
547   // optimizer will delete, so warn about it.  People sometimes try to use this
548   // to get a deterministic trap and are surprised by clang's behavior.  This
549   // only handles the pattern "*null", which is a very syntactic check.
550   const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
551   if (UO && UO->getOpcode() == UO_Deref &&
552       UO->getSubExpr()->getType()->isPointerType()) {
553     const LangAS AS =
554         UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
555     if ((!isTargetAddressSpace(AS) ||
556          (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
557         UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
558             S.Context, Expr::NPC_ValueDependentIsNotNull) &&
559         !UO->getType().isVolatileQualified()) {
560       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561                             S.PDiag(diag::warn_indirection_through_null)
562                                 << UO->getSubExpr()->getSourceRange());
563       S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
564                             S.PDiag(diag::note_indirection_through_null));
565     }
566   }
567 }
568 
569 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
570                                     SourceLocation AssignLoc,
571                                     const Expr* RHS) {
572   const ObjCIvarDecl *IV = OIRE->getDecl();
573   if (!IV)
574     return;
575 
576   DeclarationName MemberName = IV->getDeclName();
577   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
578   if (!Member || !Member->isStr("isa"))
579     return;
580 
581   const Expr *Base = OIRE->getBase();
582   QualType BaseType = Base->getType();
583   if (OIRE->isArrow())
584     BaseType = BaseType->getPointeeType();
585   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
586     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
587       ObjCInterfaceDecl *ClassDeclared = nullptr;
588       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
589       if (!ClassDeclared->getSuperClass()
590           && (*ClassDeclared->ivar_begin()) == IV) {
591         if (RHS) {
592           NamedDecl *ObjectSetClass =
593             S.LookupSingleName(S.TUScope,
594                                &S.Context.Idents.get("object_setClass"),
595                                SourceLocation(), S.LookupOrdinaryName);
596           if (ObjectSetClass) {
597             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
598             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
599                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
600                                               "object_setClass(")
601                 << FixItHint::CreateReplacement(
602                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
603                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
604           }
605           else
606             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
607         } else {
608           NamedDecl *ObjectGetClass =
609             S.LookupSingleName(S.TUScope,
610                                &S.Context.Idents.get("object_getClass"),
611                                SourceLocation(), S.LookupOrdinaryName);
612           if (ObjectGetClass)
613             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
614                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
615                                               "object_getClass(")
616                 << FixItHint::CreateReplacement(
617                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
618           else
619             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
620         }
621         S.Diag(IV->getLocation(), diag::note_ivar_decl);
622       }
623     }
624 }
625 
626 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
627   // Handle any placeholder expressions which made it here.
628   if (E->hasPlaceholderType()) {
629     ExprResult result = CheckPlaceholderExpr(E);
630     if (result.isInvalid()) return ExprError();
631     E = result.get();
632   }
633 
634   // C++ [conv.lval]p1:
635   //   A glvalue of a non-function, non-array type T can be
636   //   converted to a prvalue.
637   if (!E->isGLValue()) return E;
638 
639   QualType T = E->getType();
640   assert(!T.isNull() && "r-value conversion on typeless expression?");
641 
642   // lvalue-to-rvalue conversion cannot be applied to function or array types.
643   if (T->isFunctionType() || T->isArrayType())
644     return E;
645 
646   // We don't want to throw lvalue-to-rvalue casts on top of
647   // expressions of certain types in C++.
648   if (getLangOpts().CPlusPlus &&
649       (E->getType() == Context.OverloadTy ||
650        T->isDependentType() ||
651        T->isRecordType()))
652     return E;
653 
654   // The C standard is actually really unclear on this point, and
655   // DR106 tells us what the result should be but not why.  It's
656   // generally best to say that void types just doesn't undergo
657   // lvalue-to-rvalue at all.  Note that expressions of unqualified
658   // 'void' type are never l-values, but qualified void can be.
659   if (T->isVoidType())
660     return E;
661 
662   // OpenCL usually rejects direct accesses to values of 'half' type.
663   if (getLangOpts().OpenCL &&
664       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
665       T->isHalfType()) {
666     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
667       << 0 << T;
668     return ExprError();
669   }
670 
671   CheckForNullPointerDereference(*this, E);
672   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674                                      &Context.Idents.get("object_getClass"),
675                                      SourceLocation(), LookupOrdinaryName);
676     if (ObjectGetClass)
677       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
678           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
679           << FixItHint::CreateReplacement(
680                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
681     else
682       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
683   }
684   else if (const ObjCIvarRefExpr *OIRE =
685             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
687 
688   // C++ [conv.lval]p1:
689   //   [...] If T is a non-class type, the type of the prvalue is the
690   //   cv-unqualified version of T. Otherwise, the type of the
691   //   rvalue is T.
692   //
693   // C99 6.3.2.1p2:
694   //   If the lvalue has qualified type, the value has the unqualified
695   //   version of the type of the lvalue; otherwise, the value has the
696   //   type of the lvalue.
697   if (T.hasQualifiers())
698     T = T.getUnqualifiedType();
699 
700   // Under the MS ABI, lock down the inheritance model now.
701   if (T->isMemberPointerType() &&
702       Context.getTargetInfo().getCXXABI().isMicrosoft())
703     (void)isCompleteType(E->getExprLoc(), T);
704 
705   ExprResult Res = CheckLValueToRValueConversionOperand(E);
706   if (Res.isInvalid())
707     return Res;
708   E = Res.get();
709 
710   // Loading a __weak object implicitly retains the value, so we need a cleanup to
711   // balance that.
712   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
713     Cleanup.setExprNeedsCleanups(true);
714 
715   if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
716     Cleanup.setExprNeedsCleanups(true);
717 
718   // C++ [conv.lval]p3:
719   //   If T is cv std::nullptr_t, the result is a null pointer constant.
720   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
721   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
722                                  CurFPFeatureOverrides());
723 
724   // C11 6.3.2.1p2:
725   //   ... if the lvalue has atomic type, the value has the non-atomic version
726   //   of the type of the lvalue ...
727   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
728     T = Atomic->getValueType().getUnqualifiedType();
729     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
730                                    nullptr, VK_PRValue, FPOptionsOverride());
731   }
732 
733   return Res;
734 }
735 
736 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
737   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
738   if (Res.isInvalid())
739     return ExprError();
740   Res = DefaultLvalueConversion(Res.get());
741   if (Res.isInvalid())
742     return ExprError();
743   return Res;
744 }
745 
746 /// CallExprUnaryConversions - a special case of an unary conversion
747 /// performed on a function designator of a call expression.
748 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
749   QualType Ty = E->getType();
750   ExprResult Res = E;
751   // Only do implicit cast for a function type, but not for a pointer
752   // to function type.
753   if (Ty->isFunctionType()) {
754     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
755                             CK_FunctionToPointerDecay);
756     if (Res.isInvalid())
757       return ExprError();
758   }
759   Res = DefaultLvalueConversion(Res.get());
760   if (Res.isInvalid())
761     return ExprError();
762   return Res.get();
763 }
764 
765 /// UsualUnaryConversions - Performs various conversions that are common to most
766 /// operators (C99 6.3). The conversions of array and function types are
767 /// sometimes suppressed. For example, the array->pointer conversion doesn't
768 /// apply if the array is an argument to the sizeof or address (&) operators.
769 /// In these instances, this routine should *not* be called.
770 ExprResult Sema::UsualUnaryConversions(Expr *E) {
771   // First, convert to an r-value.
772   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
773   if (Res.isInvalid())
774     return ExprError();
775   E = Res.get();
776 
777   QualType Ty = E->getType();
778   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
779 
780   LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
781   if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
782       (getLangOpts().getFPEvalMethod() !=
783            LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
784        PP.getLastFPEvalPragmaLocation().isValid())) {
785     switch (EvalMethod) {
786     default:
787       llvm_unreachable("Unrecognized float evaluation method");
788       break;
789     case LangOptions::FEM_UnsetOnCommandLine:
790       llvm_unreachable("Float evaluation method should be set by now");
791       break;
792     case LangOptions::FEM_Double:
793       if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
794         // Widen the expression to double.
795         return Ty->isComplexType()
796                    ? ImpCastExprToType(E,
797                                        Context.getComplexType(Context.DoubleTy),
798                                        CK_FloatingComplexCast)
799                    : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
800       break;
801     case LangOptions::FEM_Extended:
802       if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
803         // Widen the expression to long double.
804         return Ty->isComplexType()
805                    ? ImpCastExprToType(
806                          E, Context.getComplexType(Context.LongDoubleTy),
807                          CK_FloatingComplexCast)
808                    : ImpCastExprToType(E, Context.LongDoubleTy,
809                                        CK_FloatingCast);
810       break;
811     }
812   }
813 
814   // Half FP have to be promoted to float unless it is natively supported
815   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
816     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
817 
818   // Try to perform integral promotions if the object has a theoretically
819   // promotable type.
820   if (Ty->isIntegralOrUnscopedEnumerationType()) {
821     // C99 6.3.1.1p2:
822     //
823     //   The following may be used in an expression wherever an int or
824     //   unsigned int may be used:
825     //     - an object or expression with an integer type whose integer
826     //       conversion rank is less than or equal to the rank of int
827     //       and unsigned int.
828     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
829     //
830     //   If an int can represent all values of the original type, the
831     //   value is converted to an int; otherwise, it is converted to an
832     //   unsigned int. These are called the integer promotions. All
833     //   other types are unchanged by the integer promotions.
834 
835     QualType PTy = Context.isPromotableBitField(E);
836     if (!PTy.isNull()) {
837       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
838       return E;
839     }
840     if (Ty->isPromotableIntegerType()) {
841       QualType PT = Context.getPromotedIntegerType(Ty);
842       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
843       return E;
844     }
845   }
846   return E;
847 }
848 
849 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
850 /// do not have a prototype. Arguments that have type float or __fp16
851 /// are promoted to double. All other argument types are converted by
852 /// UsualUnaryConversions().
853 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
854   QualType Ty = E->getType();
855   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
856 
857   ExprResult Res = UsualUnaryConversions(E);
858   if (Res.isInvalid())
859     return ExprError();
860   E = Res.get();
861 
862   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
863   // promote to double.
864   // Note that default argument promotion applies only to float (and
865   // half/fp16); it does not apply to _Float16.
866   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
867   if (BTy && (BTy->getKind() == BuiltinType::Half ||
868               BTy->getKind() == BuiltinType::Float)) {
869     if (getLangOpts().OpenCL &&
870         !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
871       if (BTy->getKind() == BuiltinType::Half) {
872         E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
873       }
874     } else {
875       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
876     }
877   }
878   if (BTy &&
879       getLangOpts().getExtendIntArgs() ==
880           LangOptions::ExtendArgsKind::ExtendTo64 &&
881       Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
882       Context.getTypeSizeInChars(BTy) <
883           Context.getTypeSizeInChars(Context.LongLongTy)) {
884     E = (Ty->isUnsignedIntegerType())
885             ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
886                   .get()
887             : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
888     assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
889            "Unexpected typesize for LongLongTy");
890   }
891 
892   // C++ performs lvalue-to-rvalue conversion as a default argument
893   // promotion, even on class types, but note:
894   //   C++11 [conv.lval]p2:
895   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
896   //     operand or a subexpression thereof the value contained in the
897   //     referenced object is not accessed. Otherwise, if the glvalue
898   //     has a class type, the conversion copy-initializes a temporary
899   //     of type T from the glvalue and the result of the conversion
900   //     is a prvalue for the temporary.
901   // FIXME: add some way to gate this entire thing for correctness in
902   // potentially potentially evaluated contexts.
903   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
904     ExprResult Temp = PerformCopyInitialization(
905                        InitializedEntity::InitializeTemporary(E->getType()),
906                                                 E->getExprLoc(), E);
907     if (Temp.isInvalid())
908       return ExprError();
909     E = Temp.get();
910   }
911 
912   return E;
913 }
914 
915 /// Determine the degree of POD-ness for an expression.
916 /// Incomplete types are considered POD, since this check can be performed
917 /// when we're in an unevaluated context.
918 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
919   if (Ty->isIncompleteType()) {
920     // C++11 [expr.call]p7:
921     //   After these conversions, if the argument does not have arithmetic,
922     //   enumeration, pointer, pointer to member, or class type, the program
923     //   is ill-formed.
924     //
925     // Since we've already performed array-to-pointer and function-to-pointer
926     // decay, the only such type in C++ is cv void. This also handles
927     // initializer lists as variadic arguments.
928     if (Ty->isVoidType())
929       return VAK_Invalid;
930 
931     if (Ty->isObjCObjectType())
932       return VAK_Invalid;
933     return VAK_Valid;
934   }
935 
936   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
937     return VAK_Invalid;
938 
939   if (Ty.isCXX98PODType(Context))
940     return VAK_Valid;
941 
942   // C++11 [expr.call]p7:
943   //   Passing a potentially-evaluated argument of class type (Clause 9)
944   //   having a non-trivial copy constructor, a non-trivial move constructor,
945   //   or a non-trivial destructor, with no corresponding parameter,
946   //   is conditionally-supported with implementation-defined semantics.
947   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
948     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
949       if (!Record->hasNonTrivialCopyConstructor() &&
950           !Record->hasNonTrivialMoveConstructor() &&
951           !Record->hasNonTrivialDestructor())
952         return VAK_ValidInCXX11;
953 
954   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
955     return VAK_Valid;
956 
957   if (Ty->isObjCObjectType())
958     return VAK_Invalid;
959 
960   if (getLangOpts().MSVCCompat)
961     return VAK_MSVCUndefined;
962 
963   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
964   // permitted to reject them. We should consider doing so.
965   return VAK_Undefined;
966 }
967 
968 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
969   // Don't allow one to pass an Objective-C interface to a vararg.
970   const QualType &Ty = E->getType();
971   VarArgKind VAK = isValidVarArgType(Ty);
972 
973   // Complain about passing non-POD types through varargs.
974   switch (VAK) {
975   case VAK_ValidInCXX11:
976     DiagRuntimeBehavior(
977         E->getBeginLoc(), nullptr,
978         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
979     LLVM_FALLTHROUGH;
980   case VAK_Valid:
981     if (Ty->isRecordType()) {
982       // This is unlikely to be what the user intended. If the class has a
983       // 'c_str' member function, the user probably meant to call that.
984       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
985                           PDiag(diag::warn_pass_class_arg_to_vararg)
986                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
987     }
988     break;
989 
990   case VAK_Undefined:
991   case VAK_MSVCUndefined:
992     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
993                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
994                             << getLangOpts().CPlusPlus11 << Ty << CT);
995     break;
996 
997   case VAK_Invalid:
998     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
999       Diag(E->getBeginLoc(),
1000            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1001           << Ty << CT;
1002     else if (Ty->isObjCObjectType())
1003       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1005                               << Ty << CT);
1006     else
1007       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1008           << isa<InitListExpr>(E) << Ty << CT;
1009     break;
1010   }
1011 }
1012 
1013 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1014 /// will create a trap if the resulting type is not a POD type.
1015 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
1016                                                   FunctionDecl *FDecl) {
1017   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1018     // Strip the unbridged-cast placeholder expression off, if applicable.
1019     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1020         (CT == VariadicMethod ||
1021          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1022       E = stripARCUnbridgedCast(E);
1023 
1024     // Otherwise, do normal placeholder checking.
1025     } else {
1026       ExprResult ExprRes = CheckPlaceholderExpr(E);
1027       if (ExprRes.isInvalid())
1028         return ExprError();
1029       E = ExprRes.get();
1030     }
1031   }
1032 
1033   ExprResult ExprRes = DefaultArgumentPromotion(E);
1034   if (ExprRes.isInvalid())
1035     return ExprError();
1036 
1037   // Copy blocks to the heap.
1038   if (ExprRes.get()->getType()->isBlockPointerType())
1039     maybeExtendBlockObject(ExprRes);
1040 
1041   E = ExprRes.get();
1042 
1043   // Diagnostics regarding non-POD argument types are
1044   // emitted along with format string checking in Sema::CheckFunctionCall().
1045   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
1046     // Turn this into a trap.
1047     CXXScopeSpec SS;
1048     SourceLocation TemplateKWLoc;
1049     UnqualifiedId Name;
1050     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1051                        E->getBeginLoc());
1052     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1053                                           /*HasTrailingLParen=*/true,
1054                                           /*IsAddressOfOperand=*/false);
1055     if (TrapFn.isInvalid())
1056       return ExprError();
1057 
1058     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1059                                     None, E->getEndLoc());
1060     if (Call.isInvalid())
1061       return ExprError();
1062 
1063     ExprResult Comma =
1064         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1065     if (Comma.isInvalid())
1066       return ExprError();
1067     return Comma.get();
1068   }
1069 
1070   if (!getLangOpts().CPlusPlus &&
1071       RequireCompleteType(E->getExprLoc(), E->getType(),
1072                           diag::err_call_incomplete_argument))
1073     return ExprError();
1074 
1075   return E;
1076 }
1077 
1078 /// Converts an integer to complex float type.  Helper function of
1079 /// UsualArithmeticConversions()
1080 ///
1081 /// \return false if the integer expression is an integer type and is
1082 /// successfully converted to the complex type.
1083 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1084                                                   ExprResult &ComplexExpr,
1085                                                   QualType IntTy,
1086                                                   QualType ComplexTy,
1087                                                   bool SkipCast) {
1088   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1089   if (SkipCast) return false;
1090   if (IntTy->isIntegerType()) {
1091     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1092     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1093     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1094                                   CK_FloatingRealToComplex);
1095   } else {
1096     assert(IntTy->isComplexIntegerType());
1097     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1098                                   CK_IntegralComplexToFloatingComplex);
1099   }
1100   return false;
1101 }
1102 
1103 /// Handle arithmetic conversion with complex types.  Helper function of
1104 /// UsualArithmeticConversions()
1105 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1106                                              ExprResult &RHS, QualType LHSType,
1107                                              QualType RHSType,
1108                                              bool IsCompAssign) {
1109   // if we have an integer operand, the result is the complex type.
1110   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1111                                              /*skipCast*/false))
1112     return LHSType;
1113   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1114                                              /*skipCast*/IsCompAssign))
1115     return RHSType;
1116 
1117   // This handles complex/complex, complex/float, or float/complex.
1118   // When both operands are complex, the shorter operand is converted to the
1119   // type of the longer, and that is the type of the result. This corresponds
1120   // to what is done when combining two real floating-point operands.
1121   // The fun begins when size promotion occur across type domains.
1122   // From H&S 6.3.4: When one operand is complex and the other is a real
1123   // floating-point type, the less precise type is converted, within it's
1124   // real or complex domain, to the precision of the other type. For example,
1125   // when combining a "long double" with a "double _Complex", the
1126   // "double _Complex" is promoted to "long double _Complex".
1127 
1128   // Compute the rank of the two types, regardless of whether they are complex.
1129   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1130 
1131   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1132   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1133   QualType LHSElementType =
1134       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1135   QualType RHSElementType =
1136       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1137 
1138   QualType ResultType = S.Context.getComplexType(LHSElementType);
1139   if (Order < 0) {
1140     // Promote the precision of the LHS if not an assignment.
1141     ResultType = S.Context.getComplexType(RHSElementType);
1142     if (!IsCompAssign) {
1143       if (LHSComplexType)
1144         LHS =
1145             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1146       else
1147         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1148     }
1149   } else if (Order > 0) {
1150     // Promote the precision of the RHS.
1151     if (RHSComplexType)
1152       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1153     else
1154       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1155   }
1156   return ResultType;
1157 }
1158 
1159 /// Handle arithmetic conversion from integer to float.  Helper function
1160 /// of UsualArithmeticConversions()
1161 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1162                                            ExprResult &IntExpr,
1163                                            QualType FloatTy, QualType IntTy,
1164                                            bool ConvertFloat, bool ConvertInt) {
1165   if (IntTy->isIntegerType()) {
1166     if (ConvertInt)
1167       // Convert intExpr to the lhs floating point type.
1168       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1169                                     CK_IntegralToFloating);
1170     return FloatTy;
1171   }
1172 
1173   // Convert both sides to the appropriate complex float.
1174   assert(IntTy->isComplexIntegerType());
1175   QualType result = S.Context.getComplexType(FloatTy);
1176 
1177   // _Complex int -> _Complex float
1178   if (ConvertInt)
1179     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1180                                   CK_IntegralComplexToFloatingComplex);
1181 
1182   // float -> _Complex float
1183   if (ConvertFloat)
1184     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1185                                     CK_FloatingRealToComplex);
1186 
1187   return result;
1188 }
1189 
1190 /// Handle arithmethic conversion with floating point types.  Helper
1191 /// function of UsualArithmeticConversions()
1192 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1193                                       ExprResult &RHS, QualType LHSType,
1194                                       QualType RHSType, bool IsCompAssign) {
1195   bool LHSFloat = LHSType->isRealFloatingType();
1196   bool RHSFloat = RHSType->isRealFloatingType();
1197 
1198   // N1169 4.1.4: If one of the operands has a floating type and the other
1199   //              operand has a fixed-point type, the fixed-point operand
1200   //              is converted to the floating type [...]
1201   if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1202     if (LHSFloat)
1203       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1204     else if (!IsCompAssign)
1205       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1206     return LHSFloat ? LHSType : RHSType;
1207   }
1208 
1209   // If we have two real floating types, convert the smaller operand
1210   // to the bigger result.
1211   if (LHSFloat && RHSFloat) {
1212     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1213     if (order > 0) {
1214       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1215       return LHSType;
1216     }
1217 
1218     assert(order < 0 && "illegal float comparison");
1219     if (!IsCompAssign)
1220       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1221     return RHSType;
1222   }
1223 
1224   if (LHSFloat) {
1225     // Half FP has to be promoted to float unless it is natively supported
1226     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1227       LHSType = S.Context.FloatTy;
1228 
1229     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1230                                       /*ConvertFloat=*/!IsCompAssign,
1231                                       /*ConvertInt=*/ true);
1232   }
1233   assert(RHSFloat);
1234   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1235                                     /*ConvertFloat=*/ true,
1236                                     /*ConvertInt=*/!IsCompAssign);
1237 }
1238 
1239 /// Diagnose attempts to convert between __float128, __ibm128 and
1240 /// long double if there is no support for such conversion.
1241 /// Helper function of UsualArithmeticConversions().
1242 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1243                                       QualType RHSType) {
1244   // No issue if either is not a floating point type.
1245   if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1246     return false;
1247 
1248   // No issue if both have the same 128-bit float semantics.
1249   auto *LHSComplex = LHSType->getAs<ComplexType>();
1250   auto *RHSComplex = RHSType->getAs<ComplexType>();
1251 
1252   QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1253   QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1254 
1255   const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1256   const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1257 
1258   if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1259        &RHSSem != &llvm::APFloat::IEEEquad()) &&
1260       (&LHSSem != &llvm::APFloat::IEEEquad() ||
1261        &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1262     return false;
1263 
1264   return true;
1265 }
1266 
1267 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1268 
1269 namespace {
1270 /// These helper callbacks are placed in an anonymous namespace to
1271 /// permit their use as function template parameters.
1272 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1273   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1274 }
1275 
1276 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1277   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1278                              CK_IntegralComplexCast);
1279 }
1280 }
1281 
1282 /// Handle integer arithmetic conversions.  Helper function of
1283 /// UsualArithmeticConversions()
1284 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1285 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1286                                         ExprResult &RHS, QualType LHSType,
1287                                         QualType RHSType, bool IsCompAssign) {
1288   // The rules for this case are in C99 6.3.1.8
1289   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1290   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1291   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1292   if (LHSSigned == RHSSigned) {
1293     // Same signedness; use the higher-ranked type
1294     if (order >= 0) {
1295       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1296       return LHSType;
1297     } else if (!IsCompAssign)
1298       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1299     return RHSType;
1300   } else if (order != (LHSSigned ? 1 : -1)) {
1301     // The unsigned type has greater than or equal rank to the
1302     // signed type, so use the unsigned type
1303     if (RHSSigned) {
1304       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1305       return LHSType;
1306     } else if (!IsCompAssign)
1307       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1308     return RHSType;
1309   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1310     // The two types are different widths; if we are here, that
1311     // means the signed type is larger than the unsigned type, so
1312     // use the signed type.
1313     if (LHSSigned) {
1314       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315       return LHSType;
1316     } else if (!IsCompAssign)
1317       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318     return RHSType;
1319   } else {
1320     // The signed type is higher-ranked than the unsigned type,
1321     // but isn't actually any bigger (like unsigned int and long
1322     // on most 32-bit systems).  Use the unsigned type corresponding
1323     // to the signed type.
1324     QualType result =
1325       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1326     RHS = (*doRHSCast)(S, RHS.get(), result);
1327     if (!IsCompAssign)
1328       LHS = (*doLHSCast)(S, LHS.get(), result);
1329     return result;
1330   }
1331 }
1332 
1333 /// Handle conversions with GCC complex int extension.  Helper function
1334 /// of UsualArithmeticConversions()
1335 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1336                                            ExprResult &RHS, QualType LHSType,
1337                                            QualType RHSType,
1338                                            bool IsCompAssign) {
1339   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1340   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1341 
1342   if (LHSComplexInt && RHSComplexInt) {
1343     QualType LHSEltType = LHSComplexInt->getElementType();
1344     QualType RHSEltType = RHSComplexInt->getElementType();
1345     QualType ScalarType =
1346       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1347         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1348 
1349     return S.Context.getComplexType(ScalarType);
1350   }
1351 
1352   if (LHSComplexInt) {
1353     QualType LHSEltType = LHSComplexInt->getElementType();
1354     QualType ScalarType =
1355       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1356         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1357     QualType ComplexType = S.Context.getComplexType(ScalarType);
1358     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1359                               CK_IntegralRealToComplex);
1360 
1361     return ComplexType;
1362   }
1363 
1364   assert(RHSComplexInt);
1365 
1366   QualType RHSEltType = RHSComplexInt->getElementType();
1367   QualType ScalarType =
1368     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1369       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1370   QualType ComplexType = S.Context.getComplexType(ScalarType);
1371 
1372   if (!IsCompAssign)
1373     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1374                               CK_IntegralRealToComplex);
1375   return ComplexType;
1376 }
1377 
1378 /// Return the rank of a given fixed point or integer type. The value itself
1379 /// doesn't matter, but the values must be increasing with proper increasing
1380 /// rank as described in N1169 4.1.1.
1381 static unsigned GetFixedPointRank(QualType Ty) {
1382   const auto *BTy = Ty->getAs<BuiltinType>();
1383   assert(BTy && "Expected a builtin type.");
1384 
1385   switch (BTy->getKind()) {
1386   case BuiltinType::ShortFract:
1387   case BuiltinType::UShortFract:
1388   case BuiltinType::SatShortFract:
1389   case BuiltinType::SatUShortFract:
1390     return 1;
1391   case BuiltinType::Fract:
1392   case BuiltinType::UFract:
1393   case BuiltinType::SatFract:
1394   case BuiltinType::SatUFract:
1395     return 2;
1396   case BuiltinType::LongFract:
1397   case BuiltinType::ULongFract:
1398   case BuiltinType::SatLongFract:
1399   case BuiltinType::SatULongFract:
1400     return 3;
1401   case BuiltinType::ShortAccum:
1402   case BuiltinType::UShortAccum:
1403   case BuiltinType::SatShortAccum:
1404   case BuiltinType::SatUShortAccum:
1405     return 4;
1406   case BuiltinType::Accum:
1407   case BuiltinType::UAccum:
1408   case BuiltinType::SatAccum:
1409   case BuiltinType::SatUAccum:
1410     return 5;
1411   case BuiltinType::LongAccum:
1412   case BuiltinType::ULongAccum:
1413   case BuiltinType::SatLongAccum:
1414   case BuiltinType::SatULongAccum:
1415     return 6;
1416   default:
1417     if (BTy->isInteger())
1418       return 0;
1419     llvm_unreachable("Unexpected fixed point or integer type");
1420   }
1421 }
1422 
1423 /// handleFixedPointConversion - Fixed point operations between fixed
1424 /// point types and integers or other fixed point types do not fall under
1425 /// usual arithmetic conversion since these conversions could result in loss
1426 /// of precsision (N1169 4.1.4). These operations should be calculated with
1427 /// the full precision of their result type (N1169 4.1.6.2.1).
1428 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1429                                            QualType RHSTy) {
1430   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1431          "Expected at least one of the operands to be a fixed point type");
1432   assert((LHSTy->isFixedPointOrIntegerType() ||
1433           RHSTy->isFixedPointOrIntegerType()) &&
1434          "Special fixed point arithmetic operation conversions are only "
1435          "applied to ints or other fixed point types");
1436 
1437   // If one operand has signed fixed-point type and the other operand has
1438   // unsigned fixed-point type, then the unsigned fixed-point operand is
1439   // converted to its corresponding signed fixed-point type and the resulting
1440   // type is the type of the converted operand.
1441   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1442     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1443   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1444     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1445 
1446   // The result type is the type with the highest rank, whereby a fixed-point
1447   // conversion rank is always greater than an integer conversion rank; if the
1448   // type of either of the operands is a saturating fixedpoint type, the result
1449   // type shall be the saturating fixed-point type corresponding to the type
1450   // with the highest rank; the resulting value is converted (taking into
1451   // account rounding and overflow) to the precision of the resulting type.
1452   // Same ranks between signed and unsigned types are resolved earlier, so both
1453   // types are either signed or both unsigned at this point.
1454   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1455   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1456 
1457   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1458 
1459   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1460     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1461 
1462   return ResultTy;
1463 }
1464 
1465 /// Check that the usual arithmetic conversions can be performed on this pair of
1466 /// expressions that might be of enumeration type.
1467 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1468                                            SourceLocation Loc,
1469                                            Sema::ArithConvKind ACK) {
1470   // C++2a [expr.arith.conv]p1:
1471   //   If one operand is of enumeration type and the other operand is of a
1472   //   different enumeration type or a floating-point type, this behavior is
1473   //   deprecated ([depr.arith.conv.enum]).
1474   //
1475   // Warn on this in all language modes. Produce a deprecation warning in C++20.
1476   // Eventually we will presumably reject these cases (in C++23 onwards?).
1477   QualType L = LHS->getType(), R = RHS->getType();
1478   bool LEnum = L->isUnscopedEnumerationType(),
1479        REnum = R->isUnscopedEnumerationType();
1480   bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1481   if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1482       (REnum && L->isFloatingType())) {
1483     S.Diag(Loc, S.getLangOpts().CPlusPlus20
1484                     ? diag::warn_arith_conv_enum_float_cxx20
1485                     : diag::warn_arith_conv_enum_float)
1486         << LHS->getSourceRange() << RHS->getSourceRange()
1487         << (int)ACK << LEnum << L << R;
1488   } else if (!IsCompAssign && LEnum && REnum &&
1489              !S.Context.hasSameUnqualifiedType(L, R)) {
1490     unsigned DiagID;
1491     if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1492         !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1493       // If either enumeration type is unnamed, it's less likely that the
1494       // user cares about this, but this situation is still deprecated in
1495       // C++2a. Use a different warning group.
1496       DiagID = S.getLangOpts().CPlusPlus20
1497                     ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1498                     : diag::warn_arith_conv_mixed_anon_enum_types;
1499     } else if (ACK == Sema::ACK_Conditional) {
1500       // Conditional expressions are separated out because they have
1501       // historically had a different warning flag.
1502       DiagID = S.getLangOpts().CPlusPlus20
1503                    ? diag::warn_conditional_mixed_enum_types_cxx20
1504                    : diag::warn_conditional_mixed_enum_types;
1505     } else if (ACK == Sema::ACK_Comparison) {
1506       // Comparison expressions are separated out because they have
1507       // historically had a different warning flag.
1508       DiagID = S.getLangOpts().CPlusPlus20
1509                    ? diag::warn_comparison_mixed_enum_types_cxx20
1510                    : diag::warn_comparison_mixed_enum_types;
1511     } else {
1512       DiagID = S.getLangOpts().CPlusPlus20
1513                    ? diag::warn_arith_conv_mixed_enum_types_cxx20
1514                    : diag::warn_arith_conv_mixed_enum_types;
1515     }
1516     S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1517                         << (int)ACK << L << R;
1518   }
1519 }
1520 
1521 /// UsualArithmeticConversions - Performs various conversions that are common to
1522 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1523 /// routine returns the first non-arithmetic type found. The client is
1524 /// responsible for emitting appropriate error diagnostics.
1525 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1526                                           SourceLocation Loc,
1527                                           ArithConvKind ACK) {
1528   checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1529 
1530   if (ACK != ACK_CompAssign) {
1531     LHS = UsualUnaryConversions(LHS.get());
1532     if (LHS.isInvalid())
1533       return QualType();
1534   }
1535 
1536   RHS = UsualUnaryConversions(RHS.get());
1537   if (RHS.isInvalid())
1538     return QualType();
1539 
1540   // For conversion purposes, we ignore any qualifiers.
1541   // For example, "const float" and "float" are equivalent.
1542   QualType LHSType =
1543     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1544   QualType RHSType =
1545     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1546 
1547   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1548   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1549     LHSType = AtomicLHS->getValueType();
1550 
1551   // If both types are identical, no conversion is needed.
1552   if (LHSType == RHSType)
1553     return LHSType;
1554 
1555   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1556   // The caller can deal with this (e.g. pointer + int).
1557   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1558     return QualType();
1559 
1560   // Apply unary and bitfield promotions to the LHS's type.
1561   QualType LHSUnpromotedType = LHSType;
1562   if (LHSType->isPromotableIntegerType())
1563     LHSType = Context.getPromotedIntegerType(LHSType);
1564   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1565   if (!LHSBitfieldPromoteTy.isNull())
1566     LHSType = LHSBitfieldPromoteTy;
1567   if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1568     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1569 
1570   // If both types are identical, no conversion is needed.
1571   if (LHSType == RHSType)
1572     return LHSType;
1573 
1574   // At this point, we have two different arithmetic types.
1575 
1576   // Diagnose attempts to convert between __ibm128, __float128 and long double
1577   // where such conversions currently can't be handled.
1578   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1579     return QualType();
1580 
1581   // Handle complex types first (C99 6.3.1.8p1).
1582   if (LHSType->isComplexType() || RHSType->isComplexType())
1583     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1584                                         ACK == ACK_CompAssign);
1585 
1586   // Now handle "real" floating types (i.e. float, double, long double).
1587   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1588     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1589                                  ACK == ACK_CompAssign);
1590 
1591   // Handle GCC complex int extension.
1592   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1593     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1594                                       ACK == ACK_CompAssign);
1595 
1596   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1597     return handleFixedPointConversion(*this, LHSType, RHSType);
1598 
1599   // Finally, we have two differing integer types.
1600   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1601            (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1602 }
1603 
1604 //===----------------------------------------------------------------------===//
1605 //  Semantic Analysis for various Expression Types
1606 //===----------------------------------------------------------------------===//
1607 
1608 
1609 ExprResult
1610 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1611                                 SourceLocation DefaultLoc,
1612                                 SourceLocation RParenLoc,
1613                                 Expr *ControllingExpr,
1614                                 ArrayRef<ParsedType> ArgTypes,
1615                                 ArrayRef<Expr *> ArgExprs) {
1616   unsigned NumAssocs = ArgTypes.size();
1617   assert(NumAssocs == ArgExprs.size());
1618 
1619   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1620   for (unsigned i = 0; i < NumAssocs; ++i) {
1621     if (ArgTypes[i])
1622       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1623     else
1624       Types[i] = nullptr;
1625   }
1626 
1627   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1628                                              ControllingExpr,
1629                                              llvm::makeArrayRef(Types, NumAssocs),
1630                                              ArgExprs);
1631   delete [] Types;
1632   return ER;
1633 }
1634 
1635 ExprResult
1636 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1637                                  SourceLocation DefaultLoc,
1638                                  SourceLocation RParenLoc,
1639                                  Expr *ControllingExpr,
1640                                  ArrayRef<TypeSourceInfo *> Types,
1641                                  ArrayRef<Expr *> Exprs) {
1642   unsigned NumAssocs = Types.size();
1643   assert(NumAssocs == Exprs.size());
1644 
1645   // Decay and strip qualifiers for the controlling expression type, and handle
1646   // placeholder type replacement. See committee discussion from WG14 DR423.
1647   {
1648     EnterExpressionEvaluationContext Unevaluated(
1649         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1650     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1651     if (R.isInvalid())
1652       return ExprError();
1653     ControllingExpr = R.get();
1654   }
1655 
1656   // The controlling expression is an unevaluated operand, so side effects are
1657   // likely unintended.
1658   if (!inTemplateInstantiation() &&
1659       ControllingExpr->HasSideEffects(Context, false))
1660     Diag(ControllingExpr->getExprLoc(),
1661          diag::warn_side_effects_unevaluated_context);
1662 
1663   bool TypeErrorFound = false,
1664        IsResultDependent = ControllingExpr->isTypeDependent(),
1665        ContainsUnexpandedParameterPack
1666          = ControllingExpr->containsUnexpandedParameterPack();
1667 
1668   for (unsigned i = 0; i < NumAssocs; ++i) {
1669     if (Exprs[i]->containsUnexpandedParameterPack())
1670       ContainsUnexpandedParameterPack = true;
1671 
1672     if (Types[i]) {
1673       if (Types[i]->getType()->containsUnexpandedParameterPack())
1674         ContainsUnexpandedParameterPack = true;
1675 
1676       if (Types[i]->getType()->isDependentType()) {
1677         IsResultDependent = true;
1678       } else {
1679         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680         // complete object type other than a variably modified type."
1681         unsigned D = 0;
1682         if (Types[i]->getType()->isIncompleteType())
1683           D = diag::err_assoc_type_incomplete;
1684         else if (!Types[i]->getType()->isObjectType())
1685           D = diag::err_assoc_type_nonobject;
1686         else if (Types[i]->getType()->isVariablyModifiedType())
1687           D = diag::err_assoc_type_variably_modified;
1688 
1689         if (D != 0) {
1690           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1691             << Types[i]->getTypeLoc().getSourceRange()
1692             << Types[i]->getType();
1693           TypeErrorFound = true;
1694         }
1695 
1696         // C11 6.5.1.1p2 "No two generic associations in the same generic
1697         // selection shall specify compatible types."
1698         for (unsigned j = i+1; j < NumAssocs; ++j)
1699           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1700               Context.typesAreCompatible(Types[i]->getType(),
1701                                          Types[j]->getType())) {
1702             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1703                  diag::err_assoc_compatible_types)
1704               << Types[j]->getTypeLoc().getSourceRange()
1705               << Types[j]->getType()
1706               << Types[i]->getType();
1707             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1708                  diag::note_compat_assoc)
1709               << Types[i]->getTypeLoc().getSourceRange()
1710               << Types[i]->getType();
1711             TypeErrorFound = true;
1712           }
1713       }
1714     }
1715   }
1716   if (TypeErrorFound)
1717     return ExprError();
1718 
1719   // If we determined that the generic selection is result-dependent, don't
1720   // try to compute the result expression.
1721   if (IsResultDependent)
1722     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1723                                         Exprs, DefaultLoc, RParenLoc,
1724                                         ContainsUnexpandedParameterPack);
1725 
1726   SmallVector<unsigned, 1> CompatIndices;
1727   unsigned DefaultIndex = -1U;
1728   for (unsigned i = 0; i < NumAssocs; ++i) {
1729     if (!Types[i])
1730       DefaultIndex = i;
1731     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1732                                         Types[i]->getType()))
1733       CompatIndices.push_back(i);
1734   }
1735 
1736   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1737   // type compatible with at most one of the types named in its generic
1738   // association list."
1739   if (CompatIndices.size() > 1) {
1740     // We strip parens here because the controlling expression is typically
1741     // parenthesized in macro definitions.
1742     ControllingExpr = ControllingExpr->IgnoreParens();
1743     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1744         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1745         << (unsigned)CompatIndices.size();
1746     for (unsigned I : CompatIndices) {
1747       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1748            diag::note_compat_assoc)
1749         << Types[I]->getTypeLoc().getSourceRange()
1750         << Types[I]->getType();
1751     }
1752     return ExprError();
1753   }
1754 
1755   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1756   // its controlling expression shall have type compatible with exactly one of
1757   // the types named in its generic association list."
1758   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1759     // We strip parens here because the controlling expression is typically
1760     // parenthesized in macro definitions.
1761     ControllingExpr = ControllingExpr->IgnoreParens();
1762     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1763         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1764     return ExprError();
1765   }
1766 
1767   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1768   // type name that is compatible with the type of the controlling expression,
1769   // then the result expression of the generic selection is the expression
1770   // in that generic association. Otherwise, the result expression of the
1771   // generic selection is the expression in the default generic association."
1772   unsigned ResultIndex =
1773     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1774 
1775   return GenericSelectionExpr::Create(
1776       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1777       ContainsUnexpandedParameterPack, ResultIndex);
1778 }
1779 
1780 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1781 /// location of the token and the offset of the ud-suffix within it.
1782 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1783                                      unsigned Offset) {
1784   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1785                                         S.getLangOpts());
1786 }
1787 
1788 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1789 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1790 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1791                                                  IdentifierInfo *UDSuffix,
1792                                                  SourceLocation UDSuffixLoc,
1793                                                  ArrayRef<Expr*> Args,
1794                                                  SourceLocation LitEndLoc) {
1795   assert(Args.size() <= 2 && "too many arguments for literal operator");
1796 
1797   QualType ArgTy[2];
1798   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1799     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1800     if (ArgTy[ArgIdx]->isArrayType())
1801       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1802   }
1803 
1804   DeclarationName OpName =
1805     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1806   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1807   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1808 
1809   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1810   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1811                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1812                               /*AllowStringTemplatePack*/ false,
1813                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1814     return ExprError();
1815 
1816   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1817 }
1818 
1819 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1820 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1821 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1822 /// multiple tokens.  However, the common case is that StringToks points to one
1823 /// string.
1824 ///
1825 ExprResult
1826 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1827   assert(!StringToks.empty() && "Must have at least one string!");
1828 
1829   StringLiteralParser Literal(StringToks, PP);
1830   if (Literal.hadError)
1831     return ExprError();
1832 
1833   SmallVector<SourceLocation, 4> StringTokLocs;
1834   for (const Token &Tok : StringToks)
1835     StringTokLocs.push_back(Tok.getLocation());
1836 
1837   QualType CharTy = Context.CharTy;
1838   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1839   if (Literal.isWide()) {
1840     CharTy = Context.getWideCharType();
1841     Kind = StringLiteral::Wide;
1842   } else if (Literal.isUTF8()) {
1843     if (getLangOpts().Char8)
1844       CharTy = Context.Char8Ty;
1845     Kind = StringLiteral::UTF8;
1846   } else if (Literal.isUTF16()) {
1847     CharTy = Context.Char16Ty;
1848     Kind = StringLiteral::UTF16;
1849   } else if (Literal.isUTF32()) {
1850     CharTy = Context.Char32Ty;
1851     Kind = StringLiteral::UTF32;
1852   } else if (Literal.isPascal()) {
1853     CharTy = Context.UnsignedCharTy;
1854   }
1855 
1856   // Warn on initializing an array of char from a u8 string literal; this
1857   // becomes ill-formed in C++2a.
1858   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1859       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1860     Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1861 
1862     // Create removals for all 'u8' prefixes in the string literal(s). This
1863     // ensures C++2a compatibility (but may change the program behavior when
1864     // built by non-Clang compilers for which the execution character set is
1865     // not always UTF-8).
1866     auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1867     SourceLocation RemovalDiagLoc;
1868     for (const Token &Tok : StringToks) {
1869       if (Tok.getKind() == tok::utf8_string_literal) {
1870         if (RemovalDiagLoc.isInvalid())
1871           RemovalDiagLoc = Tok.getLocation();
1872         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1873             Tok.getLocation(),
1874             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1875                                            getSourceManager(), getLangOpts())));
1876       }
1877     }
1878     Diag(RemovalDiagLoc, RemovalDiag);
1879   }
1880 
1881   QualType StrTy =
1882       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1883 
1884   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1885   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1886                                              Kind, Literal.Pascal, StrTy,
1887                                              &StringTokLocs[0],
1888                                              StringTokLocs.size());
1889   if (Literal.getUDSuffix().empty())
1890     return Lit;
1891 
1892   // We're building a user-defined literal.
1893   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1894   SourceLocation UDSuffixLoc =
1895     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1896                    Literal.getUDSuffixOffset());
1897 
1898   // Make sure we're allowed user-defined literals here.
1899   if (!UDLScope)
1900     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1901 
1902   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1903   //   operator "" X (str, len)
1904   QualType SizeType = Context.getSizeType();
1905 
1906   DeclarationName OpName =
1907     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1908   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1909   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1910 
1911   QualType ArgTy[] = {
1912     Context.getArrayDecayedType(StrTy), SizeType
1913   };
1914 
1915   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1916   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1917                                 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1918                                 /*AllowStringTemplatePack*/ true,
1919                                 /*DiagnoseMissing*/ true, Lit)) {
1920 
1921   case LOLR_Cooked: {
1922     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1923     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1924                                                     StringTokLocs[0]);
1925     Expr *Args[] = { Lit, LenArg };
1926 
1927     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1928   }
1929 
1930   case LOLR_Template: {
1931     TemplateArgumentListInfo ExplicitArgs;
1932     TemplateArgument Arg(Lit);
1933     TemplateArgumentLocInfo ArgInfo(Lit);
1934     ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1935     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1936                                     &ExplicitArgs);
1937   }
1938 
1939   case LOLR_StringTemplatePack: {
1940     TemplateArgumentListInfo ExplicitArgs;
1941 
1942     unsigned CharBits = Context.getIntWidth(CharTy);
1943     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1944     llvm::APSInt Value(CharBits, CharIsUnsigned);
1945 
1946     TemplateArgument TypeArg(CharTy);
1947     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1948     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1949 
1950     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1951       Value = Lit->getCodeUnit(I);
1952       TemplateArgument Arg(Context, Value, CharTy);
1953       TemplateArgumentLocInfo ArgInfo;
1954       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1955     }
1956     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1957                                     &ExplicitArgs);
1958   }
1959   case LOLR_Raw:
1960   case LOLR_ErrorNoDiagnostic:
1961     llvm_unreachable("unexpected literal operator lookup result");
1962   case LOLR_Error:
1963     return ExprError();
1964   }
1965   llvm_unreachable("unexpected literal operator lookup result");
1966 }
1967 
1968 DeclRefExpr *
1969 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1970                        SourceLocation Loc,
1971                        const CXXScopeSpec *SS) {
1972   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1973   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1974 }
1975 
1976 DeclRefExpr *
1977 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1978                        const DeclarationNameInfo &NameInfo,
1979                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1980                        SourceLocation TemplateKWLoc,
1981                        const TemplateArgumentListInfo *TemplateArgs) {
1982   NestedNameSpecifierLoc NNS =
1983       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1984   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1985                           TemplateArgs);
1986 }
1987 
1988 // CUDA/HIP: Check whether a captured reference variable is referencing a
1989 // host variable in a device or host device lambda.
1990 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1991                                                             VarDecl *VD) {
1992   if (!S.getLangOpts().CUDA || !VD->hasInit())
1993     return false;
1994   assert(VD->getType()->isReferenceType());
1995 
1996   // Check whether the reference variable is referencing a host variable.
1997   auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1998   if (!DRE)
1999     return false;
2000   auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2001   if (!Referee || !Referee->hasGlobalStorage() ||
2002       Referee->hasAttr<CUDADeviceAttr>())
2003     return false;
2004 
2005   // Check whether the current function is a device or host device lambda.
2006   // Check whether the reference variable is a capture by getDeclContext()
2007   // since refersToEnclosingVariableOrCapture() is not ready at this point.
2008   auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2009   if (MD && MD->getParent()->isLambda() &&
2010       MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2011       VD->getDeclContext() != MD)
2012     return true;
2013 
2014   return false;
2015 }
2016 
2017 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2018   // A declaration named in an unevaluated operand never constitutes an odr-use.
2019   if (isUnevaluatedContext())
2020     return NOUR_Unevaluated;
2021 
2022   // C++2a [basic.def.odr]p4:
2023   //   A variable x whose name appears as a potentially-evaluated expression e
2024   //   is odr-used by e unless [...] x is a reference that is usable in
2025   //   constant expressions.
2026   // CUDA/HIP:
2027   //   If a reference variable referencing a host variable is captured in a
2028   //   device or host device lambda, the value of the referee must be copied
2029   //   to the capture and the reference variable must be treated as odr-use
2030   //   since the value of the referee is not known at compile time and must
2031   //   be loaded from the captured.
2032   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2033     if (VD->getType()->isReferenceType() &&
2034         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2035         !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2036         VD->isUsableInConstantExpressions(Context))
2037       return NOUR_Constant;
2038   }
2039 
2040   // All remaining non-variable cases constitute an odr-use. For variables, we
2041   // need to wait and see how the expression is used.
2042   return NOUR_None;
2043 }
2044 
2045 /// BuildDeclRefExpr - Build an expression that references a
2046 /// declaration that does not require a closure capture.
2047 DeclRefExpr *
2048 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2049                        const DeclarationNameInfo &NameInfo,
2050                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2051                        SourceLocation TemplateKWLoc,
2052                        const TemplateArgumentListInfo *TemplateArgs) {
2053   bool RefersToCapturedVariable =
2054       isa<VarDecl>(D) &&
2055       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2056 
2057   DeclRefExpr *E = DeclRefExpr::Create(
2058       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2059       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2060   MarkDeclRefReferenced(E);
2061 
2062   // C++ [except.spec]p17:
2063   //   An exception-specification is considered to be needed when:
2064   //   - in an expression, the function is the unique lookup result or
2065   //     the selected member of a set of overloaded functions.
2066   //
2067   // We delay doing this until after we've built the function reference and
2068   // marked it as used so that:
2069   //  a) if the function is defaulted, we get errors from defining it before /
2070   //     instead of errors from computing its exception specification, and
2071   //  b) if the function is a defaulted comparison, we can use the body we
2072   //     build when defining it as input to the exception specification
2073   //     computation rather than computing a new body.
2074   if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2075     if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2076       if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2077         E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2078     }
2079   }
2080 
2081   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2082       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2083       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2084     getCurFunction()->recordUseOfWeak(E);
2085 
2086   FieldDecl *FD = dyn_cast<FieldDecl>(D);
2087   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2088     FD = IFD->getAnonField();
2089   if (FD) {
2090     UnusedPrivateFields.remove(FD);
2091     // Just in case we're building an illegal pointer-to-member.
2092     if (FD->isBitField())
2093       E->setObjectKind(OK_BitField);
2094   }
2095 
2096   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2097   // designates a bit-field.
2098   if (auto *BD = dyn_cast<BindingDecl>(D))
2099     if (auto *BE = BD->getBinding())
2100       E->setObjectKind(BE->getObjectKind());
2101 
2102   return E;
2103 }
2104 
2105 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2106 /// possibly a list of template arguments.
2107 ///
2108 /// If this produces template arguments, it is permitted to call
2109 /// DecomposeTemplateName.
2110 ///
2111 /// This actually loses a lot of source location information for
2112 /// non-standard name kinds; we should consider preserving that in
2113 /// some way.
2114 void
2115 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2116                              TemplateArgumentListInfo &Buffer,
2117                              DeclarationNameInfo &NameInfo,
2118                              const TemplateArgumentListInfo *&TemplateArgs) {
2119   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2120     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2121     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2122 
2123     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2124                                        Id.TemplateId->NumArgs);
2125     translateTemplateArguments(TemplateArgsPtr, Buffer);
2126 
2127     TemplateName TName = Id.TemplateId->Template.get();
2128     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2129     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2130     TemplateArgs = &Buffer;
2131   } else {
2132     NameInfo = GetNameFromUnqualifiedId(Id);
2133     TemplateArgs = nullptr;
2134   }
2135 }
2136 
2137 static void emitEmptyLookupTypoDiagnostic(
2138     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2139     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2140     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2141   DeclContext *Ctx =
2142       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2143   if (!TC) {
2144     // Emit a special diagnostic for failed member lookups.
2145     // FIXME: computing the declaration context might fail here (?)
2146     if (Ctx)
2147       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2148                                                  << SS.getRange();
2149     else
2150       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2151     return;
2152   }
2153 
2154   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2155   bool DroppedSpecifier =
2156       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2157   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2158                         ? diag::note_implicit_param_decl
2159                         : diag::note_previous_decl;
2160   if (!Ctx)
2161     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2162                          SemaRef.PDiag(NoteID));
2163   else
2164     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2165                                  << Typo << Ctx << DroppedSpecifier
2166                                  << SS.getRange(),
2167                          SemaRef.PDiag(NoteID));
2168 }
2169 
2170 /// Diagnose a lookup that found results in an enclosing class during error
2171 /// recovery. This usually indicates that the results were found in a dependent
2172 /// base class that could not be searched as part of a template definition.
2173 /// Always issues a diagnostic (though this may be only a warning in MS
2174 /// compatibility mode).
2175 ///
2176 /// Return \c true if the error is unrecoverable, or \c false if the caller
2177 /// should attempt to recover using these lookup results.
2178 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2179   // During a default argument instantiation the CurContext points
2180   // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2181   // function parameter list, hence add an explicit check.
2182   bool isDefaultArgument =
2183       !CodeSynthesisContexts.empty() &&
2184       CodeSynthesisContexts.back().Kind ==
2185           CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2186   CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2187   bool isInstance = CurMethod && CurMethod->isInstance() &&
2188                     R.getNamingClass() == CurMethod->getParent() &&
2189                     !isDefaultArgument;
2190 
2191   // There are two ways we can find a class-scope declaration during template
2192   // instantiation that we did not find in the template definition: if it is a
2193   // member of a dependent base class, or if it is declared after the point of
2194   // use in the same class. Distinguish these by comparing the class in which
2195   // the member was found to the naming class of the lookup.
2196   unsigned DiagID = diag::err_found_in_dependent_base;
2197   unsigned NoteID = diag::note_member_declared_at;
2198   if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2199     DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2200                                       : diag::err_found_later_in_class;
2201   } else if (getLangOpts().MSVCCompat) {
2202     DiagID = diag::ext_found_in_dependent_base;
2203     NoteID = diag::note_dependent_member_use;
2204   }
2205 
2206   if (isInstance) {
2207     // Give a code modification hint to insert 'this->'.
2208     Diag(R.getNameLoc(), DiagID)
2209         << R.getLookupName()
2210         << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2211     CheckCXXThisCapture(R.getNameLoc());
2212   } else {
2213     // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2214     // they're not shadowed).
2215     Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2216   }
2217 
2218   for (NamedDecl *D : R)
2219     Diag(D->getLocation(), NoteID);
2220 
2221   // Return true if we are inside a default argument instantiation
2222   // and the found name refers to an instance member function, otherwise
2223   // the caller will try to create an implicit member call and this is wrong
2224   // for default arguments.
2225   //
2226   // FIXME: Is this special case necessary? We could allow the caller to
2227   // diagnose this.
2228   if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2229     Diag(R.getNameLoc(), diag::err_member_call_without_object);
2230     return true;
2231   }
2232 
2233   // Tell the callee to try to recover.
2234   return false;
2235 }
2236 
2237 /// Diagnose an empty lookup.
2238 ///
2239 /// \return false if new lookup candidates were found
2240 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2241                                CorrectionCandidateCallback &CCC,
2242                                TemplateArgumentListInfo *ExplicitTemplateArgs,
2243                                ArrayRef<Expr *> Args, TypoExpr **Out) {
2244   DeclarationName Name = R.getLookupName();
2245 
2246   unsigned diagnostic = diag::err_undeclared_var_use;
2247   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2248   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2249       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2250       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2251     diagnostic = diag::err_undeclared_use;
2252     diagnostic_suggest = diag::err_undeclared_use_suggest;
2253   }
2254 
2255   // If the original lookup was an unqualified lookup, fake an
2256   // unqualified lookup.  This is useful when (for example) the
2257   // original lookup would not have found something because it was a
2258   // dependent name.
2259   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2260   while (DC) {
2261     if (isa<CXXRecordDecl>(DC)) {
2262       LookupQualifiedName(R, DC);
2263 
2264       if (!R.empty()) {
2265         // Don't give errors about ambiguities in this lookup.
2266         R.suppressDiagnostics();
2267 
2268         // If there's a best viable function among the results, only mention
2269         // that one in the notes.
2270         OverloadCandidateSet Candidates(R.getNameLoc(),
2271                                         OverloadCandidateSet::CSK_Normal);
2272         AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2273         OverloadCandidateSet::iterator Best;
2274         if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2275             OR_Success) {
2276           R.clear();
2277           R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2278           R.resolveKind();
2279         }
2280 
2281         return DiagnoseDependentMemberLookup(R);
2282       }
2283 
2284       R.clear();
2285     }
2286 
2287     DC = DC->getLookupParent();
2288   }
2289 
2290   // We didn't find anything, so try to correct for a typo.
2291   TypoCorrection Corrected;
2292   if (S && Out) {
2293     SourceLocation TypoLoc = R.getNameLoc();
2294     assert(!ExplicitTemplateArgs &&
2295            "Diagnosing an empty lookup with explicit template args!");
2296     *Out = CorrectTypoDelayed(
2297         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2298         [=](const TypoCorrection &TC) {
2299           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2300                                         diagnostic, diagnostic_suggest);
2301         },
2302         nullptr, CTK_ErrorRecovery);
2303     if (*Out)
2304       return true;
2305   } else if (S &&
2306              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2307                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2308     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2309     bool DroppedSpecifier =
2310         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2311     R.setLookupName(Corrected.getCorrection());
2312 
2313     bool AcceptableWithRecovery = false;
2314     bool AcceptableWithoutRecovery = false;
2315     NamedDecl *ND = Corrected.getFoundDecl();
2316     if (ND) {
2317       if (Corrected.isOverloaded()) {
2318         OverloadCandidateSet OCS(R.getNameLoc(),
2319                                  OverloadCandidateSet::CSK_Normal);
2320         OverloadCandidateSet::iterator Best;
2321         for (NamedDecl *CD : Corrected) {
2322           if (FunctionTemplateDecl *FTD =
2323                    dyn_cast<FunctionTemplateDecl>(CD))
2324             AddTemplateOverloadCandidate(
2325                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2326                 Args, OCS);
2327           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2328             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2329               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2330                                    Args, OCS);
2331         }
2332         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2333         case OR_Success:
2334           ND = Best->FoundDecl;
2335           Corrected.setCorrectionDecl(ND);
2336           break;
2337         default:
2338           // FIXME: Arbitrarily pick the first declaration for the note.
2339           Corrected.setCorrectionDecl(ND);
2340           break;
2341         }
2342       }
2343       R.addDecl(ND);
2344       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2345         CXXRecordDecl *Record = nullptr;
2346         if (Corrected.getCorrectionSpecifier()) {
2347           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2348           Record = Ty->getAsCXXRecordDecl();
2349         }
2350         if (!Record)
2351           Record = cast<CXXRecordDecl>(
2352               ND->getDeclContext()->getRedeclContext());
2353         R.setNamingClass(Record);
2354       }
2355 
2356       auto *UnderlyingND = ND->getUnderlyingDecl();
2357       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2358                                isa<FunctionTemplateDecl>(UnderlyingND);
2359       // FIXME: If we ended up with a typo for a type name or
2360       // Objective-C class name, we're in trouble because the parser
2361       // is in the wrong place to recover. Suggest the typo
2362       // correction, but don't make it a fix-it since we're not going
2363       // to recover well anyway.
2364       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2365                                   getAsTypeTemplateDecl(UnderlyingND) ||
2366                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2367     } else {
2368       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2369       // because we aren't able to recover.
2370       AcceptableWithoutRecovery = true;
2371     }
2372 
2373     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2374       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2375                             ? diag::note_implicit_param_decl
2376                             : diag::note_previous_decl;
2377       if (SS.isEmpty())
2378         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2379                      PDiag(NoteID), AcceptableWithRecovery);
2380       else
2381         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2382                                   << Name << computeDeclContext(SS, false)
2383                                   << DroppedSpecifier << SS.getRange(),
2384                      PDiag(NoteID), AcceptableWithRecovery);
2385 
2386       // Tell the callee whether to try to recover.
2387       return !AcceptableWithRecovery;
2388     }
2389   }
2390   R.clear();
2391 
2392   // Emit a special diagnostic for failed member lookups.
2393   // FIXME: computing the declaration context might fail here (?)
2394   if (!SS.isEmpty()) {
2395     Diag(R.getNameLoc(), diag::err_no_member)
2396       << Name << computeDeclContext(SS, false)
2397       << SS.getRange();
2398     return true;
2399   }
2400 
2401   // Give up, we can't recover.
2402   Diag(R.getNameLoc(), diagnostic) << Name;
2403   return true;
2404 }
2405 
2406 /// In Microsoft mode, if we are inside a template class whose parent class has
2407 /// dependent base classes, and we can't resolve an unqualified identifier, then
2408 /// assume the identifier is a member of a dependent base class.  We can only
2409 /// recover successfully in static methods, instance methods, and other contexts
2410 /// where 'this' is available.  This doesn't precisely match MSVC's
2411 /// instantiation model, but it's close enough.
2412 static Expr *
2413 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2414                                DeclarationNameInfo &NameInfo,
2415                                SourceLocation TemplateKWLoc,
2416                                const TemplateArgumentListInfo *TemplateArgs) {
2417   // Only try to recover from lookup into dependent bases in static methods or
2418   // contexts where 'this' is available.
2419   QualType ThisType = S.getCurrentThisType();
2420   const CXXRecordDecl *RD = nullptr;
2421   if (!ThisType.isNull())
2422     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2423   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2424     RD = MD->getParent();
2425   if (!RD || !RD->hasAnyDependentBases())
2426     return nullptr;
2427 
2428   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2429   // is available, suggest inserting 'this->' as a fixit.
2430   SourceLocation Loc = NameInfo.getLoc();
2431   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2432   DB << NameInfo.getName() << RD;
2433 
2434   if (!ThisType.isNull()) {
2435     DB << FixItHint::CreateInsertion(Loc, "this->");
2436     return CXXDependentScopeMemberExpr::Create(
2437         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2438         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2439         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2440   }
2441 
2442   // Synthesize a fake NNS that points to the derived class.  This will
2443   // perform name lookup during template instantiation.
2444   CXXScopeSpec SS;
2445   auto *NNS =
2446       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2447   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2448   return DependentScopeDeclRefExpr::Create(
2449       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2450       TemplateArgs);
2451 }
2452 
2453 ExprResult
2454 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2455                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2456                         bool HasTrailingLParen, bool IsAddressOfOperand,
2457                         CorrectionCandidateCallback *CCC,
2458                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2459   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2460          "cannot be direct & operand and have a trailing lparen");
2461   if (SS.isInvalid())
2462     return ExprError();
2463 
2464   TemplateArgumentListInfo TemplateArgsBuffer;
2465 
2466   // Decompose the UnqualifiedId into the following data.
2467   DeclarationNameInfo NameInfo;
2468   const TemplateArgumentListInfo *TemplateArgs;
2469   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2470 
2471   DeclarationName Name = NameInfo.getName();
2472   IdentifierInfo *II = Name.getAsIdentifierInfo();
2473   SourceLocation NameLoc = NameInfo.getLoc();
2474 
2475   if (II && II->isEditorPlaceholder()) {
2476     // FIXME: When typed placeholders are supported we can create a typed
2477     // placeholder expression node.
2478     return ExprError();
2479   }
2480 
2481   // C++ [temp.dep.expr]p3:
2482   //   An id-expression is type-dependent if it contains:
2483   //     -- an identifier that was declared with a dependent type,
2484   //        (note: handled after lookup)
2485   //     -- a template-id that is dependent,
2486   //        (note: handled in BuildTemplateIdExpr)
2487   //     -- a conversion-function-id that specifies a dependent type,
2488   //     -- a nested-name-specifier that contains a class-name that
2489   //        names a dependent type.
2490   // Determine whether this is a member of an unknown specialization;
2491   // we need to handle these differently.
2492   bool DependentID = false;
2493   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2494       Name.getCXXNameType()->isDependentType()) {
2495     DependentID = true;
2496   } else if (SS.isSet()) {
2497     if (DeclContext *DC = computeDeclContext(SS, false)) {
2498       if (RequireCompleteDeclContext(SS, DC))
2499         return ExprError();
2500     } else {
2501       DependentID = true;
2502     }
2503   }
2504 
2505   if (DependentID)
2506     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2507                                       IsAddressOfOperand, TemplateArgs);
2508 
2509   // Perform the required lookup.
2510   LookupResult R(*this, NameInfo,
2511                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2512                      ? LookupObjCImplicitSelfParam
2513                      : LookupOrdinaryName);
2514   if (TemplateKWLoc.isValid() || TemplateArgs) {
2515     // Lookup the template name again to correctly establish the context in
2516     // which it was found. This is really unfortunate as we already did the
2517     // lookup to determine that it was a template name in the first place. If
2518     // this becomes a performance hit, we can work harder to preserve those
2519     // results until we get here but it's likely not worth it.
2520     bool MemberOfUnknownSpecialization;
2521     AssumedTemplateKind AssumedTemplate;
2522     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2523                            MemberOfUnknownSpecialization, TemplateKWLoc,
2524                            &AssumedTemplate))
2525       return ExprError();
2526 
2527     if (MemberOfUnknownSpecialization ||
2528         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2529       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2530                                         IsAddressOfOperand, TemplateArgs);
2531   } else {
2532     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2533     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2534 
2535     // If the result might be in a dependent base class, this is a dependent
2536     // id-expression.
2537     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2538       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2539                                         IsAddressOfOperand, TemplateArgs);
2540 
2541     // If this reference is in an Objective-C method, then we need to do
2542     // some special Objective-C lookup, too.
2543     if (IvarLookupFollowUp) {
2544       ExprResult E(LookupInObjCMethod(R, S, II, true));
2545       if (E.isInvalid())
2546         return ExprError();
2547 
2548       if (Expr *Ex = E.getAs<Expr>())
2549         return Ex;
2550     }
2551   }
2552 
2553   if (R.isAmbiguous())
2554     return ExprError();
2555 
2556   // This could be an implicitly declared function reference (legal in C90,
2557   // extension in C99, forbidden in C++ and C2x).
2558   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus &&
2559       !getLangOpts().C2x) {
2560     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2561     if (D) R.addDecl(D);
2562   }
2563 
2564   // Determine whether this name might be a candidate for
2565   // argument-dependent lookup.
2566   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2567 
2568   if (R.empty() && !ADL) {
2569     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2570       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2571                                                    TemplateKWLoc, TemplateArgs))
2572         return E;
2573     }
2574 
2575     // Don't diagnose an empty lookup for inline assembly.
2576     if (IsInlineAsmIdentifier)
2577       return ExprError();
2578 
2579     // If this name wasn't predeclared and if this is not a function
2580     // call, diagnose the problem.
2581     TypoExpr *TE = nullptr;
2582     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2583                                                        : nullptr);
2584     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2585     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2586            "Typo correction callback misconfigured");
2587     if (CCC) {
2588       // Make sure the callback knows what the typo being diagnosed is.
2589       CCC->setTypoName(II);
2590       if (SS.isValid())
2591         CCC->setTypoNNS(SS.getScopeRep());
2592     }
2593     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2594     // a template name, but we happen to have always already looked up the name
2595     // before we get here if it must be a template name.
2596     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2597                             None, &TE)) {
2598       if (TE && KeywordReplacement) {
2599         auto &State = getTypoExprState(TE);
2600         auto BestTC = State.Consumer->getNextCorrection();
2601         if (BestTC.isKeyword()) {
2602           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2603           if (State.DiagHandler)
2604             State.DiagHandler(BestTC);
2605           KeywordReplacement->startToken();
2606           KeywordReplacement->setKind(II->getTokenID());
2607           KeywordReplacement->setIdentifierInfo(II);
2608           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2609           // Clean up the state associated with the TypoExpr, since it has
2610           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2611           clearDelayedTypo(TE);
2612           // Signal that a correction to a keyword was performed by returning a
2613           // valid-but-null ExprResult.
2614           return (Expr*)nullptr;
2615         }
2616         State.Consumer->resetCorrectionStream();
2617       }
2618       return TE ? TE : ExprError();
2619     }
2620 
2621     assert(!R.empty() &&
2622            "DiagnoseEmptyLookup returned false but added no results");
2623 
2624     // If we found an Objective-C instance variable, let
2625     // LookupInObjCMethod build the appropriate expression to
2626     // reference the ivar.
2627     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2628       R.clear();
2629       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2630       // In a hopelessly buggy code, Objective-C instance variable
2631       // lookup fails and no expression will be built to reference it.
2632       if (!E.isInvalid() && !E.get())
2633         return ExprError();
2634       return E;
2635     }
2636   }
2637 
2638   // This is guaranteed from this point on.
2639   assert(!R.empty() || ADL);
2640 
2641   // Check whether this might be a C++ implicit instance member access.
2642   // C++ [class.mfct.non-static]p3:
2643   //   When an id-expression that is not part of a class member access
2644   //   syntax and not used to form a pointer to member is used in the
2645   //   body of a non-static member function of class X, if name lookup
2646   //   resolves the name in the id-expression to a non-static non-type
2647   //   member of some class C, the id-expression is transformed into a
2648   //   class member access expression using (*this) as the
2649   //   postfix-expression to the left of the . operator.
2650   //
2651   // But we don't actually need to do this for '&' operands if R
2652   // resolved to a function or overloaded function set, because the
2653   // expression is ill-formed if it actually works out to be a
2654   // non-static member function:
2655   //
2656   // C++ [expr.ref]p4:
2657   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2658   //   [t]he expression can be used only as the left-hand operand of a
2659   //   member function call.
2660   //
2661   // There are other safeguards against such uses, but it's important
2662   // to get this right here so that we don't end up making a
2663   // spuriously dependent expression if we're inside a dependent
2664   // instance method.
2665   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2666     bool MightBeImplicitMember;
2667     if (!IsAddressOfOperand)
2668       MightBeImplicitMember = true;
2669     else if (!SS.isEmpty())
2670       MightBeImplicitMember = false;
2671     else if (R.isOverloadedResult())
2672       MightBeImplicitMember = false;
2673     else if (R.isUnresolvableResult())
2674       MightBeImplicitMember = true;
2675     else
2676       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2677                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2678                               isa<MSPropertyDecl>(R.getFoundDecl());
2679 
2680     if (MightBeImplicitMember)
2681       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2682                                              R, TemplateArgs, S);
2683   }
2684 
2685   if (TemplateArgs || TemplateKWLoc.isValid()) {
2686 
2687     // In C++1y, if this is a variable template id, then check it
2688     // in BuildTemplateIdExpr().
2689     // The single lookup result must be a variable template declaration.
2690     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2691         Id.TemplateId->Kind == TNK_Var_template) {
2692       assert(R.getAsSingle<VarTemplateDecl>() &&
2693              "There should only be one declaration found.");
2694     }
2695 
2696     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2697   }
2698 
2699   return BuildDeclarationNameExpr(SS, R, ADL);
2700 }
2701 
2702 ExprResult Sema::ActOnMutableAgnosticIdExpression(Scope *S, CXXScopeSpec &SS,
2703                                                   UnqualifiedId &Id) {
2704   MutableAgnosticContextRAII Ctx(*this);
2705   return ActOnIdExpression(S, SS, /*TemplateKwLoc*/
2706                            SourceLocation(), Id,
2707                            /*HasTrailingLParen*/ false,
2708                            /*IsAddressOfOperand*/ false,
2709                            /*CorrectionCandidateCallback*/ nullptr,
2710                            /*IsInlineAsmIdentifier*/ false,
2711                            /*KeywordReplacement*/ nullptr);
2712 }
2713 
2714 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2715 /// declaration name, generally during template instantiation.
2716 /// There's a large number of things which don't need to be done along
2717 /// this path.
2718 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2719     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2720     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2721   DeclContext *DC = computeDeclContext(SS, false);
2722   if (!DC)
2723     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2724                                      NameInfo, /*TemplateArgs=*/nullptr);
2725 
2726   if (RequireCompleteDeclContext(SS, DC))
2727     return ExprError();
2728 
2729   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2730   LookupQualifiedName(R, DC);
2731 
2732   if (R.isAmbiguous())
2733     return ExprError();
2734 
2735   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2736     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2737                                      NameInfo, /*TemplateArgs=*/nullptr);
2738 
2739   if (R.empty()) {
2740     // Don't diagnose problems with invalid record decl, the secondary no_member
2741     // diagnostic during template instantiation is likely bogus, e.g. if a class
2742     // is invalid because it's derived from an invalid base class, then missing
2743     // members were likely supposed to be inherited.
2744     if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2745       if (CD->isInvalidDecl())
2746         return ExprError();
2747     Diag(NameInfo.getLoc(), diag::err_no_member)
2748       << NameInfo.getName() << DC << SS.getRange();
2749     return ExprError();
2750   }
2751 
2752   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2753     // Diagnose a missing typename if this resolved unambiguously to a type in
2754     // a dependent context.  If we can recover with a type, downgrade this to
2755     // a warning in Microsoft compatibility mode.
2756     unsigned DiagID = diag::err_typename_missing;
2757     if (RecoveryTSI && getLangOpts().MSVCCompat)
2758       DiagID = diag::ext_typename_missing;
2759     SourceLocation Loc = SS.getBeginLoc();
2760     auto D = Diag(Loc, DiagID);
2761     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2762       << SourceRange(Loc, NameInfo.getEndLoc());
2763 
2764     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2765     // context.
2766     if (!RecoveryTSI)
2767       return ExprError();
2768 
2769     // Only issue the fixit if we're prepared to recover.
2770     D << FixItHint::CreateInsertion(Loc, "typename ");
2771 
2772     // Recover by pretending this was an elaborated type.
2773     QualType Ty = Context.getTypeDeclType(TD);
2774     TypeLocBuilder TLB;
2775     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2776 
2777     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2778     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2779     QTL.setElaboratedKeywordLoc(SourceLocation());
2780     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2781 
2782     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2783 
2784     return ExprEmpty();
2785   }
2786 
2787   // Defend against this resolving to an implicit member access. We usually
2788   // won't get here if this might be a legitimate a class member (we end up in
2789   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2790   // a pointer-to-member or in an unevaluated context in C++11.
2791   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2792     return BuildPossibleImplicitMemberExpr(SS,
2793                                            /*TemplateKWLoc=*/SourceLocation(),
2794                                            R, /*TemplateArgs=*/nullptr, S);
2795 
2796   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2797 }
2798 
2799 /// The parser has read a name in, and Sema has detected that we're currently
2800 /// inside an ObjC method. Perform some additional checks and determine if we
2801 /// should form a reference to an ivar.
2802 ///
2803 /// Ideally, most of this would be done by lookup, but there's
2804 /// actually quite a lot of extra work involved.
2805 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2806                                         IdentifierInfo *II) {
2807   SourceLocation Loc = Lookup.getNameLoc();
2808   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2809 
2810   // Check for error condition which is already reported.
2811   if (!CurMethod)
2812     return DeclResult(true);
2813 
2814   // There are two cases to handle here.  1) scoped lookup could have failed,
2815   // in which case we should look for an ivar.  2) scoped lookup could have
2816   // found a decl, but that decl is outside the current instance method (i.e.
2817   // a global variable).  In these two cases, we do a lookup for an ivar with
2818   // this name, if the lookup sucedes, we replace it our current decl.
2819 
2820   // If we're in a class method, we don't normally want to look for
2821   // ivars.  But if we don't find anything else, and there's an
2822   // ivar, that's an error.
2823   bool IsClassMethod = CurMethod->isClassMethod();
2824 
2825   bool LookForIvars;
2826   if (Lookup.empty())
2827     LookForIvars = true;
2828   else if (IsClassMethod)
2829     LookForIvars = false;
2830   else
2831     LookForIvars = (Lookup.isSingleResult() &&
2832                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2833   ObjCInterfaceDecl *IFace = nullptr;
2834   if (LookForIvars) {
2835     IFace = CurMethod->getClassInterface();
2836     ObjCInterfaceDecl *ClassDeclared;
2837     ObjCIvarDecl *IV = nullptr;
2838     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2839       // Diagnose using an ivar in a class method.
2840       if (IsClassMethod) {
2841         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2842         return DeclResult(true);
2843       }
2844 
2845       // Diagnose the use of an ivar outside of the declaring class.
2846       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2847           !declaresSameEntity(ClassDeclared, IFace) &&
2848           !getLangOpts().DebuggerSupport)
2849         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2850 
2851       // Success.
2852       return IV;
2853     }
2854   } else if (CurMethod->isInstanceMethod()) {
2855     // We should warn if a local variable hides an ivar.
2856     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2857       ObjCInterfaceDecl *ClassDeclared;
2858       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2859         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2860             declaresSameEntity(IFace, ClassDeclared))
2861           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2862       }
2863     }
2864   } else if (Lookup.isSingleResult() &&
2865              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2866     // If accessing a stand-alone ivar in a class method, this is an error.
2867     if (const ObjCIvarDecl *IV =
2868             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2869       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2870       return DeclResult(true);
2871     }
2872   }
2873 
2874   // Didn't encounter an error, didn't find an ivar.
2875   return DeclResult(false);
2876 }
2877 
2878 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2879                                   ObjCIvarDecl *IV) {
2880   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2881   assert(CurMethod && CurMethod->isInstanceMethod() &&
2882          "should not reference ivar from this context");
2883 
2884   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2885   assert(IFace && "should not reference ivar from this context");
2886 
2887   // If we're referencing an invalid decl, just return this as a silent
2888   // error node.  The error diagnostic was already emitted on the decl.
2889   if (IV->isInvalidDecl())
2890     return ExprError();
2891 
2892   // Check if referencing a field with __attribute__((deprecated)).
2893   if (DiagnoseUseOfDecl(IV, Loc))
2894     return ExprError();
2895 
2896   // FIXME: This should use a new expr for a direct reference, don't
2897   // turn this into Self->ivar, just return a BareIVarExpr or something.
2898   IdentifierInfo &II = Context.Idents.get("self");
2899   UnqualifiedId SelfName;
2900   SelfName.setImplicitSelfParam(&II);
2901   CXXScopeSpec SelfScopeSpec;
2902   SourceLocation TemplateKWLoc;
2903   ExprResult SelfExpr =
2904       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2905                         /*HasTrailingLParen=*/false,
2906                         /*IsAddressOfOperand=*/false);
2907   if (SelfExpr.isInvalid())
2908     return ExprError();
2909 
2910   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2911   if (SelfExpr.isInvalid())
2912     return ExprError();
2913 
2914   MarkAnyDeclReferenced(Loc, IV, true);
2915 
2916   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2917   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2918       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2919     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2920 
2921   ObjCIvarRefExpr *Result = new (Context)
2922       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2923                       IV->getLocation(), SelfExpr.get(), true, true);
2924 
2925   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2926     if (!isUnevaluatedContext() &&
2927         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2928       getCurFunction()->recordUseOfWeak(Result);
2929   }
2930   if (getLangOpts().ObjCAutoRefCount)
2931     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2932       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2933 
2934   return Result;
2935 }
2936 
2937 /// The parser has read a name in, and Sema has detected that we're currently
2938 /// inside an ObjC method. Perform some additional checks and determine if we
2939 /// should form a reference to an ivar. If so, build an expression referencing
2940 /// that ivar.
2941 ExprResult
2942 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2943                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2944   // FIXME: Integrate this lookup step into LookupParsedName.
2945   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2946   if (Ivar.isInvalid())
2947     return ExprError();
2948   if (Ivar.isUsable())
2949     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2950                             cast<ObjCIvarDecl>(Ivar.get()));
2951 
2952   if (Lookup.empty() && II && AllowBuiltinCreation)
2953     LookupBuiltin(Lookup);
2954 
2955   // Sentinel value saying that we didn't do anything special.
2956   return ExprResult(false);
2957 }
2958 
2959 /// Cast a base object to a member's actual type.
2960 ///
2961 /// There are two relevant checks:
2962 ///
2963 /// C++ [class.access.base]p7:
2964 ///
2965 ///   If a class member access operator [...] is used to access a non-static
2966 ///   data member or non-static member function, the reference is ill-formed if
2967 ///   the left operand [...] cannot be implicitly converted to a pointer to the
2968 ///   naming class of the right operand.
2969 ///
2970 /// C++ [expr.ref]p7:
2971 ///
2972 ///   If E2 is a non-static data member or a non-static member function, the
2973 ///   program is ill-formed if the class of which E2 is directly a member is an
2974 ///   ambiguous base (11.8) of the naming class (11.9.3) of E2.
2975 ///
2976 /// Note that the latter check does not consider access; the access of the
2977 /// "real" base class is checked as appropriate when checking the access of the
2978 /// member name.
2979 ExprResult
2980 Sema::PerformObjectMemberConversion(Expr *From,
2981                                     NestedNameSpecifier *Qualifier,
2982                                     NamedDecl *FoundDecl,
2983                                     NamedDecl *Member) {
2984   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2985   if (!RD)
2986     return From;
2987 
2988   QualType DestRecordType;
2989   QualType DestType;
2990   QualType FromRecordType;
2991   QualType FromType = From->getType();
2992   bool PointerConversions = false;
2993   if (isa<FieldDecl>(Member)) {
2994     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2995     auto FromPtrType = FromType->getAs<PointerType>();
2996     DestRecordType = Context.getAddrSpaceQualType(
2997         DestRecordType, FromPtrType
2998                             ? FromType->getPointeeType().getAddressSpace()
2999                             : FromType.getAddressSpace());
3000 
3001     if (FromPtrType) {
3002       DestType = Context.getPointerType(DestRecordType);
3003       FromRecordType = FromPtrType->getPointeeType();
3004       PointerConversions = true;
3005     } else {
3006       DestType = DestRecordType;
3007       FromRecordType = FromType;
3008     }
3009   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
3010     if (Method->isStatic())
3011       return From;
3012 
3013     DestType = Method->getThisType();
3014     DestRecordType = DestType->getPointeeType();
3015 
3016     if (FromType->getAs<PointerType>()) {
3017       FromRecordType = FromType->getPointeeType();
3018       PointerConversions = true;
3019     } else {
3020       FromRecordType = FromType;
3021       DestType = DestRecordType;
3022     }
3023 
3024     LangAS FromAS = FromRecordType.getAddressSpace();
3025     LangAS DestAS = DestRecordType.getAddressSpace();
3026     if (FromAS != DestAS) {
3027       QualType FromRecordTypeWithoutAS =
3028           Context.removeAddrSpaceQualType(FromRecordType);
3029       QualType FromTypeWithDestAS =
3030           Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3031       if (PointerConversions)
3032         FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3033       From = ImpCastExprToType(From, FromTypeWithDestAS,
3034                                CK_AddressSpaceConversion, From->getValueKind())
3035                  .get();
3036     }
3037   } else {
3038     // No conversion necessary.
3039     return From;
3040   }
3041 
3042   if (DestType->isDependentType() || FromType->isDependentType())
3043     return From;
3044 
3045   // If the unqualified types are the same, no conversion is necessary.
3046   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3047     return From;
3048 
3049   SourceRange FromRange = From->getSourceRange();
3050   SourceLocation FromLoc = FromRange.getBegin();
3051 
3052   ExprValueKind VK = From->getValueKind();
3053 
3054   // C++ [class.member.lookup]p8:
3055   //   [...] Ambiguities can often be resolved by qualifying a name with its
3056   //   class name.
3057   //
3058   // If the member was a qualified name and the qualified referred to a
3059   // specific base subobject type, we'll cast to that intermediate type
3060   // first and then to the object in which the member is declared. That allows
3061   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3062   //
3063   //   class Base { public: int x; };
3064   //   class Derived1 : public Base { };
3065   //   class Derived2 : public Base { };
3066   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
3067   //
3068   //   void VeryDerived::f() {
3069   //     x = 17; // error: ambiguous base subobjects
3070   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
3071   //   }
3072   if (Qualifier && Qualifier->getAsType()) {
3073     QualType QType = QualType(Qualifier->getAsType(), 0);
3074     assert(QType->isRecordType() && "lookup done with non-record type");
3075 
3076     QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3077 
3078     // In C++98, the qualifier type doesn't actually have to be a base
3079     // type of the object type, in which case we just ignore it.
3080     // Otherwise build the appropriate casts.
3081     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3082       CXXCastPath BasePath;
3083       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3084                                        FromLoc, FromRange, &BasePath))
3085         return ExprError();
3086 
3087       if (PointerConversions)
3088         QType = Context.getPointerType(QType);
3089       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3090                                VK, &BasePath).get();
3091 
3092       FromType = QType;
3093       FromRecordType = QRecordType;
3094 
3095       // If the qualifier type was the same as the destination type,
3096       // we're done.
3097       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3098         return From;
3099     }
3100   }
3101 
3102   CXXCastPath BasePath;
3103   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3104                                    FromLoc, FromRange, &BasePath,
3105                                    /*IgnoreAccess=*/true))
3106     return ExprError();
3107 
3108   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3109                            VK, &BasePath);
3110 }
3111 
3112 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3113                                       const LookupResult &R,
3114                                       bool HasTrailingLParen) {
3115   // Only when used directly as the postfix-expression of a call.
3116   if (!HasTrailingLParen)
3117     return false;
3118 
3119   // Never if a scope specifier was provided.
3120   if (SS.isSet())
3121     return false;
3122 
3123   // Only in C++ or ObjC++.
3124   if (!getLangOpts().CPlusPlus)
3125     return false;
3126 
3127   // Turn off ADL when we find certain kinds of declarations during
3128   // normal lookup:
3129   for (NamedDecl *D : R) {
3130     // C++0x [basic.lookup.argdep]p3:
3131     //     -- a declaration of a class member
3132     // Since using decls preserve this property, we check this on the
3133     // original decl.
3134     if (D->isCXXClassMember())
3135       return false;
3136 
3137     // C++0x [basic.lookup.argdep]p3:
3138     //     -- a block-scope function declaration that is not a
3139     //        using-declaration
3140     // NOTE: we also trigger this for function templates (in fact, we
3141     // don't check the decl type at all, since all other decl types
3142     // turn off ADL anyway).
3143     if (isa<UsingShadowDecl>(D))
3144       D = cast<UsingShadowDecl>(D)->getTargetDecl();
3145     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3146       return false;
3147 
3148     // C++0x [basic.lookup.argdep]p3:
3149     //     -- a declaration that is neither a function or a function
3150     //        template
3151     // And also for builtin functions.
3152     if (isa<FunctionDecl>(D)) {
3153       FunctionDecl *FDecl = cast<FunctionDecl>(D);
3154 
3155       // But also builtin functions.
3156       if (FDecl->getBuiltinID() && FDecl->isImplicit())
3157         return false;
3158     } else if (!isa<FunctionTemplateDecl>(D))
3159       return false;
3160   }
3161 
3162   return true;
3163 }
3164 
3165 
3166 /// Diagnoses obvious problems with the use of the given declaration
3167 /// as an expression.  This is only actually called for lookups that
3168 /// were not overloaded, and it doesn't promise that the declaration
3169 /// will in fact be used.
3170 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3171   if (D->isInvalidDecl())
3172     return true;
3173 
3174   if (isa<TypedefNameDecl>(D)) {
3175     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3176     return true;
3177   }
3178 
3179   if (isa<ObjCInterfaceDecl>(D)) {
3180     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3181     return true;
3182   }
3183 
3184   if (isa<NamespaceDecl>(D)) {
3185     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3186     return true;
3187   }
3188 
3189   return false;
3190 }
3191 
3192 // Certain multiversion types should be treated as overloaded even when there is
3193 // only one result.
3194 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3195   assert(R.isSingleResult() && "Expected only a single result");
3196   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3197   return FD &&
3198          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3199 }
3200 
3201 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3202                                           LookupResult &R, bool NeedsADL,
3203                                           bool AcceptInvalidDecl) {
3204   // If this is a single, fully-resolved result and we don't need ADL,
3205   // just build an ordinary singleton decl ref.
3206   if (!NeedsADL && R.isSingleResult() &&
3207       !R.getAsSingle<FunctionTemplateDecl>() &&
3208       !ShouldLookupResultBeMultiVersionOverload(R))
3209     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3210                                     R.getRepresentativeDecl(), nullptr,
3211                                     AcceptInvalidDecl);
3212 
3213   // We only need to check the declaration if there's exactly one
3214   // result, because in the overloaded case the results can only be
3215   // functions and function templates.
3216   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3217       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3218     return ExprError();
3219 
3220   // Otherwise, just build an unresolved lookup expression.  Suppress
3221   // any lookup-related diagnostics; we'll hash these out later, when
3222   // we've picked a target.
3223   R.suppressDiagnostics();
3224 
3225   UnresolvedLookupExpr *ULE
3226     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3227                                    SS.getWithLocInContext(Context),
3228                                    R.getLookupNameInfo(),
3229                                    NeedsADL, R.isOverloadedResult(),
3230                                    R.begin(), R.end());
3231 
3232   return ULE;
3233 }
3234 
3235 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3236                                                ValueDecl *var);
3237 
3238 /// Complete semantic analysis for a reference to the given declaration.
3239 ExprResult Sema::BuildDeclarationNameExpr(
3240     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3241     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3242     bool AcceptInvalidDecl) {
3243   assert(D && "Cannot refer to a NULL declaration");
3244   assert(!isa<FunctionTemplateDecl>(D) &&
3245          "Cannot refer unambiguously to a function template");
3246 
3247   SourceLocation Loc = NameInfo.getLoc();
3248   if (CheckDeclInExpr(*this, Loc, D)) {
3249     // Recovery from invalid cases (e.g. D is an invalid Decl).
3250     // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3251     // diagnostics, as invalid decls use int as a fallback type.
3252     return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3253   }
3254 
3255   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3256     // Specifically diagnose references to class templates that are missing
3257     // a template argument list.
3258     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3259     return ExprError();
3260   }
3261 
3262   // Make sure that we're referring to a value.
3263   if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3264     Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3265     Diag(D->getLocation(), diag::note_declared_at);
3266     return ExprError();
3267   }
3268 
3269   // Check whether this declaration can be used. Note that we suppress
3270   // this check when we're going to perform argument-dependent lookup
3271   // on this function name, because this might not be the function
3272   // that overload resolution actually selects.
3273   if (DiagnoseUseOfDecl(D, Loc))
3274     return ExprError();
3275 
3276   auto *VD = cast<ValueDecl>(D);
3277 
3278   // Only create DeclRefExpr's for valid Decl's.
3279   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3280     return ExprError();
3281 
3282   // Handle members of anonymous structs and unions.  If we got here,
3283   // and the reference is to a class member indirect field, then this
3284   // must be the subject of a pointer-to-member expression.
3285   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3286     if (!indirectField->isCXXClassMember())
3287       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3288                                                       indirectField);
3289 
3290   QualType type = VD->getType();
3291   if (type.isNull())
3292     return ExprError();
3293   ExprValueKind valueKind = VK_PRValue;
3294 
3295   // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3296   // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3297   // is expanded by some outer '...' in the context of the use.
3298   type = type.getNonPackExpansionType();
3299 
3300   switch (D->getKind()) {
3301     // Ignore all the non-ValueDecl kinds.
3302 #define ABSTRACT_DECL(kind)
3303 #define VALUE(type, base)
3304 #define DECL(type, base) case Decl::type:
3305 #include "clang/AST/DeclNodes.inc"
3306     llvm_unreachable("invalid value decl kind");
3307 
3308   // These shouldn't make it here.
3309   case Decl::ObjCAtDefsField:
3310     llvm_unreachable("forming non-member reference to ivar?");
3311 
3312   // Enum constants are always r-values and never references.
3313   // Unresolved using declarations are dependent.
3314   case Decl::EnumConstant:
3315   case Decl::UnresolvedUsingValue:
3316   case Decl::OMPDeclareReduction:
3317   case Decl::OMPDeclareMapper:
3318     valueKind = VK_PRValue;
3319     break;
3320 
3321   // Fields and indirect fields that got here must be for
3322   // pointer-to-member expressions; we just call them l-values for
3323   // internal consistency, because this subexpression doesn't really
3324   // exist in the high-level semantics.
3325   case Decl::Field:
3326   case Decl::IndirectField:
3327   case Decl::ObjCIvar:
3328     assert(getLangOpts().CPlusPlus && "building reference to field in C?");
3329 
3330     // These can't have reference type in well-formed programs, but
3331     // for internal consistency we do this anyway.
3332     type = type.getNonReferenceType();
3333     valueKind = VK_LValue;
3334     break;
3335 
3336   // Non-type template parameters are either l-values or r-values
3337   // depending on the type.
3338   case Decl::NonTypeTemplateParm: {
3339     if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3340       type = reftype->getPointeeType();
3341       valueKind = VK_LValue; // even if the parameter is an r-value reference
3342       break;
3343     }
3344 
3345     // [expr.prim.id.unqual]p2:
3346     //   If the entity is a template parameter object for a template
3347     //   parameter of type T, the type of the expression is const T.
3348     //   [...] The expression is an lvalue if the entity is a [...] template
3349     //   parameter object.
3350     if (type->isRecordType()) {
3351       type = type.getUnqualifiedType().withConst();
3352       valueKind = VK_LValue;
3353       break;
3354     }
3355 
3356     // For non-references, we need to strip qualifiers just in case
3357     // the template parameter was declared as 'const int' or whatever.
3358     valueKind = VK_PRValue;
3359     type = type.getUnqualifiedType();
3360     break;
3361   }
3362 
3363   case Decl::Var:
3364   case Decl::VarTemplateSpecialization:
3365   case Decl::VarTemplatePartialSpecialization:
3366   case Decl::Decomposition:
3367   case Decl::OMPCapturedExpr:
3368     // In C, "extern void blah;" is valid and is an r-value.
3369     if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3370         type->isVoidType()) {
3371       valueKind = VK_PRValue;
3372       break;
3373     }
3374     LLVM_FALLTHROUGH;
3375 
3376   case Decl::ImplicitParam:
3377   case Decl::ParmVar: {
3378     // These are always l-values.
3379     valueKind = VK_LValue;
3380     type = type.getNonReferenceType();
3381 
3382     // FIXME: Does the addition of const really only apply in
3383     // potentially-evaluated contexts? Since the variable isn't actually
3384     // captured in an unevaluated context, it seems that the answer is no.
3385     if (!isUnevaluatedContext()) {
3386       QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3387       if (!CapturedType.isNull())
3388         type = CapturedType;
3389     }
3390 
3391     break;
3392   }
3393 
3394   case Decl::Binding: {
3395     // These are always lvalues.
3396     valueKind = VK_LValue;
3397     type = type.getNonReferenceType();
3398     // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3399     // decides how that's supposed to work.
3400     auto *BD = cast<BindingDecl>(VD);
3401     if (BD->getDeclContext() != CurContext && !isUnevaluatedContext()) {
3402       auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3403       if (DD && DD->hasLocalStorage())
3404         diagnoseUncapturableValueReference(*this, Loc, BD);
3405     }
3406     break;
3407   }
3408 
3409   case Decl::Function: {
3410     if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3411       if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3412         type = Context.BuiltinFnTy;
3413         valueKind = VK_PRValue;
3414         break;
3415       }
3416     }
3417 
3418     const FunctionType *fty = type->castAs<FunctionType>();
3419 
3420     // If we're referring to a function with an __unknown_anytype
3421     // result type, make the entire expression __unknown_anytype.
3422     if (fty->getReturnType() == Context.UnknownAnyTy) {
3423       type = Context.UnknownAnyTy;
3424       valueKind = VK_PRValue;
3425       break;
3426     }
3427 
3428     // Functions are l-values in C++.
3429     if (getLangOpts().CPlusPlus) {
3430       valueKind = VK_LValue;
3431       break;
3432     }
3433 
3434     // C99 DR 316 says that, if a function type comes from a
3435     // function definition (without a prototype), that type is only
3436     // used for checking compatibility. Therefore, when referencing
3437     // the function, we pretend that we don't have the full function
3438     // type.
3439     if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3440       type = Context.getFunctionNoProtoType(fty->getReturnType(),
3441                                             fty->getExtInfo());
3442 
3443     // Functions are r-values in C.
3444     valueKind = VK_PRValue;
3445     break;
3446   }
3447 
3448   case Decl::CXXDeductionGuide:
3449     llvm_unreachable("building reference to deduction guide");
3450 
3451   case Decl::MSProperty:
3452   case Decl::MSGuid:
3453   case Decl::TemplateParamObject:
3454     // FIXME: Should MSGuidDecl and template parameter objects be subject to
3455     // capture in OpenMP, or duplicated between host and device?
3456     valueKind = VK_LValue;
3457     break;
3458 
3459   case Decl::UnnamedGlobalConstant:
3460     valueKind = VK_LValue;
3461     break;
3462 
3463   case Decl::CXXMethod:
3464     // If we're referring to a method with an __unknown_anytype
3465     // result type, make the entire expression __unknown_anytype.
3466     // This should only be possible with a type written directly.
3467     if (const FunctionProtoType *proto =
3468             dyn_cast<FunctionProtoType>(VD->getType()))
3469       if (proto->getReturnType() == Context.UnknownAnyTy) {
3470         type = Context.UnknownAnyTy;
3471         valueKind = VK_PRValue;
3472         break;
3473       }
3474 
3475     // C++ methods are l-values if static, r-values if non-static.
3476     if (cast<CXXMethodDecl>(VD)->isStatic()) {
3477       valueKind = VK_LValue;
3478       break;
3479     }
3480     LLVM_FALLTHROUGH;
3481 
3482   case Decl::CXXConversion:
3483   case Decl::CXXDestructor:
3484   case Decl::CXXConstructor:
3485     valueKind = VK_PRValue;
3486     break;
3487   }
3488 
3489   return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3490                           /*FIXME: TemplateKWLoc*/ SourceLocation(),
3491                           TemplateArgs);
3492 }
3493 
3494 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3495                                     SmallString<32> &Target) {
3496   Target.resize(CharByteWidth * (Source.size() + 1));
3497   char *ResultPtr = &Target[0];
3498   const llvm::UTF8 *ErrorPtr;
3499   bool success =
3500       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3501   (void)success;
3502   assert(success);
3503   Target.resize(ResultPtr - &Target[0]);
3504 }
3505 
3506 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3507                                      PredefinedExpr::IdentKind IK) {
3508   // Pick the current block, lambda, captured statement or function.
3509   Decl *currentDecl = nullptr;
3510   if (const BlockScopeInfo *BSI = getCurBlock())
3511     currentDecl = BSI->TheDecl;
3512   else if (const LambdaScopeInfo *LSI = getCurLambda())
3513     currentDecl = LSI->CallOperator;
3514   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3515     currentDecl = CSI->TheCapturedDecl;
3516   else
3517     currentDecl = getCurFunctionOrMethodDecl();
3518 
3519   if (!currentDecl) {
3520     Diag(Loc, diag::ext_predef_outside_function);
3521     currentDecl = Context.getTranslationUnitDecl();
3522   }
3523 
3524   QualType ResTy;
3525   StringLiteral *SL = nullptr;
3526   if (cast<DeclContext>(currentDecl)->isDependentContext())
3527     ResTy = Context.DependentTy;
3528   else {
3529     // Pre-defined identifiers are of type char[x], where x is the length of
3530     // the string.
3531     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3532     unsigned Length = Str.length();
3533 
3534     llvm::APInt LengthI(32, Length + 1);
3535     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3536       ResTy =
3537           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3538       SmallString<32> RawChars;
3539       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3540                               Str, RawChars);
3541       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3542                                            ArrayType::Normal,
3543                                            /*IndexTypeQuals*/ 0);
3544       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3545                                  /*Pascal*/ false, ResTy, Loc);
3546     } else {
3547       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3548       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3549                                            ArrayType::Normal,
3550                                            /*IndexTypeQuals*/ 0);
3551       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3552                                  /*Pascal*/ false, ResTy, Loc);
3553     }
3554   }
3555 
3556   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3557 }
3558 
3559 ExprResult Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3560                                                SourceLocation LParen,
3561                                                SourceLocation RParen,
3562                                                TypeSourceInfo *TSI) {
3563   return SYCLUniqueStableNameExpr::Create(Context, OpLoc, LParen, RParen, TSI);
3564 }
3565 
3566 ExprResult Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
3567                                                SourceLocation LParen,
3568                                                SourceLocation RParen,
3569                                                ParsedType ParsedTy) {
3570   TypeSourceInfo *TSI = nullptr;
3571   QualType Ty = GetTypeFromParser(ParsedTy, &TSI);
3572 
3573   if (Ty.isNull())
3574     return ExprError();
3575   if (!TSI)
3576     TSI = Context.getTrivialTypeSourceInfo(Ty, LParen);
3577 
3578   return BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
3579 }
3580 
3581 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3582   PredefinedExpr::IdentKind IK;
3583 
3584   switch (Kind) {
3585   default: llvm_unreachable("Unknown simple primary expr!");
3586   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3587   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3588   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3589   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3590   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3591   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3592   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3593   }
3594 
3595   return BuildPredefinedExpr(Loc, IK);
3596 }
3597 
3598 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3599   SmallString<16> CharBuffer;
3600   bool Invalid = false;
3601   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3602   if (Invalid)
3603     return ExprError();
3604 
3605   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3606                             PP, Tok.getKind());
3607   if (Literal.hadError())
3608     return ExprError();
3609 
3610   QualType Ty;
3611   if (Literal.isWide())
3612     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3613   else if (Literal.isUTF8() && getLangOpts().C2x)
3614     Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C2x
3615   else if (Literal.isUTF8() && getLangOpts().Char8)
3616     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3617   else if (Literal.isUTF16())
3618     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3619   else if (Literal.isUTF32())
3620     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3621   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3622     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3623   else
3624     Ty = Context.CharTy; // 'x' -> char in C++;
3625                          // u8'x' -> char in C11-C17 and in C++ without char8_t.
3626 
3627   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3628   if (Literal.isWide())
3629     Kind = CharacterLiteral::Wide;
3630   else if (Literal.isUTF16())
3631     Kind = CharacterLiteral::UTF16;
3632   else if (Literal.isUTF32())
3633     Kind = CharacterLiteral::UTF32;
3634   else if (Literal.isUTF8())
3635     Kind = CharacterLiteral::UTF8;
3636 
3637   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3638                                              Tok.getLocation());
3639 
3640   if (Literal.getUDSuffix().empty())
3641     return Lit;
3642 
3643   // We're building a user-defined literal.
3644   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3645   SourceLocation UDSuffixLoc =
3646     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3647 
3648   // Make sure we're allowed user-defined literals here.
3649   if (!UDLScope)
3650     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3651 
3652   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3653   //   operator "" X (ch)
3654   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3655                                         Lit, Tok.getLocation());
3656 }
3657 
3658 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3659   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3660   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3661                                 Context.IntTy, Loc);
3662 }
3663 
3664 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3665                                   QualType Ty, SourceLocation Loc) {
3666   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3667 
3668   using llvm::APFloat;
3669   APFloat Val(Format);
3670 
3671   APFloat::opStatus result = Literal.GetFloatValue(Val);
3672 
3673   // Overflow is always an error, but underflow is only an error if
3674   // we underflowed to zero (APFloat reports denormals as underflow).
3675   if ((result & APFloat::opOverflow) ||
3676       ((result & APFloat::opUnderflow) && Val.isZero())) {
3677     unsigned diagnostic;
3678     SmallString<20> buffer;
3679     if (result & APFloat::opOverflow) {
3680       diagnostic = diag::warn_float_overflow;
3681       APFloat::getLargest(Format).toString(buffer);
3682     } else {
3683       diagnostic = diag::warn_float_underflow;
3684       APFloat::getSmallest(Format).toString(buffer);
3685     }
3686 
3687     S.Diag(Loc, diagnostic)
3688       << Ty
3689       << StringRef(buffer.data(), buffer.size());
3690   }
3691 
3692   bool isExact = (result == APFloat::opOK);
3693   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3694 }
3695 
3696 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3697   assert(E && "Invalid expression");
3698 
3699   if (E->isValueDependent())
3700     return false;
3701 
3702   QualType QT = E->getType();
3703   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3704     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3705     return true;
3706   }
3707 
3708   llvm::APSInt ValueAPS;
3709   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3710 
3711   if (R.isInvalid())
3712     return true;
3713 
3714   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3715   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3716     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3717         << toString(ValueAPS, 10) << ValueIsPositive;
3718     return true;
3719   }
3720 
3721   return false;
3722 }
3723 
3724 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3725   // Fast path for a single digit (which is quite common).  A single digit
3726   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3727   if (Tok.getLength() == 1) {
3728     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3729     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3730   }
3731 
3732   SmallString<128> SpellingBuffer;
3733   // NumericLiteralParser wants to overread by one character.  Add padding to
3734   // the buffer in case the token is copied to the buffer.  If getSpelling()
3735   // returns a StringRef to the memory buffer, it should have a null char at
3736   // the EOF, so it is also safe.
3737   SpellingBuffer.resize(Tok.getLength() + 1);
3738 
3739   // Get the spelling of the token, which eliminates trigraphs, etc.
3740   bool Invalid = false;
3741   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3742   if (Invalid)
3743     return ExprError();
3744 
3745   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3746                                PP.getSourceManager(), PP.getLangOpts(),
3747                                PP.getTargetInfo(), PP.getDiagnostics());
3748   if (Literal.hadError)
3749     return ExprError();
3750 
3751   if (Literal.hasUDSuffix()) {
3752     // We're building a user-defined literal.
3753     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3754     SourceLocation UDSuffixLoc =
3755       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3756 
3757     // Make sure we're allowed user-defined literals here.
3758     if (!UDLScope)
3759       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3760 
3761     QualType CookedTy;
3762     if (Literal.isFloatingLiteral()) {
3763       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3764       // long double, the literal is treated as a call of the form
3765       //   operator "" X (f L)
3766       CookedTy = Context.LongDoubleTy;
3767     } else {
3768       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3769       // unsigned long long, the literal is treated as a call of the form
3770       //   operator "" X (n ULL)
3771       CookedTy = Context.UnsignedLongLongTy;
3772     }
3773 
3774     DeclarationName OpName =
3775       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3776     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3777     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3778 
3779     SourceLocation TokLoc = Tok.getLocation();
3780 
3781     // Perform literal operator lookup to determine if we're building a raw
3782     // literal or a cooked one.
3783     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3784     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3785                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3786                                   /*AllowStringTemplatePack*/ false,
3787                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3788     case LOLR_ErrorNoDiagnostic:
3789       // Lookup failure for imaginary constants isn't fatal, there's still the
3790       // GNU extension producing _Complex types.
3791       break;
3792     case LOLR_Error:
3793       return ExprError();
3794     case LOLR_Cooked: {
3795       Expr *Lit;
3796       if (Literal.isFloatingLiteral()) {
3797         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3798       } else {
3799         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3800         if (Literal.GetIntegerValue(ResultVal))
3801           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3802               << /* Unsigned */ 1;
3803         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3804                                      Tok.getLocation());
3805       }
3806       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3807     }
3808 
3809     case LOLR_Raw: {
3810       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3811       // literal is treated as a call of the form
3812       //   operator "" X ("n")
3813       unsigned Length = Literal.getUDSuffixOffset();
3814       QualType StrTy = Context.getConstantArrayType(
3815           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3816           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3817       Expr *Lit = StringLiteral::Create(
3818           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3819           /*Pascal*/false, StrTy, &TokLoc, 1);
3820       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3821     }
3822 
3823     case LOLR_Template: {
3824       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3825       // template), L is treated as a call fo the form
3826       //   operator "" X <'c1', 'c2', ... 'ck'>()
3827       // where n is the source character sequence c1 c2 ... ck.
3828       TemplateArgumentListInfo ExplicitArgs;
3829       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3830       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3831       llvm::APSInt Value(CharBits, CharIsUnsigned);
3832       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3833         Value = TokSpelling[I];
3834         TemplateArgument Arg(Context, Value, Context.CharTy);
3835         TemplateArgumentLocInfo ArgInfo;
3836         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3837       }
3838       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3839                                       &ExplicitArgs);
3840     }
3841     case LOLR_StringTemplatePack:
3842       llvm_unreachable("unexpected literal operator lookup result");
3843     }
3844   }
3845 
3846   Expr *Res;
3847 
3848   if (Literal.isFixedPointLiteral()) {
3849     QualType Ty;
3850 
3851     if (Literal.isAccum) {
3852       if (Literal.isHalf) {
3853         Ty = Context.ShortAccumTy;
3854       } else if (Literal.isLong) {
3855         Ty = Context.LongAccumTy;
3856       } else {
3857         Ty = Context.AccumTy;
3858       }
3859     } else if (Literal.isFract) {
3860       if (Literal.isHalf) {
3861         Ty = Context.ShortFractTy;
3862       } else if (Literal.isLong) {
3863         Ty = Context.LongFractTy;
3864       } else {
3865         Ty = Context.FractTy;
3866       }
3867     }
3868 
3869     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3870 
3871     bool isSigned = !Literal.isUnsigned;
3872     unsigned scale = Context.getFixedPointScale(Ty);
3873     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3874 
3875     llvm::APInt Val(bit_width, 0, isSigned);
3876     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3877     bool ValIsZero = Val.isZero() && !Overflowed;
3878 
3879     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3880     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3881       // Clause 6.4.4 - The value of a constant shall be in the range of
3882       // representable values for its type, with exception for constants of a
3883       // fract type with a value of exactly 1; such a constant shall denote
3884       // the maximal value for the type.
3885       --Val;
3886     else if (Val.ugt(MaxVal) || Overflowed)
3887       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3888 
3889     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3890                                               Tok.getLocation(), scale);
3891   } else if (Literal.isFloatingLiteral()) {
3892     QualType Ty;
3893     if (Literal.isHalf){
3894       if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3895         Ty = Context.HalfTy;
3896       else {
3897         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3898         return ExprError();
3899       }
3900     } else if (Literal.isFloat)
3901       Ty = Context.FloatTy;
3902     else if (Literal.isLong)
3903       Ty = Context.LongDoubleTy;
3904     else if (Literal.isFloat16)
3905       Ty = Context.Float16Ty;
3906     else if (Literal.isFloat128)
3907       Ty = Context.Float128Ty;
3908     else
3909       Ty = Context.DoubleTy;
3910 
3911     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3912 
3913     if (Ty == Context.DoubleTy) {
3914       if (getLangOpts().SinglePrecisionConstants) {
3915         if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3916           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3917         }
3918       } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3919                                              "cl_khr_fp64", getLangOpts())) {
3920         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3921         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3922             << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3923         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3924       }
3925     }
3926   } else if (!Literal.isIntegerLiteral()) {
3927     return ExprError();
3928   } else {
3929     QualType Ty;
3930 
3931     // 'long long' is a C99 or C++11 feature.
3932     if (!getLangOpts().C99 && Literal.isLongLong) {
3933       if (getLangOpts().CPlusPlus)
3934         Diag(Tok.getLocation(),
3935              getLangOpts().CPlusPlus11 ?
3936              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3937       else
3938         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3939     }
3940 
3941     // 'z/uz' literals are a C++2b feature.
3942     if (Literal.isSizeT)
3943       Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3944                                   ? getLangOpts().CPlusPlus2b
3945                                         ? diag::warn_cxx20_compat_size_t_suffix
3946                                         : diag::ext_cxx2b_size_t_suffix
3947                                   : diag::err_cxx2b_size_t_suffix);
3948 
3949     // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3950     // but we do not currently support the suffix in C++ mode because it's not
3951     // entirely clear whether WG21 will prefer this suffix to return a library
3952     // type such as std::bit_int instead of returning a _BitInt.
3953     if (Literal.isBitInt && !getLangOpts().CPlusPlus)
3954       PP.Diag(Tok.getLocation(), getLangOpts().C2x
3955                                      ? diag::warn_c2x_compat_bitint_suffix
3956                                      : diag::ext_c2x_bitint_suffix);
3957 
3958     // Get the value in the widest-possible width. What is "widest" depends on
3959     // whether the literal is a bit-precise integer or not. For a bit-precise
3960     // integer type, try to scan the source to determine how many bits are
3961     // needed to represent the value. This may seem a bit expensive, but trying
3962     // to get the integer value from an overly-wide APInt is *extremely*
3963     // expensive, so the naive approach of assuming
3964     // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3965     unsigned BitsNeeded =
3966         Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3967                                Literal.getLiteralDigits(), Literal.getRadix())
3968                          : Context.getTargetInfo().getIntMaxTWidth();
3969     llvm::APInt ResultVal(BitsNeeded, 0);
3970 
3971     if (Literal.GetIntegerValue(ResultVal)) {
3972       // If this value didn't fit into uintmax_t, error and force to ull.
3973       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3974           << /* Unsigned */ 1;
3975       Ty = Context.UnsignedLongLongTy;
3976       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3977              "long long is not intmax_t?");
3978     } else {
3979       // If this value fits into a ULL, try to figure out what else it fits into
3980       // according to the rules of C99 6.4.4.1p5.
3981 
3982       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3983       // be an unsigned int.
3984       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3985 
3986       // Check from smallest to largest, picking the smallest type we can.
3987       unsigned Width = 0;
3988 
3989       // Microsoft specific integer suffixes are explicitly sized.
3990       if (Literal.MicrosoftInteger) {
3991         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3992           Width = 8;
3993           Ty = Context.CharTy;
3994         } else {
3995           Width = Literal.MicrosoftInteger;
3996           Ty = Context.getIntTypeForBitwidth(Width,
3997                                              /*Signed=*/!Literal.isUnsigned);
3998         }
3999       }
4000 
4001       // Bit-precise integer literals are automagically-sized based on the
4002       // width required by the literal.
4003       if (Literal.isBitInt) {
4004         // The signed version has one more bit for the sign value. There are no
4005         // zero-width bit-precise integers, even if the literal value is 0.
4006         Width = std::max(ResultVal.getActiveBits(), 1u) +
4007                 (Literal.isUnsigned ? 0u : 1u);
4008 
4009         // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4010         // and reset the type to the largest supported width.
4011         unsigned int MaxBitIntWidth =
4012             Context.getTargetInfo().getMaxBitIntWidth();
4013         if (Width > MaxBitIntWidth) {
4014           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4015               << Literal.isUnsigned;
4016           Width = MaxBitIntWidth;
4017         }
4018 
4019         // Reset the result value to the smaller APInt and select the correct
4020         // type to be used. Note, we zext even for signed values because the
4021         // literal itself is always an unsigned value (a preceeding - is a
4022         // unary operator, not part of the literal).
4023         ResultVal = ResultVal.zextOrTrunc(Width);
4024         Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4025       }
4026 
4027       // Check C++2b size_t literals.
4028       if (Literal.isSizeT) {
4029         assert(!Literal.MicrosoftInteger &&
4030                "size_t literals can't be Microsoft literals");
4031         unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4032             Context.getTargetInfo().getSizeType());
4033 
4034         // Does it fit in size_t?
4035         if (ResultVal.isIntN(SizeTSize)) {
4036           // Does it fit in ssize_t?
4037           if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4038             Ty = Context.getSignedSizeType();
4039           else if (AllowUnsigned)
4040             Ty = Context.getSizeType();
4041           Width = SizeTSize;
4042         }
4043       }
4044 
4045       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4046           !Literal.isSizeT) {
4047         // Are int/unsigned possibilities?
4048         unsigned IntSize = Context.getTargetInfo().getIntWidth();
4049 
4050         // Does it fit in a unsigned int?
4051         if (ResultVal.isIntN(IntSize)) {
4052           // Does it fit in a signed int?
4053           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4054             Ty = Context.IntTy;
4055           else if (AllowUnsigned)
4056             Ty = Context.UnsignedIntTy;
4057           Width = IntSize;
4058         }
4059       }
4060 
4061       // Are long/unsigned long possibilities?
4062       if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4063         unsigned LongSize = Context.getTargetInfo().getLongWidth();
4064 
4065         // Does it fit in a unsigned long?
4066         if (ResultVal.isIntN(LongSize)) {
4067           // Does it fit in a signed long?
4068           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4069             Ty = Context.LongTy;
4070           else if (AllowUnsigned)
4071             Ty = Context.UnsignedLongTy;
4072           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4073           // is compatible.
4074           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4075             const unsigned LongLongSize =
4076                 Context.getTargetInfo().getLongLongWidth();
4077             Diag(Tok.getLocation(),
4078                  getLangOpts().CPlusPlus
4079                      ? Literal.isLong
4080                            ? diag::warn_old_implicitly_unsigned_long_cxx
4081                            : /*C++98 UB*/ diag::
4082                                  ext_old_implicitly_unsigned_long_cxx
4083                      : diag::warn_old_implicitly_unsigned_long)
4084                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4085                                             : /*will be ill-formed*/ 1);
4086             Ty = Context.UnsignedLongTy;
4087           }
4088           Width = LongSize;
4089         }
4090       }
4091 
4092       // Check long long if needed.
4093       if (Ty.isNull() && !Literal.isSizeT) {
4094         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4095 
4096         // Does it fit in a unsigned long long?
4097         if (ResultVal.isIntN(LongLongSize)) {
4098           // Does it fit in a signed long long?
4099           // To be compatible with MSVC, hex integer literals ending with the
4100           // LL or i64 suffix are always signed in Microsoft mode.
4101           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4102               (getLangOpts().MSVCCompat && Literal.isLongLong)))
4103             Ty = Context.LongLongTy;
4104           else if (AllowUnsigned)
4105             Ty = Context.UnsignedLongLongTy;
4106           Width = LongLongSize;
4107         }
4108       }
4109 
4110       // If we still couldn't decide a type, we either have 'size_t' literal
4111       // that is out of range, or a decimal literal that does not fit in a
4112       // signed long long and has no U suffix.
4113       if (Ty.isNull()) {
4114         if (Literal.isSizeT)
4115           Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4116               << Literal.isUnsigned;
4117         else
4118           Diag(Tok.getLocation(),
4119                diag::ext_integer_literal_too_large_for_signed);
4120         Ty = Context.UnsignedLongLongTy;
4121         Width = Context.getTargetInfo().getLongLongWidth();
4122       }
4123 
4124       if (ResultVal.getBitWidth() != Width)
4125         ResultVal = ResultVal.trunc(Width);
4126     }
4127     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4128   }
4129 
4130   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4131   if (Literal.isImaginary) {
4132     Res = new (Context) ImaginaryLiteral(Res,
4133                                         Context.getComplexType(Res->getType()));
4134 
4135     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4136   }
4137   return Res;
4138 }
4139 
4140 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4141   assert(E && "ActOnParenExpr() missing expr");
4142   QualType ExprTy = E->getType();
4143   if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4144       !E->isLValue() && ExprTy->hasFloatingRepresentation())
4145     return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4146   return new (Context) ParenExpr(L, R, E);
4147 }
4148 
4149 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4150                                          SourceLocation Loc,
4151                                          SourceRange ArgRange) {
4152   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4153   // scalar or vector data type argument..."
4154   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4155   // type (C99 6.2.5p18) or void.
4156   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4157     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4158       << T << ArgRange;
4159     return true;
4160   }
4161 
4162   assert((T->isVoidType() || !T->isIncompleteType()) &&
4163          "Scalar types should always be complete");
4164   return false;
4165 }
4166 
4167 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4168                                            SourceLocation Loc,
4169                                            SourceRange ArgRange,
4170                                            UnaryExprOrTypeTrait TraitKind) {
4171   // Invalid types must be hard errors for SFINAE in C++.
4172   if (S.LangOpts.CPlusPlus)
4173     return true;
4174 
4175   // C99 6.5.3.4p1:
4176   if (T->isFunctionType() &&
4177       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4178        TraitKind == UETT_PreferredAlignOf)) {
4179     // sizeof(function)/alignof(function) is allowed as an extension.
4180     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4181         << getTraitSpelling(TraitKind) << ArgRange;
4182     return false;
4183   }
4184 
4185   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4186   // this is an error (OpenCL v1.1 s6.3.k)
4187   if (T->isVoidType()) {
4188     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4189                                         : diag::ext_sizeof_alignof_void_type;
4190     S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4191     return false;
4192   }
4193 
4194   return true;
4195 }
4196 
4197 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4198                                              SourceLocation Loc,
4199                                              SourceRange ArgRange,
4200                                              UnaryExprOrTypeTrait TraitKind) {
4201   // Reject sizeof(interface) and sizeof(interface<proto>) if the
4202   // runtime doesn't allow it.
4203   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4204     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4205       << T << (TraitKind == UETT_SizeOf)
4206       << ArgRange;
4207     return true;
4208   }
4209 
4210   return false;
4211 }
4212 
4213 /// Check whether E is a pointer from a decayed array type (the decayed
4214 /// pointer type is equal to T) and emit a warning if it is.
4215 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4216                                      Expr *E) {
4217   // Don't warn if the operation changed the type.
4218   if (T != E->getType())
4219     return;
4220 
4221   // Now look for array decays.
4222   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4223   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4224     return;
4225 
4226   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4227                                              << ICE->getType()
4228                                              << ICE->getSubExpr()->getType();
4229 }
4230 
4231 /// Check the constraints on expression operands to unary type expression
4232 /// and type traits.
4233 ///
4234 /// Completes any types necessary and validates the constraints on the operand
4235 /// expression. The logic mostly mirrors the type-based overload, but may modify
4236 /// the expression as it completes the type for that expression through template
4237 /// instantiation, etc.
4238 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4239                                             UnaryExprOrTypeTrait ExprKind) {
4240   QualType ExprTy = E->getType();
4241   assert(!ExprTy->isReferenceType());
4242 
4243   bool IsUnevaluatedOperand =
4244       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4245        ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4246   if (IsUnevaluatedOperand) {
4247     ExprResult Result = CheckUnevaluatedOperand(E);
4248     if (Result.isInvalid())
4249       return true;
4250     E = Result.get();
4251   }
4252 
4253   // The operand for sizeof and alignof is in an unevaluated expression context,
4254   // so side effects could result in unintended consequences.
4255   // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4256   // used to build SFINAE gadgets.
4257   // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4258   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4259       !E->isInstantiationDependent() &&
4260       E->HasSideEffects(Context, false))
4261     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4262 
4263   if (ExprKind == UETT_VecStep)
4264     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4265                                         E->getSourceRange());
4266 
4267   // Explicitly list some types as extensions.
4268   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4269                                       E->getSourceRange(), ExprKind))
4270     return false;
4271 
4272   // 'alignof' applied to an expression only requires the base element type of
4273   // the expression to be complete. 'sizeof' requires the expression's type to
4274   // be complete (and will attempt to complete it if it's an array of unknown
4275   // bound).
4276   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4277     if (RequireCompleteSizedType(
4278             E->getExprLoc(), Context.getBaseElementType(E->getType()),
4279             diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4280             getTraitSpelling(ExprKind), E->getSourceRange()))
4281       return true;
4282   } else {
4283     if (RequireCompleteSizedExprType(
4284             E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4285             getTraitSpelling(ExprKind), E->getSourceRange()))
4286       return true;
4287   }
4288 
4289   // Completing the expression's type may have changed it.
4290   ExprTy = E->getType();
4291   assert(!ExprTy->isReferenceType());
4292 
4293   if (ExprTy->isFunctionType()) {
4294     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4295         << getTraitSpelling(ExprKind) << E->getSourceRange();
4296     return true;
4297   }
4298 
4299   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4300                                        E->getSourceRange(), ExprKind))
4301     return true;
4302 
4303   if (ExprKind == UETT_SizeOf) {
4304     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4305       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4306         QualType OType = PVD->getOriginalType();
4307         QualType Type = PVD->getType();
4308         if (Type->isPointerType() && OType->isArrayType()) {
4309           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4310             << Type << OType;
4311           Diag(PVD->getLocation(), diag::note_declared_at);
4312         }
4313       }
4314     }
4315 
4316     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4317     // decays into a pointer and returns an unintended result. This is most
4318     // likely a typo for "sizeof(array) op x".
4319     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4320       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4321                                BO->getLHS());
4322       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4323                                BO->getRHS());
4324     }
4325   }
4326 
4327   return false;
4328 }
4329 
4330 /// Check the constraints on operands to unary expression and type
4331 /// traits.
4332 ///
4333 /// This will complete any types necessary, and validate the various constraints
4334 /// on those operands.
4335 ///
4336 /// The UsualUnaryConversions() function is *not* called by this routine.
4337 /// C99 6.3.2.1p[2-4] all state:
4338 ///   Except when it is the operand of the sizeof operator ...
4339 ///
4340 /// C++ [expr.sizeof]p4
4341 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4342 ///   standard conversions are not applied to the operand of sizeof.
4343 ///
4344 /// This policy is followed for all of the unary trait expressions.
4345 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4346                                             SourceLocation OpLoc,
4347                                             SourceRange ExprRange,
4348                                             UnaryExprOrTypeTrait ExprKind) {
4349   if (ExprType->isDependentType())
4350     return false;
4351 
4352   // C++ [expr.sizeof]p2:
4353   //     When applied to a reference or a reference type, the result
4354   //     is the size of the referenced type.
4355   // C++11 [expr.alignof]p3:
4356   //     When alignof is applied to a reference type, the result
4357   //     shall be the alignment of the referenced type.
4358   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4359     ExprType = Ref->getPointeeType();
4360 
4361   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4362   //   When alignof or _Alignof is applied to an array type, the result
4363   //   is the alignment of the element type.
4364   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4365       ExprKind == UETT_OpenMPRequiredSimdAlign)
4366     ExprType = Context.getBaseElementType(ExprType);
4367 
4368   if (ExprKind == UETT_VecStep)
4369     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4370 
4371   // Explicitly list some types as extensions.
4372   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4373                                       ExprKind))
4374     return false;
4375 
4376   if (RequireCompleteSizedType(
4377           OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4378           getTraitSpelling(ExprKind), ExprRange))
4379     return true;
4380 
4381   if (ExprType->isFunctionType()) {
4382     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4383         << getTraitSpelling(ExprKind) << ExprRange;
4384     return true;
4385   }
4386 
4387   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4388                                        ExprKind))
4389     return true;
4390 
4391   return false;
4392 }
4393 
4394 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4395   // Cannot know anything else if the expression is dependent.
4396   if (E->isTypeDependent())
4397     return false;
4398 
4399   if (E->getObjectKind() == OK_BitField) {
4400     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4401        << 1 << E->getSourceRange();
4402     return true;
4403   }
4404 
4405   ValueDecl *D = nullptr;
4406   Expr *Inner = E->IgnoreParens();
4407   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4408     D = DRE->getDecl();
4409   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4410     D = ME->getMemberDecl();
4411   }
4412 
4413   // If it's a field, require the containing struct to have a
4414   // complete definition so that we can compute the layout.
4415   //
4416   // This can happen in C++11 onwards, either by naming the member
4417   // in a way that is not transformed into a member access expression
4418   // (in an unevaluated operand, for instance), or by naming the member
4419   // in a trailing-return-type.
4420   //
4421   // For the record, since __alignof__ on expressions is a GCC
4422   // extension, GCC seems to permit this but always gives the
4423   // nonsensical answer 0.
4424   //
4425   // We don't really need the layout here --- we could instead just
4426   // directly check for all the appropriate alignment-lowing
4427   // attributes --- but that would require duplicating a lot of
4428   // logic that just isn't worth duplicating for such a marginal
4429   // use-case.
4430   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4431     // Fast path this check, since we at least know the record has a
4432     // definition if we can find a member of it.
4433     if (!FD->getParent()->isCompleteDefinition()) {
4434       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4435         << E->getSourceRange();
4436       return true;
4437     }
4438 
4439     // Otherwise, if it's a field, and the field doesn't have
4440     // reference type, then it must have a complete type (or be a
4441     // flexible array member, which we explicitly want to
4442     // white-list anyway), which makes the following checks trivial.
4443     if (!FD->getType()->isReferenceType())
4444       return false;
4445   }
4446 
4447   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4448 }
4449 
4450 bool Sema::CheckVecStepExpr(Expr *E) {
4451   E = E->IgnoreParens();
4452 
4453   // Cannot know anything else if the expression is dependent.
4454   if (E->isTypeDependent())
4455     return false;
4456 
4457   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4458 }
4459 
4460 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4461                                         CapturingScopeInfo *CSI) {
4462   assert(T->isVariablyModifiedType());
4463   assert(CSI != nullptr);
4464 
4465   // We're going to walk down into the type and look for VLA expressions.
4466   do {
4467     const Type *Ty = T.getTypePtr();
4468     switch (Ty->getTypeClass()) {
4469 #define TYPE(Class, Base)
4470 #define ABSTRACT_TYPE(Class, Base)
4471 #define NON_CANONICAL_TYPE(Class, Base)
4472 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4473 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4474 #include "clang/AST/TypeNodes.inc"
4475       T = QualType();
4476       break;
4477     // These types are never variably-modified.
4478     case Type::Builtin:
4479     case Type::Complex:
4480     case Type::Vector:
4481     case Type::ExtVector:
4482     case Type::ConstantMatrix:
4483     case Type::Record:
4484     case Type::Enum:
4485     case Type::Elaborated:
4486     case Type::TemplateSpecialization:
4487     case Type::ObjCObject:
4488     case Type::ObjCInterface:
4489     case Type::ObjCObjectPointer:
4490     case Type::ObjCTypeParam:
4491     case Type::Pipe:
4492     case Type::BitInt:
4493       llvm_unreachable("type class is never variably-modified!");
4494     case Type::Adjusted:
4495       T = cast<AdjustedType>(Ty)->getOriginalType();
4496       break;
4497     case Type::Decayed:
4498       T = cast<DecayedType>(Ty)->getPointeeType();
4499       break;
4500     case Type::Pointer:
4501       T = cast<PointerType>(Ty)->getPointeeType();
4502       break;
4503     case Type::BlockPointer:
4504       T = cast<BlockPointerType>(Ty)->getPointeeType();
4505       break;
4506     case Type::LValueReference:
4507     case Type::RValueReference:
4508       T = cast<ReferenceType>(Ty)->getPointeeType();
4509       break;
4510     case Type::MemberPointer:
4511       T = cast<MemberPointerType>(Ty)->getPointeeType();
4512       break;
4513     case Type::ConstantArray:
4514     case Type::IncompleteArray:
4515       // Losing element qualification here is fine.
4516       T = cast<ArrayType>(Ty)->getElementType();
4517       break;
4518     case Type::VariableArray: {
4519       // Losing element qualification here is fine.
4520       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4521 
4522       // Unknown size indication requires no size computation.
4523       // Otherwise, evaluate and record it.
4524       auto Size = VAT->getSizeExpr();
4525       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4526           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4527         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4528 
4529       T = VAT->getElementType();
4530       break;
4531     }
4532     case Type::FunctionProto:
4533     case Type::FunctionNoProto:
4534       T = cast<FunctionType>(Ty)->getReturnType();
4535       break;
4536     case Type::Paren:
4537     case Type::TypeOf:
4538     case Type::UnaryTransform:
4539     case Type::Attributed:
4540     case Type::BTFTagAttributed:
4541     case Type::SubstTemplateTypeParm:
4542     case Type::MacroQualified:
4543       // Keep walking after single level desugaring.
4544       T = T.getSingleStepDesugaredType(Context);
4545       break;
4546     case Type::Typedef:
4547       T = cast<TypedefType>(Ty)->desugar();
4548       break;
4549     case Type::Decltype:
4550       T = cast<DecltypeType>(Ty)->desugar();
4551       break;
4552     case Type::Using:
4553       T = cast<UsingType>(Ty)->desugar();
4554       break;
4555     case Type::Auto:
4556     case Type::DeducedTemplateSpecialization:
4557       T = cast<DeducedType>(Ty)->getDeducedType();
4558       break;
4559     case Type::TypeOfExpr:
4560       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4561       break;
4562     case Type::Atomic:
4563       T = cast<AtomicType>(Ty)->getValueType();
4564       break;
4565     }
4566   } while (!T.isNull() && T->isVariablyModifiedType());
4567 }
4568 
4569 /// Build a sizeof or alignof expression given a type operand.
4570 ExprResult
4571 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4572                                      SourceLocation OpLoc,
4573                                      UnaryExprOrTypeTrait ExprKind,
4574                                      SourceRange R) {
4575   if (!TInfo)
4576     return ExprError();
4577 
4578   QualType T = TInfo->getType();
4579 
4580   if (!T->isDependentType() &&
4581       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4582     return ExprError();
4583 
4584   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4585     if (auto *TT = T->getAs<TypedefType>()) {
4586       for (auto I = FunctionScopes.rbegin(),
4587                 E = std::prev(FunctionScopes.rend());
4588            I != E; ++I) {
4589         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4590         if (CSI == nullptr)
4591           break;
4592         DeclContext *DC = nullptr;
4593         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4594           DC = LSI->CallOperator;
4595         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4596           DC = CRSI->TheCapturedDecl;
4597         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4598           DC = BSI->TheDecl;
4599         if (DC) {
4600           if (DC->containsDecl(TT->getDecl()))
4601             break;
4602           captureVariablyModifiedType(Context, T, CSI);
4603         }
4604       }
4605     }
4606   }
4607 
4608   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4609   if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4610       TInfo->getType()->isVariablyModifiedType())
4611     TInfo = TransformToPotentiallyEvaluated(TInfo);
4612 
4613   return new (Context) UnaryExprOrTypeTraitExpr(
4614       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4615 }
4616 
4617 /// Build a sizeof or alignof expression given an expression
4618 /// operand.
4619 ExprResult
4620 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4621                                      UnaryExprOrTypeTrait ExprKind) {
4622   ExprResult PE = CheckPlaceholderExpr(E);
4623   if (PE.isInvalid())
4624     return ExprError();
4625 
4626   E = PE.get();
4627 
4628   // Verify that the operand is valid.
4629   bool isInvalid = false;
4630   if (E->isTypeDependent()) {
4631     // Delay type-checking for type-dependent expressions.
4632   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4633     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4634   } else if (ExprKind == UETT_VecStep) {
4635     isInvalid = CheckVecStepExpr(E);
4636   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4637       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4638       isInvalid = true;
4639   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4640     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4641     isInvalid = true;
4642   } else {
4643     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4644   }
4645 
4646   if (isInvalid)
4647     return ExprError();
4648 
4649   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4650     PE = TransformToPotentiallyEvaluated(E);
4651     if (PE.isInvalid()) return ExprError();
4652     E = PE.get();
4653   }
4654 
4655   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4656   return new (Context) UnaryExprOrTypeTraitExpr(
4657       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4658 }
4659 
4660 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4661 /// expr and the same for @c alignof and @c __alignof
4662 /// Note that the ArgRange is invalid if isType is false.
4663 ExprResult
4664 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4665                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4666                                     void *TyOrEx, SourceRange ArgRange) {
4667   // If error parsing type, ignore.
4668   if (!TyOrEx) return ExprError();
4669 
4670   if (IsType) {
4671     TypeSourceInfo *TInfo;
4672     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4673     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4674   }
4675 
4676   Expr *ArgEx = (Expr *)TyOrEx;
4677   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4678   return Result;
4679 }
4680 
4681 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4682                                      bool IsReal) {
4683   if (V.get()->isTypeDependent())
4684     return S.Context.DependentTy;
4685 
4686   // _Real and _Imag are only l-values for normal l-values.
4687   if (V.get()->getObjectKind() != OK_Ordinary) {
4688     V = S.DefaultLvalueConversion(V.get());
4689     if (V.isInvalid())
4690       return QualType();
4691   }
4692 
4693   // These operators return the element type of a complex type.
4694   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4695     return CT->getElementType();
4696 
4697   // Otherwise they pass through real integer and floating point types here.
4698   if (V.get()->getType()->isArithmeticType())
4699     return V.get()->getType();
4700 
4701   // Test for placeholders.
4702   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4703   if (PR.isInvalid()) return QualType();
4704   if (PR.get() != V.get()) {
4705     V = PR;
4706     return CheckRealImagOperand(S, V, Loc, IsReal);
4707   }
4708 
4709   // Reject anything else.
4710   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4711     << (IsReal ? "__real" : "__imag");
4712   return QualType();
4713 }
4714 
4715 
4716 
4717 ExprResult
4718 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4719                           tok::TokenKind Kind, Expr *Input) {
4720   UnaryOperatorKind Opc;
4721   switch (Kind) {
4722   default: llvm_unreachable("Unknown unary op!");
4723   case tok::plusplus:   Opc = UO_PostInc; break;
4724   case tok::minusminus: Opc = UO_PostDec; break;
4725   }
4726 
4727   // Since this might is a postfix expression, get rid of ParenListExprs.
4728   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4729   if (Result.isInvalid()) return ExprError();
4730   Input = Result.get();
4731 
4732   return BuildUnaryOp(S, OpLoc, Opc, Input);
4733 }
4734 
4735 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4736 ///
4737 /// \return true on error
4738 static bool checkArithmeticOnObjCPointer(Sema &S,
4739                                          SourceLocation opLoc,
4740                                          Expr *op) {
4741   assert(op->getType()->isObjCObjectPointerType());
4742   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4743       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4744     return false;
4745 
4746   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4747     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4748     << op->getSourceRange();
4749   return true;
4750 }
4751 
4752 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4753   auto *BaseNoParens = Base->IgnoreParens();
4754   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4755     return MSProp->getPropertyDecl()->getType()->isArrayType();
4756   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4757 }
4758 
4759 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4760 // Typically this is DependentTy, but can sometimes be more precise.
4761 //
4762 // There are cases when we could determine a non-dependent type:
4763 //  - LHS and RHS may have non-dependent types despite being type-dependent
4764 //    (e.g. unbounded array static members of the current instantiation)
4765 //  - one may be a dependent-sized array with known element type
4766 //  - one may be a dependent-typed valid index (enum in current instantiation)
4767 //
4768 // We *always* return a dependent type, in such cases it is DependentTy.
4769 // This avoids creating type-dependent expressions with non-dependent types.
4770 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4771 static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
4772                                                const ASTContext &Ctx) {
4773   assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4774   QualType LTy = LHS->getType(), RTy = RHS->getType();
4775   QualType Result = Ctx.DependentTy;
4776   if (RTy->isIntegralOrUnscopedEnumerationType()) {
4777     if (const PointerType *PT = LTy->getAs<PointerType>())
4778       Result = PT->getPointeeType();
4779     else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4780       Result = AT->getElementType();
4781   } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4782     if (const PointerType *PT = RTy->getAs<PointerType>())
4783       Result = PT->getPointeeType();
4784     else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4785       Result = AT->getElementType();
4786   }
4787   // Ensure we return a dependent type.
4788   return Result->isDependentType() ? Result : Ctx.DependentTy;
4789 }
4790 
4791 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args);
4792 
4793 ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
4794                                          SourceLocation lbLoc,
4795                                          MultiExprArg ArgExprs,
4796                                          SourceLocation rbLoc) {
4797 
4798   if (base && !base->getType().isNull() &&
4799       base->hasPlaceholderType(BuiltinType::OMPArraySection))
4800     return ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(), SourceLocation(),
4801                                     SourceLocation(), /*Length*/ nullptr,
4802                                     /*Stride=*/nullptr, rbLoc);
4803 
4804   // Since this might be a postfix expression, get rid of ParenListExprs.
4805   if (isa<ParenListExpr>(base)) {
4806     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4807     if (result.isInvalid())
4808       return ExprError();
4809     base = result.get();
4810   }
4811 
4812   // Check if base and idx form a MatrixSubscriptExpr.
4813   //
4814   // Helper to check for comma expressions, which are not allowed as indices for
4815   // matrix subscript expressions.
4816   auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4817     if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4818       Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4819           << SourceRange(base->getBeginLoc(), rbLoc);
4820       return true;
4821     }
4822     return false;
4823   };
4824   // The matrix subscript operator ([][])is considered a single operator.
4825   // Separating the index expressions by parenthesis is not allowed.
4826   if (base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4827       !isa<MatrixSubscriptExpr>(base)) {
4828     Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4829         << SourceRange(base->getBeginLoc(), rbLoc);
4830     return ExprError();
4831   }
4832   // If the base is a MatrixSubscriptExpr, try to create a new
4833   // MatrixSubscriptExpr.
4834   auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4835   if (matSubscriptE) {
4836     assert(ArgExprs.size() == 1);
4837     if (CheckAndReportCommaError(ArgExprs.front()))
4838       return ExprError();
4839 
4840     assert(matSubscriptE->isIncomplete() &&
4841            "base has to be an incomplete matrix subscript");
4842     return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4843                                             matSubscriptE->getRowIdx(),
4844                                             ArgExprs.front(), rbLoc);
4845   }
4846 
4847   // Handle any non-overload placeholder types in the base and index
4848   // expressions.  We can't handle overloads here because the other
4849   // operand might be an overloadable type, in which case the overload
4850   // resolution for the operator overload should get the first crack
4851   // at the overload.
4852   bool IsMSPropertySubscript = false;
4853   if (base->getType()->isNonOverloadPlaceholderType()) {
4854     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4855     if (!IsMSPropertySubscript) {
4856       ExprResult result = CheckPlaceholderExpr(base);
4857       if (result.isInvalid())
4858         return ExprError();
4859       base = result.get();
4860     }
4861   }
4862 
4863   // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4864   if (base->getType()->isMatrixType()) {
4865     assert(ArgExprs.size() == 1);
4866     if (CheckAndReportCommaError(ArgExprs.front()))
4867       return ExprError();
4868 
4869     return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4870                                             rbLoc);
4871   }
4872 
4873   if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4874     Expr *idx = ArgExprs[0];
4875     if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4876         (isa<CXXOperatorCallExpr>(idx) &&
4877          cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4878       Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4879           << SourceRange(base->getBeginLoc(), rbLoc);
4880     }
4881   }
4882 
4883   if (ArgExprs.size() == 1 &&
4884       ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4885     ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4886     if (result.isInvalid())
4887       return ExprError();
4888     ArgExprs[0] = result.get();
4889   } else {
4890     if (checkArgsForPlaceholders(*this, ArgExprs))
4891       return ExprError();
4892   }
4893 
4894   // Build an unanalyzed expression if either operand is type-dependent.
4895   if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4896       (base->isTypeDependent() ||
4897        Expr::hasAnyTypeDependentArguments(ArgExprs))) {
4898     return new (Context) ArraySubscriptExpr(
4899         base, ArgExprs.front(),
4900         getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4901         VK_LValue, OK_Ordinary, rbLoc);
4902   }
4903 
4904   // MSDN, property (C++)
4905   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4906   // This attribute can also be used in the declaration of an empty array in a
4907   // class or structure definition. For example:
4908   // __declspec(property(get=GetX, put=PutX)) int x[];
4909   // The above statement indicates that x[] can be used with one or more array
4910   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4911   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4912   if (IsMSPropertySubscript) {
4913     assert(ArgExprs.size() == 1);
4914     // Build MS property subscript expression if base is MS property reference
4915     // or MS property subscript.
4916     return new (Context)
4917         MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4918                                 VK_LValue, OK_Ordinary, rbLoc);
4919   }
4920 
4921   // Use C++ overloaded-operator rules if either operand has record
4922   // type.  The spec says to do this if either type is *overloadable*,
4923   // but enum types can't declare subscript operators or conversion
4924   // operators, so there's nothing interesting for overload resolution
4925   // to do if there aren't any record types involved.
4926   //
4927   // ObjC pointers have their own subscripting logic that is not tied
4928   // to overload resolution and so should not take this path.
4929   if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4930       ((base->getType()->isRecordType() ||
4931         (ArgExprs.size() != 1 || ArgExprs[0]->getType()->isRecordType())))) {
4932     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4933   }
4934 
4935   ExprResult Res =
4936       CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4937 
4938   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4939     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4940 
4941   return Res;
4942 }
4943 
4944 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4945   InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4946   InitializationKind Kind =
4947       InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4948   InitializationSequence InitSeq(*this, Entity, Kind, E);
4949   return InitSeq.Perform(*this, Entity, Kind, E);
4950 }
4951 
4952 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4953                                                   Expr *ColumnIdx,
4954                                                   SourceLocation RBLoc) {
4955   ExprResult BaseR = CheckPlaceholderExpr(Base);
4956   if (BaseR.isInvalid())
4957     return BaseR;
4958   Base = BaseR.get();
4959 
4960   ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4961   if (RowR.isInvalid())
4962     return RowR;
4963   RowIdx = RowR.get();
4964 
4965   if (!ColumnIdx)
4966     return new (Context) MatrixSubscriptExpr(
4967         Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4968 
4969   // Build an unanalyzed expression if any of the operands is type-dependent.
4970   if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4971       ColumnIdx->isTypeDependent())
4972     return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4973                                              Context.DependentTy, RBLoc);
4974 
4975   ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4976   if (ColumnR.isInvalid())
4977     return ColumnR;
4978   ColumnIdx = ColumnR.get();
4979 
4980   // Check that IndexExpr is an integer expression. If it is a constant
4981   // expression, check that it is less than Dim (= the number of elements in the
4982   // corresponding dimension).
4983   auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4984                           bool IsColumnIdx) -> Expr * {
4985     if (!IndexExpr->getType()->isIntegerType() &&
4986         !IndexExpr->isTypeDependent()) {
4987       Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4988           << IsColumnIdx;
4989       return nullptr;
4990     }
4991 
4992     if (Optional<llvm::APSInt> Idx =
4993             IndexExpr->getIntegerConstantExpr(Context)) {
4994       if ((*Idx < 0 || *Idx >= Dim)) {
4995         Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4996             << IsColumnIdx << Dim;
4997         return nullptr;
4998       }
4999     }
5000 
5001     ExprResult ConvExpr =
5002         tryConvertExprToType(IndexExpr, Context.getSizeType());
5003     assert(!ConvExpr.isInvalid() &&
5004            "should be able to convert any integer type to size type");
5005     return ConvExpr.get();
5006   };
5007 
5008   auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5009   RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5010   ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5011   if (!RowIdx || !ColumnIdx)
5012     return ExprError();
5013 
5014   return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5015                                            MTy->getElementType(), RBLoc);
5016 }
5017 
5018 void Sema::CheckAddressOfNoDeref(const Expr *E) {
5019   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5020   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5021 
5022   // For expressions like `&(*s).b`, the base is recorded and what should be
5023   // checked.
5024   const MemberExpr *Member = nullptr;
5025   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5026     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5027 
5028   LastRecord.PossibleDerefs.erase(StrippedExpr);
5029 }
5030 
5031 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5032   if (isUnevaluatedContext())
5033     return;
5034 
5035   QualType ResultTy = E->getType();
5036   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5037 
5038   // Bail if the element is an array since it is not memory access.
5039   if (isa<ArrayType>(ResultTy))
5040     return;
5041 
5042   if (ResultTy->hasAttr(attr::NoDeref)) {
5043     LastRecord.PossibleDerefs.insert(E);
5044     return;
5045   }
5046 
5047   // Check if the base type is a pointer to a member access of a struct
5048   // marked with noderef.
5049   const Expr *Base = E->getBase();
5050   QualType BaseTy = Base->getType();
5051   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5052     // Not a pointer access
5053     return;
5054 
5055   const MemberExpr *Member = nullptr;
5056   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5057          Member->isArrow())
5058     Base = Member->getBase();
5059 
5060   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5061     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5062       LastRecord.PossibleDerefs.insert(E);
5063   }
5064 }
5065 
5066 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5067                                           Expr *LowerBound,
5068                                           SourceLocation ColonLocFirst,
5069                                           SourceLocation ColonLocSecond,
5070                                           Expr *Length, Expr *Stride,
5071                                           SourceLocation RBLoc) {
5072   if (Base->hasPlaceholderType() &&
5073       !Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5074     ExprResult Result = CheckPlaceholderExpr(Base);
5075     if (Result.isInvalid())
5076       return ExprError();
5077     Base = Result.get();
5078   }
5079   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
5080     ExprResult Result = CheckPlaceholderExpr(LowerBound);
5081     if (Result.isInvalid())
5082       return ExprError();
5083     Result = DefaultLvalueConversion(Result.get());
5084     if (Result.isInvalid())
5085       return ExprError();
5086     LowerBound = Result.get();
5087   }
5088   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
5089     ExprResult Result = CheckPlaceholderExpr(Length);
5090     if (Result.isInvalid())
5091       return ExprError();
5092     Result = DefaultLvalueConversion(Result.get());
5093     if (Result.isInvalid())
5094       return ExprError();
5095     Length = Result.get();
5096   }
5097   if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
5098     ExprResult Result = CheckPlaceholderExpr(Stride);
5099     if (Result.isInvalid())
5100       return ExprError();
5101     Result = DefaultLvalueConversion(Result.get());
5102     if (Result.isInvalid())
5103       return ExprError();
5104     Stride = Result.get();
5105   }
5106 
5107   // Build an unanalyzed expression if either operand is type-dependent.
5108   if (Base->isTypeDependent() ||
5109       (LowerBound &&
5110        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
5111       (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
5112       (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
5113     return new (Context) OMPArraySectionExpr(
5114         Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
5115         OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5116   }
5117 
5118   // Perform default conversions.
5119   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
5120   QualType ResultTy;
5121   if (OriginalTy->isAnyPointerType()) {
5122     ResultTy = OriginalTy->getPointeeType();
5123   } else if (OriginalTy->isArrayType()) {
5124     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
5125   } else {
5126     return ExprError(
5127         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
5128         << Base->getSourceRange());
5129   }
5130   // C99 6.5.2.1p1
5131   if (LowerBound) {
5132     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
5133                                                       LowerBound);
5134     if (Res.isInvalid())
5135       return ExprError(Diag(LowerBound->getExprLoc(),
5136                             diag::err_omp_typecheck_section_not_integer)
5137                        << 0 << LowerBound->getSourceRange());
5138     LowerBound = Res.get();
5139 
5140     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5141         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5142       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
5143           << 0 << LowerBound->getSourceRange();
5144   }
5145   if (Length) {
5146     auto Res =
5147         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
5148     if (Res.isInvalid())
5149       return ExprError(Diag(Length->getExprLoc(),
5150                             diag::err_omp_typecheck_section_not_integer)
5151                        << 1 << Length->getSourceRange());
5152     Length = Res.get();
5153 
5154     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5155         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5156       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
5157           << 1 << Length->getSourceRange();
5158   }
5159   if (Stride) {
5160     ExprResult Res =
5161         PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
5162     if (Res.isInvalid())
5163       return ExprError(Diag(Stride->getExprLoc(),
5164                             diag::err_omp_typecheck_section_not_integer)
5165                        << 1 << Stride->getSourceRange());
5166     Stride = Res.get();
5167 
5168     if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5169         Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5170       Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
5171           << 1 << Stride->getSourceRange();
5172   }
5173 
5174   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5175   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5176   // type. Note that functions are not objects, and that (in C99 parlance)
5177   // incomplete types are not object types.
5178   if (ResultTy->isFunctionType()) {
5179     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
5180         << ResultTy << Base->getSourceRange();
5181     return ExprError();
5182   }
5183 
5184   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5185                           diag::err_omp_section_incomplete_type, Base))
5186     return ExprError();
5187 
5188   if (LowerBound && !OriginalTy->isAnyPointerType()) {
5189     Expr::EvalResult Result;
5190     if (LowerBound->EvaluateAsInt(Result, Context)) {
5191       // OpenMP 5.0, [2.1.5 Array Sections]
5192       // The array section must be a subset of the original array.
5193       llvm::APSInt LowerBoundValue = Result.Val.getInt();
5194       if (LowerBoundValue.isNegative()) {
5195         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5196             << LowerBound->getSourceRange();
5197         return ExprError();
5198       }
5199     }
5200   }
5201 
5202   if (Length) {
5203     Expr::EvalResult Result;
5204     if (Length->EvaluateAsInt(Result, Context)) {
5205       // OpenMP 5.0, [2.1.5 Array Sections]
5206       // The length must evaluate to non-negative integers.
5207       llvm::APSInt LengthValue = Result.Val.getInt();
5208       if (LengthValue.isNegative()) {
5209         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5210             << toString(LengthValue, /*Radix=*/10, /*Signed=*/true)
5211             << Length->getSourceRange();
5212         return ExprError();
5213       }
5214     }
5215   } else if (ColonLocFirst.isValid() &&
5216              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5217                                       !OriginalTy->isVariableArrayType()))) {
5218     // OpenMP 5.0, [2.1.5 Array Sections]
5219     // When the size of the array dimension is not known, the length must be
5220     // specified explicitly.
5221     Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5222         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5223     return ExprError();
5224   }
5225 
5226   if (Stride) {
5227     Expr::EvalResult Result;
5228     if (Stride->EvaluateAsInt(Result, Context)) {
5229       // OpenMP 5.0, [2.1.5 Array Sections]
5230       // The stride must evaluate to a positive integer.
5231       llvm::APSInt StrideValue = Result.Val.getInt();
5232       if (!StrideValue.isStrictlyPositive()) {
5233         Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5234             << toString(StrideValue, /*Radix=*/10, /*Signed=*/true)
5235             << Stride->getSourceRange();
5236         return ExprError();
5237       }
5238     }
5239   }
5240 
5241   if (!Base->hasPlaceholderType(BuiltinType::OMPArraySection)) {
5242     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5243     if (Result.isInvalid())
5244       return ExprError();
5245     Base = Result.get();
5246   }
5247   return new (Context) OMPArraySectionExpr(
5248       Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5249       OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5250 }
5251 
5252 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5253                                           SourceLocation RParenLoc,
5254                                           ArrayRef<Expr *> Dims,
5255                                           ArrayRef<SourceRange> Brackets) {
5256   if (Base->hasPlaceholderType()) {
5257     ExprResult Result = CheckPlaceholderExpr(Base);
5258     if (Result.isInvalid())
5259       return ExprError();
5260     Result = DefaultLvalueConversion(Result.get());
5261     if (Result.isInvalid())
5262       return ExprError();
5263     Base = Result.get();
5264   }
5265   QualType BaseTy = Base->getType();
5266   // Delay analysis of the types/expressions if instantiation/specialization is
5267   // required.
5268   if (!BaseTy->isPointerType() && Base->isTypeDependent())
5269     return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5270                                        LParenLoc, RParenLoc, Dims, Brackets);
5271   if (!BaseTy->isPointerType() ||
5272       (!Base->isTypeDependent() &&
5273        BaseTy->getPointeeType()->isIncompleteType()))
5274     return ExprError(Diag(Base->getExprLoc(),
5275                           diag::err_omp_non_pointer_type_array_shaping_base)
5276                      << Base->getSourceRange());
5277 
5278   SmallVector<Expr *, 4> NewDims;
5279   bool ErrorFound = false;
5280   for (Expr *Dim : Dims) {
5281     if (Dim->hasPlaceholderType()) {
5282       ExprResult Result = CheckPlaceholderExpr(Dim);
5283       if (Result.isInvalid()) {
5284         ErrorFound = true;
5285         continue;
5286       }
5287       Result = DefaultLvalueConversion(Result.get());
5288       if (Result.isInvalid()) {
5289         ErrorFound = true;
5290         continue;
5291       }
5292       Dim = Result.get();
5293     }
5294     if (!Dim->isTypeDependent()) {
5295       ExprResult Result =
5296           PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5297       if (Result.isInvalid()) {
5298         ErrorFound = true;
5299         Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5300             << Dim->getSourceRange();
5301         continue;
5302       }
5303       Dim = Result.get();
5304       Expr::EvalResult EvResult;
5305       if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5306         // OpenMP 5.0, [2.1.4 Array Shaping]
5307         // Each si is an integral type expression that must evaluate to a
5308         // positive integer.
5309         llvm::APSInt Value = EvResult.Val.getInt();
5310         if (!Value.isStrictlyPositive()) {
5311           Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5312               << toString(Value, /*Radix=*/10, /*Signed=*/true)
5313               << Dim->getSourceRange();
5314           ErrorFound = true;
5315           continue;
5316         }
5317       }
5318     }
5319     NewDims.push_back(Dim);
5320   }
5321   if (ErrorFound)
5322     return ExprError();
5323   return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5324                                      LParenLoc, RParenLoc, NewDims, Brackets);
5325 }
5326 
5327 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5328                                       SourceLocation LLoc, SourceLocation RLoc,
5329                                       ArrayRef<OMPIteratorData> Data) {
5330   SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5331   bool IsCorrect = true;
5332   for (const OMPIteratorData &D : Data) {
5333     TypeSourceInfo *TInfo = nullptr;
5334     SourceLocation StartLoc;
5335     QualType DeclTy;
5336     if (!D.Type.getAsOpaquePtr()) {
5337       // OpenMP 5.0, 2.1.6 Iterators
5338       // In an iterator-specifier, if the iterator-type is not specified then
5339       // the type of that iterator is of int type.
5340       DeclTy = Context.IntTy;
5341       StartLoc = D.DeclIdentLoc;
5342     } else {
5343       DeclTy = GetTypeFromParser(D.Type, &TInfo);
5344       StartLoc = TInfo->getTypeLoc().getBeginLoc();
5345     }
5346 
5347     bool IsDeclTyDependent = DeclTy->isDependentType() ||
5348                              DeclTy->containsUnexpandedParameterPack() ||
5349                              DeclTy->isInstantiationDependentType();
5350     if (!IsDeclTyDependent) {
5351       if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5352         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5353         // The iterator-type must be an integral or pointer type.
5354         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5355             << DeclTy;
5356         IsCorrect = false;
5357         continue;
5358       }
5359       if (DeclTy.isConstant(Context)) {
5360         // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5361         // The iterator-type must not be const qualified.
5362         Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5363             << DeclTy;
5364         IsCorrect = false;
5365         continue;
5366       }
5367     }
5368 
5369     // Iterator declaration.
5370     assert(D.DeclIdent && "Identifier expected.");
5371     // Always try to create iterator declarator to avoid extra error messages
5372     // about unknown declarations use.
5373     auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5374                                D.DeclIdent, DeclTy, TInfo, SC_None);
5375     VD->setImplicit();
5376     if (S) {
5377       // Check for conflicting previous declaration.
5378       DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5379       LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5380                             ForVisibleRedeclaration);
5381       Previous.suppressDiagnostics();
5382       LookupName(Previous, S);
5383 
5384       FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5385                            /*AllowInlineNamespace=*/false);
5386       if (!Previous.empty()) {
5387         NamedDecl *Old = Previous.getRepresentativeDecl();
5388         Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5389         Diag(Old->getLocation(), diag::note_previous_definition);
5390       } else {
5391         PushOnScopeChains(VD, S);
5392       }
5393     } else {
5394       CurContext->addDecl(VD);
5395     }
5396     Expr *Begin = D.Range.Begin;
5397     if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5398       ExprResult BeginRes =
5399           PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5400       Begin = BeginRes.get();
5401     }
5402     Expr *End = D.Range.End;
5403     if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5404       ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5405       End = EndRes.get();
5406     }
5407     Expr *Step = D.Range.Step;
5408     if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5409       if (!Step->getType()->isIntegralType(Context)) {
5410         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5411             << Step << Step->getSourceRange();
5412         IsCorrect = false;
5413         continue;
5414       }
5415       Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5416       // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5417       // If the step expression of a range-specification equals zero, the
5418       // behavior is unspecified.
5419       if (Result && Result->isZero()) {
5420         Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5421             << Step << Step->getSourceRange();
5422         IsCorrect = false;
5423         continue;
5424       }
5425     }
5426     if (!Begin || !End || !IsCorrect) {
5427       IsCorrect = false;
5428       continue;
5429     }
5430     OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5431     IDElem.IteratorDecl = VD;
5432     IDElem.AssignmentLoc = D.AssignLoc;
5433     IDElem.Range.Begin = Begin;
5434     IDElem.Range.End = End;
5435     IDElem.Range.Step = Step;
5436     IDElem.ColonLoc = D.ColonLoc;
5437     IDElem.SecondColonLoc = D.SecColonLoc;
5438   }
5439   if (!IsCorrect) {
5440     // Invalidate all created iterator declarations if error is found.
5441     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5442       if (Decl *ID = D.IteratorDecl)
5443         ID->setInvalidDecl();
5444     }
5445     return ExprError();
5446   }
5447   SmallVector<OMPIteratorHelperData, 4> Helpers;
5448   if (!CurContext->isDependentContext()) {
5449     // Build number of ityeration for each iteration range.
5450     // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5451     // ((Begini-Stepi-1-Endi) / -Stepi);
5452     for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5453       // (Endi - Begini)
5454       ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5455                                           D.Range.Begin);
5456       if(!Res.isUsable()) {
5457         IsCorrect = false;
5458         continue;
5459       }
5460       ExprResult St, St1;
5461       if (D.Range.Step) {
5462         St = D.Range.Step;
5463         // (Endi - Begini) + Stepi
5464         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5465         if (!Res.isUsable()) {
5466           IsCorrect = false;
5467           continue;
5468         }
5469         // (Endi - Begini) + Stepi - 1
5470         Res =
5471             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5472                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5473         if (!Res.isUsable()) {
5474           IsCorrect = false;
5475           continue;
5476         }
5477         // ((Endi - Begini) + Stepi - 1) / Stepi
5478         Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5479         if (!Res.isUsable()) {
5480           IsCorrect = false;
5481           continue;
5482         }
5483         St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5484         // (Begini - Endi)
5485         ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5486                                              D.Range.Begin, D.Range.End);
5487         if (!Res1.isUsable()) {
5488           IsCorrect = false;
5489           continue;
5490         }
5491         // (Begini - Endi) - Stepi
5492         Res1 =
5493             CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5494         if (!Res1.isUsable()) {
5495           IsCorrect = false;
5496           continue;
5497         }
5498         // (Begini - Endi) - Stepi - 1
5499         Res1 =
5500             CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5501                                ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5502         if (!Res1.isUsable()) {
5503           IsCorrect = false;
5504           continue;
5505         }
5506         // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5507         Res1 =
5508             CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5509         if (!Res1.isUsable()) {
5510           IsCorrect = false;
5511           continue;
5512         }
5513         // Stepi > 0.
5514         ExprResult CmpRes =
5515             CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5516                                ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5517         if (!CmpRes.isUsable()) {
5518           IsCorrect = false;
5519           continue;
5520         }
5521         Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5522                                  Res.get(), Res1.get());
5523         if (!Res.isUsable()) {
5524           IsCorrect = false;
5525           continue;
5526         }
5527       }
5528       Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5529       if (!Res.isUsable()) {
5530         IsCorrect = false;
5531         continue;
5532       }
5533 
5534       // Build counter update.
5535       // Build counter.
5536       auto *CounterVD =
5537           VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5538                           D.IteratorDecl->getBeginLoc(), nullptr,
5539                           Res.get()->getType(), nullptr, SC_None);
5540       CounterVD->setImplicit();
5541       ExprResult RefRes =
5542           BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5543                            D.IteratorDecl->getBeginLoc());
5544       // Build counter update.
5545       // I = Begini + counter * Stepi;
5546       ExprResult UpdateRes;
5547       if (D.Range.Step) {
5548         UpdateRes = CreateBuiltinBinOp(
5549             D.AssignmentLoc, BO_Mul,
5550             DefaultLvalueConversion(RefRes.get()).get(), St.get());
5551       } else {
5552         UpdateRes = DefaultLvalueConversion(RefRes.get());
5553       }
5554       if (!UpdateRes.isUsable()) {
5555         IsCorrect = false;
5556         continue;
5557       }
5558       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5559                                      UpdateRes.get());
5560       if (!UpdateRes.isUsable()) {
5561         IsCorrect = false;
5562         continue;
5563       }
5564       ExprResult VDRes =
5565           BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5566                            cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5567                            D.IteratorDecl->getBeginLoc());
5568       UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5569                                      UpdateRes.get());
5570       if (!UpdateRes.isUsable()) {
5571         IsCorrect = false;
5572         continue;
5573       }
5574       UpdateRes =
5575           ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5576       if (!UpdateRes.isUsable()) {
5577         IsCorrect = false;
5578         continue;
5579       }
5580       ExprResult CounterUpdateRes =
5581           CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5582       if (!CounterUpdateRes.isUsable()) {
5583         IsCorrect = false;
5584         continue;
5585       }
5586       CounterUpdateRes =
5587           ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5588       if (!CounterUpdateRes.isUsable()) {
5589         IsCorrect = false;
5590         continue;
5591       }
5592       OMPIteratorHelperData &HD = Helpers.emplace_back();
5593       HD.CounterVD = CounterVD;
5594       HD.Upper = Res.get();
5595       HD.Update = UpdateRes.get();
5596       HD.CounterUpdate = CounterUpdateRes.get();
5597     }
5598   } else {
5599     Helpers.assign(ID.size(), {});
5600   }
5601   if (!IsCorrect) {
5602     // Invalidate all created iterator declarations if error is found.
5603     for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5604       if (Decl *ID = D.IteratorDecl)
5605         ID->setInvalidDecl();
5606     }
5607     return ExprError();
5608   }
5609   return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5610                                  LLoc, RLoc, ID, Helpers);
5611 }
5612 
5613 ExprResult
5614 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5615                                       Expr *Idx, SourceLocation RLoc) {
5616   Expr *LHSExp = Base;
5617   Expr *RHSExp = Idx;
5618 
5619   ExprValueKind VK = VK_LValue;
5620   ExprObjectKind OK = OK_Ordinary;
5621 
5622   // Per C++ core issue 1213, the result is an xvalue if either operand is
5623   // a non-lvalue array, and an lvalue otherwise.
5624   if (getLangOpts().CPlusPlus11) {
5625     for (auto *Op : {LHSExp, RHSExp}) {
5626       Op = Op->IgnoreImplicit();
5627       if (Op->getType()->isArrayType() && !Op->isLValue())
5628         VK = VK_XValue;
5629     }
5630   }
5631 
5632   // Perform default conversions.
5633   if (!LHSExp->getType()->getAs<VectorType>()) {
5634     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5635     if (Result.isInvalid())
5636       return ExprError();
5637     LHSExp = Result.get();
5638   }
5639   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5640   if (Result.isInvalid())
5641     return ExprError();
5642   RHSExp = Result.get();
5643 
5644   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5645 
5646   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5647   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5648   // in the subscript position. As a result, we need to derive the array base
5649   // and index from the expression types.
5650   Expr *BaseExpr, *IndexExpr;
5651   QualType ResultType;
5652   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5653     BaseExpr = LHSExp;
5654     IndexExpr = RHSExp;
5655     ResultType =
5656         getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());
5657   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5658     BaseExpr = LHSExp;
5659     IndexExpr = RHSExp;
5660     ResultType = PTy->getPointeeType();
5661   } else if (const ObjCObjectPointerType *PTy =
5662                LHSTy->getAs<ObjCObjectPointerType>()) {
5663     BaseExpr = LHSExp;
5664     IndexExpr = RHSExp;
5665 
5666     // Use custom logic if this should be the pseudo-object subscript
5667     // expression.
5668     if (!LangOpts.isSubscriptPointerArithmetic())
5669       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5670                                           nullptr);
5671 
5672     ResultType = PTy->getPointeeType();
5673   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5674      // Handle the uncommon case of "123[Ptr]".
5675     BaseExpr = RHSExp;
5676     IndexExpr = LHSExp;
5677     ResultType = PTy->getPointeeType();
5678   } else if (const ObjCObjectPointerType *PTy =
5679                RHSTy->getAs<ObjCObjectPointerType>()) {
5680      // Handle the uncommon case of "123[Ptr]".
5681     BaseExpr = RHSExp;
5682     IndexExpr = LHSExp;
5683     ResultType = PTy->getPointeeType();
5684     if (!LangOpts.isSubscriptPointerArithmetic()) {
5685       Diag(LLoc, diag::err_subscript_nonfragile_interface)
5686         << ResultType << BaseExpr->getSourceRange();
5687       return ExprError();
5688     }
5689   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5690     BaseExpr = LHSExp;    // vectors: V[123]
5691     IndexExpr = RHSExp;
5692     // We apply C++ DR1213 to vector subscripting too.
5693     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5694       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5695       if (Materialized.isInvalid())
5696         return ExprError();
5697       LHSExp = Materialized.get();
5698     }
5699     VK = LHSExp->getValueKind();
5700     if (VK != VK_PRValue)
5701       OK = OK_VectorComponent;
5702 
5703     ResultType = VTy->getElementType();
5704     QualType BaseType = BaseExpr->getType();
5705     Qualifiers BaseQuals = BaseType.getQualifiers();
5706     Qualifiers MemberQuals = ResultType.getQualifiers();
5707     Qualifiers Combined = BaseQuals + MemberQuals;
5708     if (Combined != MemberQuals)
5709       ResultType = Context.getQualifiedType(ResultType, Combined);
5710   } else if (LHSTy->isBuiltinType() &&
5711              LHSTy->getAs<BuiltinType>()->isVLSTBuiltinType()) {
5712     const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5713     if (BTy->isSVEBool())
5714       return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5715                        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5716 
5717     BaseExpr = LHSExp;
5718     IndexExpr = RHSExp;
5719     if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5720       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5721       if (Materialized.isInvalid())
5722         return ExprError();
5723       LHSExp = Materialized.get();
5724     }
5725     VK = LHSExp->getValueKind();
5726     if (VK != VK_PRValue)
5727       OK = OK_VectorComponent;
5728 
5729     ResultType = BTy->getSveEltType(Context);
5730 
5731     QualType BaseType = BaseExpr->getType();
5732     Qualifiers BaseQuals = BaseType.getQualifiers();
5733     Qualifiers MemberQuals = ResultType.getQualifiers();
5734     Qualifiers Combined = BaseQuals + MemberQuals;
5735     if (Combined != MemberQuals)
5736       ResultType = Context.getQualifiedType(ResultType, Combined);
5737   } else if (LHSTy->isArrayType()) {
5738     // If we see an array that wasn't promoted by
5739     // DefaultFunctionArrayLvalueConversion, it must be an array that
5740     // wasn't promoted because of the C90 rule that doesn't
5741     // allow promoting non-lvalue arrays.  Warn, then
5742     // force the promotion here.
5743     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5744         << LHSExp->getSourceRange();
5745     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5746                                CK_ArrayToPointerDecay).get();
5747     LHSTy = LHSExp->getType();
5748 
5749     BaseExpr = LHSExp;
5750     IndexExpr = RHSExp;
5751     ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5752   } else if (RHSTy->isArrayType()) {
5753     // Same as previous, except for 123[f().a] case
5754     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5755         << RHSExp->getSourceRange();
5756     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5757                                CK_ArrayToPointerDecay).get();
5758     RHSTy = RHSExp->getType();
5759 
5760     BaseExpr = RHSExp;
5761     IndexExpr = LHSExp;
5762     ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5763   } else {
5764     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5765        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5766   }
5767   // C99 6.5.2.1p1
5768   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5769     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5770                      << IndexExpr->getSourceRange());
5771 
5772   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5773        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5774          && !IndexExpr->isTypeDependent())
5775     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5776 
5777   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5778   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5779   // type. Note that Functions are not objects, and that (in C99 parlance)
5780   // incomplete types are not object types.
5781   if (ResultType->isFunctionType()) {
5782     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5783         << ResultType << BaseExpr->getSourceRange();
5784     return ExprError();
5785   }
5786 
5787   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5788     // GNU extension: subscripting on pointer to void
5789     Diag(LLoc, diag::ext_gnu_subscript_void_type)
5790       << BaseExpr->getSourceRange();
5791 
5792     // C forbids expressions of unqualified void type from being l-values.
5793     // See IsCForbiddenLValueType.
5794     if (!ResultType.hasQualifiers())
5795       VK = VK_PRValue;
5796   } else if (!ResultType->isDependentType() &&
5797              RequireCompleteSizedType(
5798                  LLoc, ResultType,
5799                  diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5800     return ExprError();
5801 
5802   assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5803          !ResultType.isCForbiddenLValueType());
5804 
5805   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5806       FunctionScopes.size() > 1) {
5807     if (auto *TT =
5808             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5809       for (auto I = FunctionScopes.rbegin(),
5810                 E = std::prev(FunctionScopes.rend());
5811            I != E; ++I) {
5812         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5813         if (CSI == nullptr)
5814           break;
5815         DeclContext *DC = nullptr;
5816         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5817           DC = LSI->CallOperator;
5818         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5819           DC = CRSI->TheCapturedDecl;
5820         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5821           DC = BSI->TheDecl;
5822         if (DC) {
5823           if (DC->containsDecl(TT->getDecl()))
5824             break;
5825           captureVariablyModifiedType(
5826               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5827         }
5828       }
5829     }
5830   }
5831 
5832   return new (Context)
5833       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5834 }
5835 
5836 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5837                                   ParmVarDecl *Param) {
5838   if (Param->hasUnparsedDefaultArg()) {
5839     // If we've already cleared out the location for the default argument,
5840     // that means we're parsing it right now.
5841     if (!UnparsedDefaultArgLocs.count(Param)) {
5842       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5843       Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5844       Param->setInvalidDecl();
5845       return true;
5846     }
5847 
5848     Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5849         << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5850     Diag(UnparsedDefaultArgLocs[Param],
5851          diag::note_default_argument_declared_here);
5852     return true;
5853   }
5854 
5855   if (Param->hasUninstantiatedDefaultArg() &&
5856       InstantiateDefaultArgument(CallLoc, FD, Param))
5857     return true;
5858 
5859   assert(Param->hasInit() && "default argument but no initializer?");
5860 
5861   // If the default expression creates temporaries, we need to
5862   // push them to the current stack of expression temporaries so they'll
5863   // be properly destroyed.
5864   // FIXME: We should really be rebuilding the default argument with new
5865   // bound temporaries; see the comment in PR5810.
5866   // We don't need to do that with block decls, though, because
5867   // blocks in default argument expression can never capture anything.
5868   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5869     // Set the "needs cleanups" bit regardless of whether there are
5870     // any explicit objects.
5871     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5872 
5873     // Append all the objects to the cleanup list.  Right now, this
5874     // should always be a no-op, because blocks in default argument
5875     // expressions should never be able to capture anything.
5876     assert(!Init->getNumObjects() &&
5877            "default argument expression has capturing blocks?");
5878   }
5879 
5880   // We already type-checked the argument, so we know it works.
5881   // Just mark all of the declarations in this potentially-evaluated expression
5882   // as being "referenced".
5883   EnterExpressionEvaluationContext EvalContext(
5884       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5885   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5886                                    /*SkipLocalVariables=*/true);
5887   return false;
5888 }
5889 
5890 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5891                                         FunctionDecl *FD, ParmVarDecl *Param) {
5892   assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5893   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5894     return ExprError();
5895   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5896 }
5897 
5898 Sema::VariadicCallType
5899 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5900                           Expr *Fn) {
5901   if (Proto && Proto->isVariadic()) {
5902     if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5903       return VariadicConstructor;
5904     else if (Fn && Fn->getType()->isBlockPointerType())
5905       return VariadicBlock;
5906     else if (FDecl) {
5907       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5908         if (Method->isInstance())
5909           return VariadicMethod;
5910     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5911       return VariadicMethod;
5912     return VariadicFunction;
5913   }
5914   return VariadicDoesNotApply;
5915 }
5916 
5917 namespace {
5918 class FunctionCallCCC final : public FunctionCallFilterCCC {
5919 public:
5920   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5921                   unsigned NumArgs, MemberExpr *ME)
5922       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5923         FunctionName(FuncName) {}
5924 
5925   bool ValidateCandidate(const TypoCorrection &candidate) override {
5926     if (!candidate.getCorrectionSpecifier() ||
5927         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5928       return false;
5929     }
5930 
5931     return FunctionCallFilterCCC::ValidateCandidate(candidate);
5932   }
5933 
5934   std::unique_ptr<CorrectionCandidateCallback> clone() override {
5935     return std::make_unique<FunctionCallCCC>(*this);
5936   }
5937 
5938 private:
5939   const IdentifierInfo *const FunctionName;
5940 };
5941 }
5942 
5943 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5944                                                FunctionDecl *FDecl,
5945                                                ArrayRef<Expr *> Args) {
5946   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5947   DeclarationName FuncName = FDecl->getDeclName();
5948   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5949 
5950   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5951   if (TypoCorrection Corrected = S.CorrectTypo(
5952           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5953           S.getScopeForContext(S.CurContext), nullptr, CCC,
5954           Sema::CTK_ErrorRecovery)) {
5955     if (NamedDecl *ND = Corrected.getFoundDecl()) {
5956       if (Corrected.isOverloaded()) {
5957         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5958         OverloadCandidateSet::iterator Best;
5959         for (NamedDecl *CD : Corrected) {
5960           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5961             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5962                                    OCS);
5963         }
5964         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5965         case OR_Success:
5966           ND = Best->FoundDecl;
5967           Corrected.setCorrectionDecl(ND);
5968           break;
5969         default:
5970           break;
5971         }
5972       }
5973       ND = ND->getUnderlyingDecl();
5974       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5975         return Corrected;
5976     }
5977   }
5978   return TypoCorrection();
5979 }
5980 
5981 /// ConvertArgumentsForCall - Converts the arguments specified in
5982 /// Args/NumArgs to the parameter types of the function FDecl with
5983 /// function prototype Proto. Call is the call expression itself, and
5984 /// Fn is the function expression. For a C++ member function, this
5985 /// routine does not attempt to convert the object argument. Returns
5986 /// true if the call is ill-formed.
5987 bool
5988 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5989                               FunctionDecl *FDecl,
5990                               const FunctionProtoType *Proto,
5991                               ArrayRef<Expr *> Args,
5992                               SourceLocation RParenLoc,
5993                               bool IsExecConfig) {
5994   // Bail out early if calling a builtin with custom typechecking.
5995   if (FDecl)
5996     if (unsigned ID = FDecl->getBuiltinID())
5997       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5998         return false;
5999 
6000   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6001   // assignment, to the types of the corresponding parameter, ...
6002   unsigned NumParams = Proto->getNumParams();
6003   bool Invalid = false;
6004   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6005   unsigned FnKind = Fn->getType()->isBlockPointerType()
6006                        ? 1 /* block */
6007                        : (IsExecConfig ? 3 /* kernel function (exec config) */
6008                                        : 0 /* function */);
6009 
6010   // If too few arguments are available (and we don't have default
6011   // arguments for the remaining parameters), don't make the call.
6012   if (Args.size() < NumParams) {
6013     if (Args.size() < MinArgs) {
6014       TypoCorrection TC;
6015       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6016         unsigned diag_id =
6017             MinArgs == NumParams && !Proto->isVariadic()
6018                 ? diag::err_typecheck_call_too_few_args_suggest
6019                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6020         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
6021                                         << static_cast<unsigned>(Args.size())
6022                                         << TC.getCorrectionRange());
6023       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
6024         Diag(RParenLoc,
6025              MinArgs == NumParams && !Proto->isVariadic()
6026                  ? diag::err_typecheck_call_too_few_args_one
6027                  : diag::err_typecheck_call_too_few_args_at_least_one)
6028             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
6029       else
6030         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6031                             ? diag::err_typecheck_call_too_few_args
6032                             : diag::err_typecheck_call_too_few_args_at_least)
6033             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
6034             << Fn->getSourceRange();
6035 
6036       // Emit the location of the prototype.
6037       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6038         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6039 
6040       return true;
6041     }
6042     // We reserve space for the default arguments when we create
6043     // the call expression, before calling ConvertArgumentsForCall.
6044     assert((Call->getNumArgs() == NumParams) &&
6045            "We should have reserved space for the default arguments before!");
6046   }
6047 
6048   // If too many are passed and not variadic, error on the extras and drop
6049   // them.
6050   if (Args.size() > NumParams) {
6051     if (!Proto->isVariadic()) {
6052       TypoCorrection TC;
6053       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6054         unsigned diag_id =
6055             MinArgs == NumParams && !Proto->isVariadic()
6056                 ? diag::err_typecheck_call_too_many_args_suggest
6057                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6058         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
6059                                         << static_cast<unsigned>(Args.size())
6060                                         << TC.getCorrectionRange());
6061       } else if (NumParams == 1 && FDecl &&
6062                  FDecl->getParamDecl(0)->getDeclName())
6063         Diag(Args[NumParams]->getBeginLoc(),
6064              MinArgs == NumParams
6065                  ? diag::err_typecheck_call_too_many_args_one
6066                  : diag::err_typecheck_call_too_many_args_at_most_one)
6067             << FnKind << FDecl->getParamDecl(0)
6068             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
6069             << SourceRange(Args[NumParams]->getBeginLoc(),
6070                            Args.back()->getEndLoc());
6071       else
6072         Diag(Args[NumParams]->getBeginLoc(),
6073              MinArgs == NumParams
6074                  ? diag::err_typecheck_call_too_many_args
6075                  : diag::err_typecheck_call_too_many_args_at_most)
6076             << FnKind << NumParams << static_cast<unsigned>(Args.size())
6077             << Fn->getSourceRange()
6078             << SourceRange(Args[NumParams]->getBeginLoc(),
6079                            Args.back()->getEndLoc());
6080 
6081       // Emit the location of the prototype.
6082       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6083         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6084 
6085       // This deletes the extra arguments.
6086       Call->shrinkNumArgs(NumParams);
6087       return true;
6088     }
6089   }
6090   SmallVector<Expr *, 8> AllArgs;
6091   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6092 
6093   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6094                                    AllArgs, CallType);
6095   if (Invalid)
6096     return true;
6097   unsigned TotalNumArgs = AllArgs.size();
6098   for (unsigned i = 0; i < TotalNumArgs; ++i)
6099     Call->setArg(i, AllArgs[i]);
6100 
6101   Call->computeDependence();
6102   return false;
6103 }
6104 
6105 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
6106                                   const FunctionProtoType *Proto,
6107                                   unsigned FirstParam, ArrayRef<Expr *> Args,
6108                                   SmallVectorImpl<Expr *> &AllArgs,
6109                                   VariadicCallType CallType, bool AllowExplicit,
6110                                   bool IsListInitialization) {
6111   unsigned NumParams = Proto->getNumParams();
6112   bool Invalid = false;
6113   size_t ArgIx = 0;
6114   // Continue to check argument types (even if we have too few/many args).
6115   for (unsigned i = FirstParam; i < NumParams; i++) {
6116     QualType ProtoArgType = Proto->getParamType(i);
6117 
6118     Expr *Arg;
6119     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6120     if (ArgIx < Args.size()) {
6121       Arg = Args[ArgIx++];
6122 
6123       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6124                               diag::err_call_incomplete_argument, Arg))
6125         return true;
6126 
6127       // Strip the unbridged-cast placeholder expression off, if applicable.
6128       bool CFAudited = false;
6129       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6130           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6131           (!Param || !Param->hasAttr<CFConsumedAttr>()))
6132         Arg = stripARCUnbridgedCast(Arg);
6133       else if (getLangOpts().ObjCAutoRefCount &&
6134                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6135                (!Param || !Param->hasAttr<CFConsumedAttr>()))
6136         CFAudited = true;
6137 
6138       if (Proto->getExtParameterInfo(i).isNoEscape() &&
6139           ProtoArgType->isBlockPointerType())
6140         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6141           BE->getBlockDecl()->setDoesNotEscape();
6142 
6143       InitializedEntity Entity =
6144           Param ? InitializedEntity::InitializeParameter(Context, Param,
6145                                                          ProtoArgType)
6146                 : InitializedEntity::InitializeParameter(
6147                       Context, ProtoArgType, Proto->isParamConsumed(i));
6148 
6149       // Remember that parameter belongs to a CF audited API.
6150       if (CFAudited)
6151         Entity.setParameterCFAudited();
6152 
6153       ExprResult ArgE = PerformCopyInitialization(
6154           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6155       if (ArgE.isInvalid())
6156         return true;
6157 
6158       Arg = ArgE.getAs<Expr>();
6159     } else {
6160       assert(Param && "can't use default arguments without a known callee");
6161 
6162       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6163       if (ArgExpr.isInvalid())
6164         return true;
6165 
6166       Arg = ArgExpr.getAs<Expr>();
6167     }
6168 
6169     // Check for array bounds violations for each argument to the call. This
6170     // check only triggers warnings when the argument isn't a more complex Expr
6171     // with its own checking, such as a BinaryOperator.
6172     CheckArrayAccess(Arg);
6173 
6174     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6175     CheckStaticArrayArgument(CallLoc, Param, Arg);
6176 
6177     AllArgs.push_back(Arg);
6178   }
6179 
6180   // If this is a variadic call, handle args passed through "...".
6181   if (CallType != VariadicDoesNotApply) {
6182     // Assume that extern "C" functions with variadic arguments that
6183     // return __unknown_anytype aren't *really* variadic.
6184     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6185         FDecl->isExternC()) {
6186       for (Expr *A : Args.slice(ArgIx)) {
6187         QualType paramType; // ignored
6188         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6189         Invalid |= arg.isInvalid();
6190         AllArgs.push_back(arg.get());
6191       }
6192 
6193     // Otherwise do argument promotion, (C99 6.5.2.2p7).
6194     } else {
6195       for (Expr *A : Args.slice(ArgIx)) {
6196         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6197         Invalid |= Arg.isInvalid();
6198         AllArgs.push_back(Arg.get());
6199       }
6200     }
6201 
6202     // Check for array bounds violations.
6203     for (Expr *A : Args.slice(ArgIx))
6204       CheckArrayAccess(A);
6205   }
6206   return Invalid;
6207 }
6208 
6209 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6210   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6211   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6212     TL = DTL.getOriginalLoc();
6213   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6214     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6215       << ATL.getLocalSourceRange();
6216 }
6217 
6218 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6219 /// array parameter, check that it is non-null, and that if it is formed by
6220 /// array-to-pointer decay, the underlying array is sufficiently large.
6221 ///
6222 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6223 /// array type derivation, then for each call to the function, the value of the
6224 /// corresponding actual argument shall provide access to the first element of
6225 /// an array with at least as many elements as specified by the size expression.
6226 void
6227 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6228                                ParmVarDecl *Param,
6229                                const Expr *ArgExpr) {
6230   // Static array parameters are not supported in C++.
6231   if (!Param || getLangOpts().CPlusPlus)
6232     return;
6233 
6234   QualType OrigTy = Param->getOriginalType();
6235 
6236   const ArrayType *AT = Context.getAsArrayType(OrigTy);
6237   if (!AT || AT->getSizeModifier() != ArrayType::Static)
6238     return;
6239 
6240   if (ArgExpr->isNullPointerConstant(Context,
6241                                      Expr::NPC_NeverValueDependent)) {
6242     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6243     DiagnoseCalleeStaticArrayParam(*this, Param);
6244     return;
6245   }
6246 
6247   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6248   if (!CAT)
6249     return;
6250 
6251   const ConstantArrayType *ArgCAT =
6252     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6253   if (!ArgCAT)
6254     return;
6255 
6256   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6257                                              ArgCAT->getElementType())) {
6258     if (ArgCAT->getSize().ult(CAT->getSize())) {
6259       Diag(CallLoc, diag::warn_static_array_too_small)
6260           << ArgExpr->getSourceRange()
6261           << (unsigned)ArgCAT->getSize().getZExtValue()
6262           << (unsigned)CAT->getSize().getZExtValue() << 0;
6263       DiagnoseCalleeStaticArrayParam(*this, Param);
6264     }
6265     return;
6266   }
6267 
6268   Optional<CharUnits> ArgSize =
6269       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6270   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6271   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6272     Diag(CallLoc, diag::warn_static_array_too_small)
6273         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6274         << (unsigned)ParmSize->getQuantity() << 1;
6275     DiagnoseCalleeStaticArrayParam(*this, Param);
6276   }
6277 }
6278 
6279 /// Given a function expression of unknown-any type, try to rebuild it
6280 /// to have a function type.
6281 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6282 
6283 /// Is the given type a placeholder that we need to lower out
6284 /// immediately during argument processing?
6285 static bool isPlaceholderToRemoveAsArg(QualType type) {
6286   // Placeholders are never sugared.
6287   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6288   if (!placeholder) return false;
6289 
6290   switch (placeholder->getKind()) {
6291   // Ignore all the non-placeholder types.
6292 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6293   case BuiltinType::Id:
6294 #include "clang/Basic/OpenCLImageTypes.def"
6295 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6296   case BuiltinType::Id:
6297 #include "clang/Basic/OpenCLExtensionTypes.def"
6298   // In practice we'll never use this, since all SVE types are sugared
6299   // via TypedefTypes rather than exposed directly as BuiltinTypes.
6300 #define SVE_TYPE(Name, Id, SingletonId) \
6301   case BuiltinType::Id:
6302 #include "clang/Basic/AArch64SVEACLETypes.def"
6303 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6304   case BuiltinType::Id:
6305 #include "clang/Basic/PPCTypes.def"
6306 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6307 #include "clang/Basic/RISCVVTypes.def"
6308 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6309 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6310 #include "clang/AST/BuiltinTypes.def"
6311     return false;
6312 
6313   // We cannot lower out overload sets; they might validly be resolved
6314   // by the call machinery.
6315   case BuiltinType::Overload:
6316     return false;
6317 
6318   // Unbridged casts in ARC can be handled in some call positions and
6319   // should be left in place.
6320   case BuiltinType::ARCUnbridgedCast:
6321     return false;
6322 
6323   // Pseudo-objects should be converted as soon as possible.
6324   case BuiltinType::PseudoObject:
6325     return true;
6326 
6327   // The debugger mode could theoretically but currently does not try
6328   // to resolve unknown-typed arguments based on known parameter types.
6329   case BuiltinType::UnknownAny:
6330     return true;
6331 
6332   // These are always invalid as call arguments and should be reported.
6333   case BuiltinType::BoundMember:
6334   case BuiltinType::BuiltinFn:
6335   case BuiltinType::IncompleteMatrixIdx:
6336   case BuiltinType::OMPArraySection:
6337   case BuiltinType::OMPArrayShaping:
6338   case BuiltinType::OMPIterator:
6339     return true;
6340 
6341   }
6342   llvm_unreachable("bad builtin type kind");
6343 }
6344 
6345 /// Check an argument list for placeholders that we won't try to
6346 /// handle later.
6347 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6348   // Apply this processing to all the arguments at once instead of
6349   // dying at the first failure.
6350   bool hasInvalid = false;
6351   for (size_t i = 0, e = args.size(); i != e; i++) {
6352     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6353       ExprResult result = S.CheckPlaceholderExpr(args[i]);
6354       if (result.isInvalid()) hasInvalid = true;
6355       else args[i] = result.get();
6356     }
6357   }
6358   return hasInvalid;
6359 }
6360 
6361 /// If a builtin function has a pointer argument with no explicit address
6362 /// space, then it should be able to accept a pointer to any address
6363 /// space as input.  In order to do this, we need to replace the
6364 /// standard builtin declaration with one that uses the same address space
6365 /// as the call.
6366 ///
6367 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6368 ///                  it does not contain any pointer arguments without
6369 ///                  an address space qualifer.  Otherwise the rewritten
6370 ///                  FunctionDecl is returned.
6371 /// TODO: Handle pointer return types.
6372 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6373                                                 FunctionDecl *FDecl,
6374                                                 MultiExprArg ArgExprs) {
6375 
6376   QualType DeclType = FDecl->getType();
6377   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6378 
6379   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6380       ArgExprs.size() < FT->getNumParams())
6381     return nullptr;
6382 
6383   bool NeedsNewDecl = false;
6384   unsigned i = 0;
6385   SmallVector<QualType, 8> OverloadParams;
6386 
6387   for (QualType ParamType : FT->param_types()) {
6388 
6389     // Convert array arguments to pointer to simplify type lookup.
6390     ExprResult ArgRes =
6391         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6392     if (ArgRes.isInvalid())
6393       return nullptr;
6394     Expr *Arg = ArgRes.get();
6395     QualType ArgType = Arg->getType();
6396     if (!ParamType->isPointerType() ||
6397         ParamType.hasAddressSpace() ||
6398         !ArgType->isPointerType() ||
6399         !ArgType->getPointeeType().hasAddressSpace()) {
6400       OverloadParams.push_back(ParamType);
6401       continue;
6402     }
6403 
6404     QualType PointeeType = ParamType->getPointeeType();
6405     if (PointeeType.hasAddressSpace())
6406       continue;
6407 
6408     NeedsNewDecl = true;
6409     LangAS AS = ArgType->getPointeeType().getAddressSpace();
6410 
6411     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6412     OverloadParams.push_back(Context.getPointerType(PointeeType));
6413   }
6414 
6415   if (!NeedsNewDecl)
6416     return nullptr;
6417 
6418   FunctionProtoType::ExtProtoInfo EPI;
6419   EPI.Variadic = FT->isVariadic();
6420   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6421                                                 OverloadParams, EPI);
6422   DeclContext *Parent = FDecl->getParent();
6423   FunctionDecl *OverloadDecl = FunctionDecl::Create(
6424       Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6425       FDecl->getIdentifier(), OverloadTy,
6426       /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6427       false,
6428       /*hasPrototype=*/true);
6429   SmallVector<ParmVarDecl*, 16> Params;
6430   FT = cast<FunctionProtoType>(OverloadTy);
6431   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6432     QualType ParamType = FT->getParamType(i);
6433     ParmVarDecl *Parm =
6434         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6435                                 SourceLocation(), nullptr, ParamType,
6436                                 /*TInfo=*/nullptr, SC_None, nullptr);
6437     Parm->setScopeInfo(0, i);
6438     Params.push_back(Parm);
6439   }
6440   OverloadDecl->setParams(Params);
6441   Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6442   return OverloadDecl;
6443 }
6444 
6445 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6446                                     FunctionDecl *Callee,
6447                                     MultiExprArg ArgExprs) {
6448   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6449   // similar attributes) really don't like it when functions are called with an
6450   // invalid number of args.
6451   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6452                          /*PartialOverloading=*/false) &&
6453       !Callee->isVariadic())
6454     return;
6455   if (Callee->getMinRequiredArguments() > ArgExprs.size())
6456     return;
6457 
6458   if (const EnableIfAttr *Attr =
6459           S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6460     S.Diag(Fn->getBeginLoc(),
6461            isa<CXXMethodDecl>(Callee)
6462                ? diag::err_ovl_no_viable_member_function_in_call
6463                : diag::err_ovl_no_viable_function_in_call)
6464         << Callee << Callee->getSourceRange();
6465     S.Diag(Callee->getLocation(),
6466            diag::note_ovl_candidate_disabled_by_function_cond_attr)
6467         << Attr->getCond()->getSourceRange() << Attr->getMessage();
6468     return;
6469   }
6470 }
6471 
6472 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6473     const UnresolvedMemberExpr *const UME, Sema &S) {
6474 
6475   const auto GetFunctionLevelDCIfCXXClass =
6476       [](Sema &S) -> const CXXRecordDecl * {
6477     const DeclContext *const DC = S.getFunctionLevelDeclContext();
6478     if (!DC || !DC->getParent())
6479       return nullptr;
6480 
6481     // If the call to some member function was made from within a member
6482     // function body 'M' return return 'M's parent.
6483     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6484       return MD->getParent()->getCanonicalDecl();
6485     // else the call was made from within a default member initializer of a
6486     // class, so return the class.
6487     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6488       return RD->getCanonicalDecl();
6489     return nullptr;
6490   };
6491   // If our DeclContext is neither a member function nor a class (in the
6492   // case of a lambda in a default member initializer), we can't have an
6493   // enclosing 'this'.
6494 
6495   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6496   if (!CurParentClass)
6497     return false;
6498 
6499   // The naming class for implicit member functions call is the class in which
6500   // name lookup starts.
6501   const CXXRecordDecl *const NamingClass =
6502       UME->getNamingClass()->getCanonicalDecl();
6503   assert(NamingClass && "Must have naming class even for implicit access");
6504 
6505   // If the unresolved member functions were found in a 'naming class' that is
6506   // related (either the same or derived from) to the class that contains the
6507   // member function that itself contained the implicit member access.
6508 
6509   return CurParentClass == NamingClass ||
6510          CurParentClass->isDerivedFrom(NamingClass);
6511 }
6512 
6513 static void
6514 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6515     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6516 
6517   if (!UME)
6518     return;
6519 
6520   LambdaScopeInfo *const CurLSI = S.getCurLambda();
6521   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6522   // already been captured, or if this is an implicit member function call (if
6523   // it isn't, an attempt to capture 'this' should already have been made).
6524   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6525       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6526     return;
6527 
6528   // Check if the naming class in which the unresolved members were found is
6529   // related (same as or is a base of) to the enclosing class.
6530 
6531   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6532     return;
6533 
6534 
6535   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6536   // If the enclosing function is not dependent, then this lambda is
6537   // capture ready, so if we can capture this, do so.
6538   if (!EnclosingFunctionCtx->isDependentContext()) {
6539     // If the current lambda and all enclosing lambdas can capture 'this' -
6540     // then go ahead and capture 'this' (since our unresolved overload set
6541     // contains at least one non-static member function).
6542     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6543       S.CheckCXXThisCapture(CallLoc);
6544   } else if (S.CurContext->isDependentContext()) {
6545     // ... since this is an implicit member reference, that might potentially
6546     // involve a 'this' capture, mark 'this' for potential capture in
6547     // enclosing lambdas.
6548     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6549       CurLSI->addPotentialThisCapture(CallLoc);
6550   }
6551 }
6552 
6553 // Once a call is fully resolved, warn for unqualified calls to specific
6554 // C++ standard functions, like move and forward.
6555 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, CallExpr *Call) {
6556   // We are only checking unary move and forward so exit early here.
6557   if (Call->getNumArgs() != 1)
6558     return;
6559 
6560   Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6561   if (!E || isa<UnresolvedLookupExpr>(E))
6562     return;
6563   DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E);
6564   if (!DRE || !DRE->getLocation().isValid())
6565     return;
6566 
6567   if (DRE->getQualifier())
6568     return;
6569 
6570   NamedDecl *D = dyn_cast_or_null<NamedDecl>(Call->getCalleeDecl());
6571   if (!D || !D->isInStdNamespace())
6572     return;
6573 
6574   // Only warn for some functions deemed more frequent or problematic.
6575   static constexpr llvm::StringRef SpecialFunctions[] = {"move", "forward"};
6576   auto it = llvm::find(SpecialFunctions, D->getName());
6577   if (it == std::end(SpecialFunctions))
6578     return;
6579 
6580   S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6581       << D->getQualifiedNameAsString()
6582       << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6583 }
6584 
6585 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6586                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6587                                Expr *ExecConfig) {
6588   ExprResult Call =
6589       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6590                     /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6591   if (Call.isInvalid())
6592     return Call;
6593 
6594   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6595   // language modes.
6596   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6597     if (ULE->hasExplicitTemplateArgs() &&
6598         ULE->decls_begin() == ULE->decls_end()) {
6599       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6600                                  ? diag::warn_cxx17_compat_adl_only_template_id
6601                                  : diag::ext_adl_only_template_id)
6602           << ULE->getName();
6603     }
6604   }
6605 
6606   if (LangOpts.OpenMP)
6607     Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6608                            ExecConfig);
6609   if (LangOpts.CPlusPlus) {
6610     CallExpr *CE = dyn_cast<CallExpr>(Call.get());
6611     if (CE)
6612       DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);
6613   }
6614   return Call;
6615 }
6616 
6617 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6618 /// This provides the location of the left/right parens and a list of comma
6619 /// locations.
6620 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6621                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
6622                                Expr *ExecConfig, bool IsExecConfig,
6623                                bool AllowRecovery) {
6624   // Since this might be a postfix expression, get rid of ParenListExprs.
6625   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6626   if (Result.isInvalid()) return ExprError();
6627   Fn = Result.get();
6628 
6629   if (checkArgsForPlaceholders(*this, ArgExprs))
6630     return ExprError();
6631 
6632   if (getLangOpts().CPlusPlus) {
6633     // If this is a pseudo-destructor expression, build the call immediately.
6634     if (isa<CXXPseudoDestructorExpr>(Fn)) {
6635       if (!ArgExprs.empty()) {
6636         // Pseudo-destructor calls should not have any arguments.
6637         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6638             << FixItHint::CreateRemoval(
6639                    SourceRange(ArgExprs.front()->getBeginLoc(),
6640                                ArgExprs.back()->getEndLoc()));
6641       }
6642 
6643       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6644                               VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6645     }
6646     if (Fn->getType() == Context.PseudoObjectTy) {
6647       ExprResult result = CheckPlaceholderExpr(Fn);
6648       if (result.isInvalid()) return ExprError();
6649       Fn = result.get();
6650     }
6651 
6652     // Determine whether this is a dependent call inside a C++ template,
6653     // in which case we won't do any semantic analysis now.
6654     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6655       if (ExecConfig) {
6656         return CUDAKernelCallExpr::Create(Context, Fn,
6657                                           cast<CallExpr>(ExecConfig), ArgExprs,
6658                                           Context.DependentTy, VK_PRValue,
6659                                           RParenLoc, CurFPFeatureOverrides());
6660       } else {
6661 
6662         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6663             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6664             Fn->getBeginLoc());
6665 
6666         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6667                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6668       }
6669     }
6670 
6671     // Determine whether this is a call to an object (C++ [over.call.object]).
6672     if (Fn->getType()->isRecordType())
6673       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6674                                           RParenLoc);
6675 
6676     if (Fn->getType() == Context.UnknownAnyTy) {
6677       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6678       if (result.isInvalid()) return ExprError();
6679       Fn = result.get();
6680     }
6681 
6682     if (Fn->getType() == Context.BoundMemberTy) {
6683       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6684                                        RParenLoc, ExecConfig, IsExecConfig,
6685                                        AllowRecovery);
6686     }
6687   }
6688 
6689   // Check for overloaded calls.  This can happen even in C due to extensions.
6690   if (Fn->getType() == Context.OverloadTy) {
6691     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6692 
6693     // We aren't supposed to apply this logic if there's an '&' involved.
6694     if (!find.HasFormOfMemberPointer) {
6695       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6696         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6697                                 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6698       OverloadExpr *ovl = find.Expression;
6699       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6700         return BuildOverloadedCallExpr(
6701             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6702             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6703       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6704                                        RParenLoc, ExecConfig, IsExecConfig,
6705                                        AllowRecovery);
6706     }
6707   }
6708 
6709   // If we're directly calling a function, get the appropriate declaration.
6710   if (Fn->getType() == Context.UnknownAnyTy) {
6711     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6712     if (result.isInvalid()) return ExprError();
6713     Fn = result.get();
6714   }
6715 
6716   Expr *NakedFn = Fn->IgnoreParens();
6717 
6718   bool CallingNDeclIndirectly = false;
6719   NamedDecl *NDecl = nullptr;
6720   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6721     if (UnOp->getOpcode() == UO_AddrOf) {
6722       CallingNDeclIndirectly = true;
6723       NakedFn = UnOp->getSubExpr()->IgnoreParens();
6724     }
6725   }
6726 
6727   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6728     NDecl = DRE->getDecl();
6729 
6730     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6731     if (FDecl && FDecl->getBuiltinID()) {
6732       // Rewrite the function decl for this builtin by replacing parameters
6733       // with no explicit address space with the address space of the arguments
6734       // in ArgExprs.
6735       if ((FDecl =
6736                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6737         NDecl = FDecl;
6738         Fn = DeclRefExpr::Create(
6739             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6740             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6741             nullptr, DRE->isNonOdrUse());
6742       }
6743     }
6744   } else if (isa<MemberExpr>(NakedFn))
6745     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6746 
6747   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6748     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6749                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
6750       return ExprError();
6751 
6752     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6753 
6754     // If this expression is a call to a builtin function in HIP device
6755     // compilation, allow a pointer-type argument to default address space to be
6756     // passed as a pointer-type parameter to a non-default address space.
6757     // If Arg is declared in the default address space and Param is declared
6758     // in a non-default address space, perform an implicit address space cast to
6759     // the parameter type.
6760     if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6761         FD->getBuiltinID()) {
6762       for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6763         ParmVarDecl *Param = FD->getParamDecl(Idx);
6764         if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6765             !ArgExprs[Idx]->getType()->isPointerType())
6766           continue;
6767 
6768         auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6769         auto ArgTy = ArgExprs[Idx]->getType();
6770         auto ArgPtTy = ArgTy->getPointeeType();
6771         auto ArgAS = ArgPtTy.getAddressSpace();
6772 
6773         // Add address space cast if target address spaces are different
6774         bool NeedImplicitASC =
6775           ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.
6776           ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS
6777                                               // or from specific AS which has target AS matching that of Param.
6778           getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));
6779         if (!NeedImplicitASC)
6780           continue;
6781 
6782         // First, ensure that the Arg is an RValue.
6783         if (ArgExprs[Idx]->isGLValue()) {
6784           ArgExprs[Idx] = ImplicitCastExpr::Create(
6785               Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6786               nullptr, VK_PRValue, FPOptionsOverride());
6787         }
6788 
6789         // Construct a new arg type with address space of Param
6790         Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6791         ArgPtQuals.setAddressSpace(ParamAS);
6792         auto NewArgPtTy =
6793             Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6794         auto NewArgTy =
6795             Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6796                                      ArgTy.getQualifiers());
6797 
6798         // Finally perform an implicit address space cast
6799         ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6800                                           CK_AddressSpaceConversion)
6801                             .get();
6802       }
6803     }
6804   }
6805 
6806   if (Context.isDependenceAllowed() &&
6807       (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6808     assert(!getLangOpts().CPlusPlus);
6809     assert((Fn->containsErrors() ||
6810             llvm::any_of(ArgExprs,
6811                          [](clang::Expr *E) { return E->containsErrors(); })) &&
6812            "should only occur in error-recovery path.");
6813     QualType ReturnType =
6814         llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6815             ? cast<FunctionDecl>(NDecl)->getCallResultType()
6816             : Context.DependentTy;
6817     return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6818                             Expr::getValueKindForType(ReturnType), RParenLoc,
6819                             CurFPFeatureOverrides());
6820   }
6821   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6822                                ExecConfig, IsExecConfig);
6823 }
6824 
6825 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6826 //  with the specified CallArgs
6827 Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6828                                  MultiExprArg CallArgs) {
6829   StringRef Name = Context.BuiltinInfo.getName(Id);
6830   LookupResult R(*this, &Context.Idents.get(Name), Loc,
6831                  Sema::LookupOrdinaryName);
6832   LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6833 
6834   auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6835   assert(BuiltInDecl && "failed to find builtin declaration");
6836 
6837   ExprResult DeclRef =
6838       BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6839   assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6840 
6841   ExprResult Call =
6842       BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6843 
6844   assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6845   return Call.get();
6846 }
6847 
6848 /// Parse a __builtin_astype expression.
6849 ///
6850 /// __builtin_astype( value, dst type )
6851 ///
6852 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6853                                  SourceLocation BuiltinLoc,
6854                                  SourceLocation RParenLoc) {
6855   QualType DstTy = GetTypeFromParser(ParsedDestTy);
6856   return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6857 }
6858 
6859 /// Create a new AsTypeExpr node (bitcast) from the arguments.
6860 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6861                                  SourceLocation BuiltinLoc,
6862                                  SourceLocation RParenLoc) {
6863   ExprValueKind VK = VK_PRValue;
6864   ExprObjectKind OK = OK_Ordinary;
6865   QualType SrcTy = E->getType();
6866   if (!SrcTy->isDependentType() &&
6867       Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6868     return ExprError(
6869         Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6870         << DestTy << SrcTy << E->getSourceRange());
6871   return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6872 }
6873 
6874 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6875 /// provided arguments.
6876 ///
6877 /// __builtin_convertvector( value, dst type )
6878 ///
6879 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6880                                         SourceLocation BuiltinLoc,
6881                                         SourceLocation RParenLoc) {
6882   TypeSourceInfo *TInfo;
6883   GetTypeFromParser(ParsedDestTy, &TInfo);
6884   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6885 }
6886 
6887 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6888 /// i.e. an expression not of \p OverloadTy.  The expression should
6889 /// unary-convert to an expression of function-pointer or
6890 /// block-pointer type.
6891 ///
6892 /// \param NDecl the declaration being called, if available
6893 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6894                                        SourceLocation LParenLoc,
6895                                        ArrayRef<Expr *> Args,
6896                                        SourceLocation RParenLoc, Expr *Config,
6897                                        bool IsExecConfig, ADLCallKind UsesADL) {
6898   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6899   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6900 
6901   // Functions with 'interrupt' attribute cannot be called directly.
6902   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6903     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6904     return ExprError();
6905   }
6906 
6907   // Interrupt handlers don't save off the VFP regs automatically on ARM,
6908   // so there's some risk when calling out to non-interrupt handler functions
6909   // that the callee might not preserve them. This is easy to diagnose here,
6910   // but can be very challenging to debug.
6911   // Likewise, X86 interrupt handlers may only call routines with attribute
6912   // no_caller_saved_registers since there is no efficient way to
6913   // save and restore the non-GPR state.
6914   if (auto *Caller = getCurFunctionDecl()) {
6915     if (Caller->hasAttr<ARMInterruptAttr>()) {
6916       bool VFP = Context.getTargetInfo().hasFeature("vfp");
6917       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6918         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6919         if (FDecl)
6920           Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6921       }
6922     }
6923     if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6924         ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6925       Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6926       if (FDecl)
6927         Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6928     }
6929   }
6930 
6931   // Promote the function operand.
6932   // We special-case function promotion here because we only allow promoting
6933   // builtin functions to function pointers in the callee of a call.
6934   ExprResult Result;
6935   QualType ResultTy;
6936   if (BuiltinID &&
6937       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6938     // Extract the return type from the (builtin) function pointer type.
6939     // FIXME Several builtins still have setType in
6940     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6941     // Builtins.def to ensure they are correct before removing setType calls.
6942     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6943     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6944     ResultTy = FDecl->getCallResultType();
6945   } else {
6946     Result = CallExprUnaryConversions(Fn);
6947     ResultTy = Context.BoolTy;
6948   }
6949   if (Result.isInvalid())
6950     return ExprError();
6951   Fn = Result.get();
6952 
6953   // Check for a valid function type, but only if it is not a builtin which
6954   // requires custom type checking. These will be handled by
6955   // CheckBuiltinFunctionCall below just after creation of the call expression.
6956   const FunctionType *FuncT = nullptr;
6957   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6958   retry:
6959     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6960       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6961       // have type pointer to function".
6962       FuncT = PT->getPointeeType()->getAs<FunctionType>();
6963       if (!FuncT)
6964         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6965                          << Fn->getType() << Fn->getSourceRange());
6966     } else if (const BlockPointerType *BPT =
6967                    Fn->getType()->getAs<BlockPointerType>()) {
6968       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6969     } else {
6970       // Handle calls to expressions of unknown-any type.
6971       if (Fn->getType() == Context.UnknownAnyTy) {
6972         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6973         if (rewrite.isInvalid())
6974           return ExprError();
6975         Fn = rewrite.get();
6976         goto retry;
6977       }
6978 
6979       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6980                        << Fn->getType() << Fn->getSourceRange());
6981     }
6982   }
6983 
6984   // Get the number of parameters in the function prototype, if any.
6985   // We will allocate space for max(Args.size(), NumParams) arguments
6986   // in the call expression.
6987   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6988   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6989 
6990   CallExpr *TheCall;
6991   if (Config) {
6992     assert(UsesADL == ADLCallKind::NotADL &&
6993            "CUDAKernelCallExpr should not use ADL");
6994     TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6995                                          Args, ResultTy, VK_PRValue, RParenLoc,
6996                                          CurFPFeatureOverrides(), NumParams);
6997   } else {
6998     TheCall =
6999         CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7000                          CurFPFeatureOverrides(), NumParams, UsesADL);
7001   }
7002 
7003   if (!Context.isDependenceAllowed()) {
7004     // Forget about the nulled arguments since typo correction
7005     // do not handle them well.
7006     TheCall->shrinkNumArgs(Args.size());
7007     // C cannot always handle TypoExpr nodes in builtin calls and direct
7008     // function calls as their argument checking don't necessarily handle
7009     // dependent types properly, so make sure any TypoExprs have been
7010     // dealt with.
7011     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7012     if (!Result.isUsable()) return ExprError();
7013     CallExpr *TheOldCall = TheCall;
7014     TheCall = dyn_cast<CallExpr>(Result.get());
7015     bool CorrectedTypos = TheCall != TheOldCall;
7016     if (!TheCall) return Result;
7017     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7018 
7019     // A new call expression node was created if some typos were corrected.
7020     // However it may not have been constructed with enough storage. In this
7021     // case, rebuild the node with enough storage. The waste of space is
7022     // immaterial since this only happens when some typos were corrected.
7023     if (CorrectedTypos && Args.size() < NumParams) {
7024       if (Config)
7025         TheCall = CUDAKernelCallExpr::Create(
7026             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7027             RParenLoc, CurFPFeatureOverrides(), NumParams);
7028       else
7029         TheCall =
7030             CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7031                              CurFPFeatureOverrides(), NumParams, UsesADL);
7032     }
7033     // We can now handle the nulled arguments for the default arguments.
7034     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7035   }
7036 
7037   // Bail out early if calling a builtin with custom type checking.
7038   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7039     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7040 
7041   if (getLangOpts().CUDA) {
7042     if (Config) {
7043       // CUDA: Kernel calls must be to global functions
7044       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7045         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7046             << FDecl << Fn->getSourceRange());
7047 
7048       // CUDA: Kernel function must have 'void' return type
7049       if (!FuncT->getReturnType()->isVoidType() &&
7050           !FuncT->getReturnType()->getAs<AutoType>() &&
7051           !FuncT->getReturnType()->isInstantiationDependentType())
7052         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7053             << Fn->getType() << Fn->getSourceRange());
7054     } else {
7055       // CUDA: Calls to global functions must be configured
7056       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7057         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7058             << FDecl << Fn->getSourceRange());
7059     }
7060   }
7061 
7062   // Check for a valid return type
7063   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7064                           FDecl))
7065     return ExprError();
7066 
7067   // We know the result type of the call, set it.
7068   TheCall->setType(FuncT->getCallResultType(Context));
7069   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
7070 
7071   if (Proto) {
7072     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7073                                 IsExecConfig))
7074       return ExprError();
7075   } else {
7076     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7077 
7078     if (FDecl) {
7079       // Check if we have too few/too many template arguments, based
7080       // on our knowledge of the function definition.
7081       const FunctionDecl *Def = nullptr;
7082       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7083         Proto = Def->getType()->getAs<FunctionProtoType>();
7084        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7085           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7086           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7087       }
7088 
7089       // If the function we're calling isn't a function prototype, but we have
7090       // a function prototype from a prior declaratiom, use that prototype.
7091       if (!FDecl->hasPrototype())
7092         Proto = FDecl->getType()->getAs<FunctionProtoType>();
7093     }
7094 
7095     // If we still haven't found a prototype to use but there are arguments to
7096     // the call, diagnose this as calling a function without a prototype.
7097     // However, if we found a function declaration, check to see if
7098     // -Wdeprecated-non-prototype was disabled where the function was declared.
7099     // If so, we will silence the diagnostic here on the assumption that this
7100     // interface is intentional and the user knows what they're doing. We will
7101     // also silence the diagnostic if there is a function declaration but it
7102     // was implicitly defined (the user already gets diagnostics about the
7103     // creation of the implicit function declaration, so the additional warning
7104     // is not helpful).
7105     if (!Proto && !Args.empty() &&
7106         (!FDecl || (!FDecl->isImplicit() &&
7107                     !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7108                                      FDecl->getLocation()))))
7109       Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7110           << (FDecl != nullptr) << FDecl;
7111 
7112     // Promote the arguments (C99 6.5.2.2p6).
7113     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7114       Expr *Arg = Args[i];
7115 
7116       if (Proto && i < Proto->getNumParams()) {
7117         InitializedEntity Entity = InitializedEntity::InitializeParameter(
7118             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7119         ExprResult ArgE =
7120             PerformCopyInitialization(Entity, SourceLocation(), Arg);
7121         if (ArgE.isInvalid())
7122           return true;
7123 
7124         Arg = ArgE.getAs<Expr>();
7125 
7126       } else {
7127         ExprResult ArgE = DefaultArgumentPromotion(Arg);
7128 
7129         if (ArgE.isInvalid())
7130           return true;
7131 
7132         Arg = ArgE.getAs<Expr>();
7133       }
7134 
7135       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7136                               diag::err_call_incomplete_argument, Arg))
7137         return ExprError();
7138 
7139       TheCall->setArg(i, Arg);
7140     }
7141     TheCall->computeDependence();
7142   }
7143 
7144   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7145     if (!Method->isStatic())
7146       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7147         << Fn->getSourceRange());
7148 
7149   // Check for sentinels
7150   if (NDecl)
7151     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7152 
7153   // Warn for unions passing across security boundary (CMSE).
7154   if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7155     for (unsigned i = 0, e = Args.size(); i != e; i++) {
7156       if (const auto *RT =
7157               dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7158         if (RT->getDecl()->isOrContainsUnion())
7159           Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7160               << 0 << i;
7161       }
7162     }
7163   }
7164 
7165   // Do special checking on direct calls to functions.
7166   if (FDecl) {
7167     if (CheckFunctionCall(FDecl, TheCall, Proto))
7168       return ExprError();
7169 
7170     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7171 
7172     if (BuiltinID)
7173       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7174   } else if (NDecl) {
7175     if (CheckPointerCall(NDecl, TheCall, Proto))
7176       return ExprError();
7177   } else {
7178     if (CheckOtherCall(TheCall, Proto))
7179       return ExprError();
7180   }
7181 
7182   return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7183 }
7184 
7185 ExprResult
7186 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
7187                            SourceLocation RParenLoc, Expr *InitExpr) {
7188   assert(Ty && "ActOnCompoundLiteral(): missing type");
7189   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7190 
7191   TypeSourceInfo *TInfo;
7192   QualType literalType = GetTypeFromParser(Ty, &TInfo);
7193   if (!TInfo)
7194     TInfo = Context.getTrivialTypeSourceInfo(literalType);
7195 
7196   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7197 }
7198 
7199 ExprResult
7200 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7201                                SourceLocation RParenLoc, Expr *LiteralExpr) {
7202   QualType literalType = TInfo->getType();
7203 
7204   if (literalType->isArrayType()) {
7205     if (RequireCompleteSizedType(
7206             LParenLoc, Context.getBaseElementType(literalType),
7207             diag::err_array_incomplete_or_sizeless_type,
7208             SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7209       return ExprError();
7210     if (literalType->isVariableArrayType()) {
7211       if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7212                                            diag::err_variable_object_no_init)) {
7213         return ExprError();
7214       }
7215     }
7216   } else if (!literalType->isDependentType() &&
7217              RequireCompleteType(LParenLoc, literalType,
7218                diag::err_typecheck_decl_incomplete_type,
7219                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7220     return ExprError();
7221 
7222   InitializedEntity Entity
7223     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
7224   InitializationKind Kind
7225     = InitializationKind::CreateCStyleCast(LParenLoc,
7226                                            SourceRange(LParenLoc, RParenLoc),
7227                                            /*InitList=*/true);
7228   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7229   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7230                                       &literalType);
7231   if (Result.isInvalid())
7232     return ExprError();
7233   LiteralExpr = Result.get();
7234 
7235   bool isFileScope = !CurContext->isFunctionOrMethod();
7236 
7237   // In C, compound literals are l-values for some reason.
7238   // For GCC compatibility, in C++, file-scope array compound literals with
7239   // constant initializers are also l-values, and compound literals are
7240   // otherwise prvalues.
7241   //
7242   // (GCC also treats C++ list-initialized file-scope array prvalues with
7243   // constant initializers as l-values, but that's non-conforming, so we don't
7244   // follow it there.)
7245   //
7246   // FIXME: It would be better to handle the lvalue cases as materializing and
7247   // lifetime-extending a temporary object, but our materialized temporaries
7248   // representation only supports lifetime extension from a variable, not "out
7249   // of thin air".
7250   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7251   // is bound to the result of applying array-to-pointer decay to the compound
7252   // literal.
7253   // FIXME: GCC supports compound literals of reference type, which should
7254   // obviously have a value kind derived from the kind of reference involved.
7255   ExprValueKind VK =
7256       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7257           ? VK_PRValue
7258           : VK_LValue;
7259 
7260   if (isFileScope)
7261     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7262       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7263         Expr *Init = ILE->getInit(i);
7264         ILE->setInit(i, ConstantExpr::Create(Context, Init));
7265       }
7266 
7267   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7268                                               VK, LiteralExpr, isFileScope);
7269   if (isFileScope) {
7270     if (!LiteralExpr->isTypeDependent() &&
7271         !LiteralExpr->isValueDependent() &&
7272         !literalType->isDependentType()) // C99 6.5.2.5p3
7273       if (CheckForConstantInitializer(LiteralExpr, literalType))
7274         return ExprError();
7275   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7276              literalType.getAddressSpace() != LangAS::Default) {
7277     // Embedded-C extensions to C99 6.5.2.5:
7278     //   "If the compound literal occurs inside the body of a function, the
7279     //   type name shall not be qualified by an address-space qualifier."
7280     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7281       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7282     return ExprError();
7283   }
7284 
7285   if (!isFileScope && !getLangOpts().CPlusPlus) {
7286     // Compound literals that have automatic storage duration are destroyed at
7287     // the end of the scope in C; in C++, they're just temporaries.
7288 
7289     // Emit diagnostics if it is or contains a C union type that is non-trivial
7290     // to destruct.
7291     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7292       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
7293                             NTCUC_CompoundLiteral, NTCUK_Destruct);
7294 
7295     // Diagnose jumps that enter or exit the lifetime of the compound literal.
7296     if (literalType.isDestructedType()) {
7297       Cleanup.setExprNeedsCleanups(true);
7298       ExprCleanupObjects.push_back(E);
7299       getCurFunction()->setHasBranchProtectedScope();
7300     }
7301   }
7302 
7303   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7304       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7305     checkNonTrivialCUnionInInitializer(E->getInitializer(),
7306                                        E->getInitializer()->getExprLoc());
7307 
7308   return MaybeBindToTemporary(E);
7309 }
7310 
7311 ExprResult
7312 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7313                     SourceLocation RBraceLoc) {
7314   // Only produce each kind of designated initialization diagnostic once.
7315   SourceLocation FirstDesignator;
7316   bool DiagnosedArrayDesignator = false;
7317   bool DiagnosedNestedDesignator = false;
7318   bool DiagnosedMixedDesignator = false;
7319 
7320   // Check that any designated initializers are syntactically valid in the
7321   // current language mode.
7322   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7323     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7324       if (FirstDesignator.isInvalid())
7325         FirstDesignator = DIE->getBeginLoc();
7326 
7327       if (!getLangOpts().CPlusPlus)
7328         break;
7329 
7330       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7331         DiagnosedNestedDesignator = true;
7332         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7333           << DIE->getDesignatorsSourceRange();
7334       }
7335 
7336       for (auto &Desig : DIE->designators()) {
7337         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7338           DiagnosedArrayDesignator = true;
7339           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7340             << Desig.getSourceRange();
7341         }
7342       }
7343 
7344       if (!DiagnosedMixedDesignator &&
7345           !isa<DesignatedInitExpr>(InitArgList[0])) {
7346         DiagnosedMixedDesignator = true;
7347         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7348           << DIE->getSourceRange();
7349         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7350           << InitArgList[0]->getSourceRange();
7351       }
7352     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7353                isa<DesignatedInitExpr>(InitArgList[0])) {
7354       DiagnosedMixedDesignator = true;
7355       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7356       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7357         << DIE->getSourceRange();
7358       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7359         << InitArgList[I]->getSourceRange();
7360     }
7361   }
7362 
7363   if (FirstDesignator.isValid()) {
7364     // Only diagnose designated initiaization as a C++20 extension if we didn't
7365     // already diagnose use of (non-C++20) C99 designator syntax.
7366     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7367         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7368       Diag(FirstDesignator, getLangOpts().CPlusPlus20
7369                                 ? diag::warn_cxx17_compat_designated_init
7370                                 : diag::ext_cxx_designated_init);
7371     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7372       Diag(FirstDesignator, diag::ext_designated_init);
7373     }
7374   }
7375 
7376   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7377 }
7378 
7379 ExprResult
7380 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7381                     SourceLocation RBraceLoc) {
7382   // Semantic analysis for initializers is done by ActOnDeclarator() and
7383   // CheckInitializer() - it requires knowledge of the object being initialized.
7384 
7385   // Immediately handle non-overload placeholders.  Overloads can be
7386   // resolved contextually, but everything else here can't.
7387   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7388     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7389       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7390 
7391       // Ignore failures; dropping the entire initializer list because
7392       // of one failure would be terrible for indexing/etc.
7393       if (result.isInvalid()) continue;
7394 
7395       InitArgList[I] = result.get();
7396     }
7397   }
7398 
7399   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7400                                                RBraceLoc);
7401   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7402   return E;
7403 }
7404 
7405 /// Do an explicit extend of the given block pointer if we're in ARC.
7406 void Sema::maybeExtendBlockObject(ExprResult &E) {
7407   assert(E.get()->getType()->isBlockPointerType());
7408   assert(E.get()->isPRValue());
7409 
7410   // Only do this in an r-value context.
7411   if (!getLangOpts().ObjCAutoRefCount) return;
7412 
7413   E = ImplicitCastExpr::Create(
7414       Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7415       /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7416   Cleanup.setExprNeedsCleanups(true);
7417 }
7418 
7419 /// Prepare a conversion of the given expression to an ObjC object
7420 /// pointer type.
7421 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7422   QualType type = E.get()->getType();
7423   if (type->isObjCObjectPointerType()) {
7424     return CK_BitCast;
7425   } else if (type->isBlockPointerType()) {
7426     maybeExtendBlockObject(E);
7427     return CK_BlockPointerToObjCPointerCast;
7428   } else {
7429     assert(type->isPointerType());
7430     return CK_CPointerToObjCPointerCast;
7431   }
7432 }
7433 
7434 /// Prepares for a scalar cast, performing all the necessary stages
7435 /// except the final cast and returning the kind required.
7436 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7437   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7438   // Also, callers should have filtered out the invalid cases with
7439   // pointers.  Everything else should be possible.
7440 
7441   QualType SrcTy = Src.get()->getType();
7442   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7443     return CK_NoOp;
7444 
7445   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7446   case Type::STK_MemberPointer:
7447     llvm_unreachable("member pointer type in C");
7448 
7449   case Type::STK_CPointer:
7450   case Type::STK_BlockPointer:
7451   case Type::STK_ObjCObjectPointer:
7452     switch (DestTy->getScalarTypeKind()) {
7453     case Type::STK_CPointer: {
7454       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7455       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7456       if (SrcAS != DestAS)
7457         return CK_AddressSpaceConversion;
7458       if (Context.hasCvrSimilarType(SrcTy, DestTy))
7459         return CK_NoOp;
7460       return CK_BitCast;
7461     }
7462     case Type::STK_BlockPointer:
7463       return (SrcKind == Type::STK_BlockPointer
7464                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7465     case Type::STK_ObjCObjectPointer:
7466       if (SrcKind == Type::STK_ObjCObjectPointer)
7467         return CK_BitCast;
7468       if (SrcKind == Type::STK_CPointer)
7469         return CK_CPointerToObjCPointerCast;
7470       maybeExtendBlockObject(Src);
7471       return CK_BlockPointerToObjCPointerCast;
7472     case Type::STK_Bool:
7473       return CK_PointerToBoolean;
7474     case Type::STK_Integral:
7475       return CK_PointerToIntegral;
7476     case Type::STK_Floating:
7477     case Type::STK_FloatingComplex:
7478     case Type::STK_IntegralComplex:
7479     case Type::STK_MemberPointer:
7480     case Type::STK_FixedPoint:
7481       llvm_unreachable("illegal cast from pointer");
7482     }
7483     llvm_unreachable("Should have returned before this");
7484 
7485   case Type::STK_FixedPoint:
7486     switch (DestTy->getScalarTypeKind()) {
7487     case Type::STK_FixedPoint:
7488       return CK_FixedPointCast;
7489     case Type::STK_Bool:
7490       return CK_FixedPointToBoolean;
7491     case Type::STK_Integral:
7492       return CK_FixedPointToIntegral;
7493     case Type::STK_Floating:
7494       return CK_FixedPointToFloating;
7495     case Type::STK_IntegralComplex:
7496     case Type::STK_FloatingComplex:
7497       Diag(Src.get()->getExprLoc(),
7498            diag::err_unimplemented_conversion_with_fixed_point_type)
7499           << DestTy;
7500       return CK_IntegralCast;
7501     case Type::STK_CPointer:
7502     case Type::STK_ObjCObjectPointer:
7503     case Type::STK_BlockPointer:
7504     case Type::STK_MemberPointer:
7505       llvm_unreachable("illegal cast to pointer type");
7506     }
7507     llvm_unreachable("Should have returned before this");
7508 
7509   case Type::STK_Bool: // casting from bool is like casting from an integer
7510   case Type::STK_Integral:
7511     switch (DestTy->getScalarTypeKind()) {
7512     case Type::STK_CPointer:
7513     case Type::STK_ObjCObjectPointer:
7514     case Type::STK_BlockPointer:
7515       if (Src.get()->isNullPointerConstant(Context,
7516                                            Expr::NPC_ValueDependentIsNull))
7517         return CK_NullToPointer;
7518       return CK_IntegralToPointer;
7519     case Type::STK_Bool:
7520       return CK_IntegralToBoolean;
7521     case Type::STK_Integral:
7522       return CK_IntegralCast;
7523     case Type::STK_Floating:
7524       return CK_IntegralToFloating;
7525     case Type::STK_IntegralComplex:
7526       Src = ImpCastExprToType(Src.get(),
7527                       DestTy->castAs<ComplexType>()->getElementType(),
7528                       CK_IntegralCast);
7529       return CK_IntegralRealToComplex;
7530     case Type::STK_FloatingComplex:
7531       Src = ImpCastExprToType(Src.get(),
7532                       DestTy->castAs<ComplexType>()->getElementType(),
7533                       CK_IntegralToFloating);
7534       return CK_FloatingRealToComplex;
7535     case Type::STK_MemberPointer:
7536       llvm_unreachable("member pointer type in C");
7537     case Type::STK_FixedPoint:
7538       return CK_IntegralToFixedPoint;
7539     }
7540     llvm_unreachable("Should have returned before this");
7541 
7542   case Type::STK_Floating:
7543     switch (DestTy->getScalarTypeKind()) {
7544     case Type::STK_Floating:
7545       return CK_FloatingCast;
7546     case Type::STK_Bool:
7547       return CK_FloatingToBoolean;
7548     case Type::STK_Integral:
7549       return CK_FloatingToIntegral;
7550     case Type::STK_FloatingComplex:
7551       Src = ImpCastExprToType(Src.get(),
7552                               DestTy->castAs<ComplexType>()->getElementType(),
7553                               CK_FloatingCast);
7554       return CK_FloatingRealToComplex;
7555     case Type::STK_IntegralComplex:
7556       Src = ImpCastExprToType(Src.get(),
7557                               DestTy->castAs<ComplexType>()->getElementType(),
7558                               CK_FloatingToIntegral);
7559       return CK_IntegralRealToComplex;
7560     case Type::STK_CPointer:
7561     case Type::STK_ObjCObjectPointer:
7562     case Type::STK_BlockPointer:
7563       llvm_unreachable("valid float->pointer cast?");
7564     case Type::STK_MemberPointer:
7565       llvm_unreachable("member pointer type in C");
7566     case Type::STK_FixedPoint:
7567       return CK_FloatingToFixedPoint;
7568     }
7569     llvm_unreachable("Should have returned before this");
7570 
7571   case Type::STK_FloatingComplex:
7572     switch (DestTy->getScalarTypeKind()) {
7573     case Type::STK_FloatingComplex:
7574       return CK_FloatingComplexCast;
7575     case Type::STK_IntegralComplex:
7576       return CK_FloatingComplexToIntegralComplex;
7577     case Type::STK_Floating: {
7578       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7579       if (Context.hasSameType(ET, DestTy))
7580         return CK_FloatingComplexToReal;
7581       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7582       return CK_FloatingCast;
7583     }
7584     case Type::STK_Bool:
7585       return CK_FloatingComplexToBoolean;
7586     case Type::STK_Integral:
7587       Src = ImpCastExprToType(Src.get(),
7588                               SrcTy->castAs<ComplexType>()->getElementType(),
7589                               CK_FloatingComplexToReal);
7590       return CK_FloatingToIntegral;
7591     case Type::STK_CPointer:
7592     case Type::STK_ObjCObjectPointer:
7593     case Type::STK_BlockPointer:
7594       llvm_unreachable("valid complex float->pointer cast?");
7595     case Type::STK_MemberPointer:
7596       llvm_unreachable("member pointer type in C");
7597     case Type::STK_FixedPoint:
7598       Diag(Src.get()->getExprLoc(),
7599            diag::err_unimplemented_conversion_with_fixed_point_type)
7600           << SrcTy;
7601       return CK_IntegralCast;
7602     }
7603     llvm_unreachable("Should have returned before this");
7604 
7605   case Type::STK_IntegralComplex:
7606     switch (DestTy->getScalarTypeKind()) {
7607     case Type::STK_FloatingComplex:
7608       return CK_IntegralComplexToFloatingComplex;
7609     case Type::STK_IntegralComplex:
7610       return CK_IntegralComplexCast;
7611     case Type::STK_Integral: {
7612       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7613       if (Context.hasSameType(ET, DestTy))
7614         return CK_IntegralComplexToReal;
7615       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7616       return CK_IntegralCast;
7617     }
7618     case Type::STK_Bool:
7619       return CK_IntegralComplexToBoolean;
7620     case Type::STK_Floating:
7621       Src = ImpCastExprToType(Src.get(),
7622                               SrcTy->castAs<ComplexType>()->getElementType(),
7623                               CK_IntegralComplexToReal);
7624       return CK_IntegralToFloating;
7625     case Type::STK_CPointer:
7626     case Type::STK_ObjCObjectPointer:
7627     case Type::STK_BlockPointer:
7628       llvm_unreachable("valid complex int->pointer cast?");
7629     case Type::STK_MemberPointer:
7630       llvm_unreachable("member pointer type in C");
7631     case Type::STK_FixedPoint:
7632       Diag(Src.get()->getExprLoc(),
7633            diag::err_unimplemented_conversion_with_fixed_point_type)
7634           << SrcTy;
7635       return CK_IntegralCast;
7636     }
7637     llvm_unreachable("Should have returned before this");
7638   }
7639 
7640   llvm_unreachable("Unhandled scalar cast");
7641 }
7642 
7643 static bool breakDownVectorType(QualType type, uint64_t &len,
7644                                 QualType &eltType) {
7645   // Vectors are simple.
7646   if (const VectorType *vecType = type->getAs<VectorType>()) {
7647     len = vecType->getNumElements();
7648     eltType = vecType->getElementType();
7649     assert(eltType->isScalarType());
7650     return true;
7651   }
7652 
7653   // We allow lax conversion to and from non-vector types, but only if
7654   // they're real types (i.e. non-complex, non-pointer scalar types).
7655   if (!type->isRealType()) return false;
7656 
7657   len = 1;
7658   eltType = type;
7659   return true;
7660 }
7661 
7662 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7663 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7664 /// allowed?
7665 ///
7666 /// This will also return false if the two given types do not make sense from
7667 /// the perspective of SVE bitcasts.
7668 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7669   assert(srcTy->isVectorType() || destTy->isVectorType());
7670 
7671   auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7672     if (!FirstType->isSizelessBuiltinType())
7673       return false;
7674 
7675     const auto *VecTy = SecondType->getAs<VectorType>();
7676     return VecTy &&
7677            VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7678   };
7679 
7680   return ValidScalableConversion(srcTy, destTy) ||
7681          ValidScalableConversion(destTy, srcTy);
7682 }
7683 
7684 /// Are the two types matrix types and do they have the same dimensions i.e.
7685 /// do they have the same number of rows and the same number of columns?
7686 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7687   if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7688     return false;
7689 
7690   const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7691   const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7692 
7693   return matSrcType->getNumRows() == matDestType->getNumRows() &&
7694          matSrcType->getNumColumns() == matDestType->getNumColumns();
7695 }
7696 
7697 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7698   assert(DestTy->isVectorType() || SrcTy->isVectorType());
7699 
7700   uint64_t SrcLen, DestLen;
7701   QualType SrcEltTy, DestEltTy;
7702   if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7703     return false;
7704   if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7705     return false;
7706 
7707   // ASTContext::getTypeSize will return the size rounded up to a
7708   // power of 2, so instead of using that, we need to use the raw
7709   // element size multiplied by the element count.
7710   uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7711   uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7712 
7713   return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7714 }
7715 
7716 /// Are the two types lax-compatible vector types?  That is, given
7717 /// that one of them is a vector, do they have equal storage sizes,
7718 /// where the storage size is the number of elements times the element
7719 /// size?
7720 ///
7721 /// This will also return false if either of the types is neither a
7722 /// vector nor a real type.
7723 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7724   assert(destTy->isVectorType() || srcTy->isVectorType());
7725 
7726   // Disallow lax conversions between scalars and ExtVectors (these
7727   // conversions are allowed for other vector types because common headers
7728   // depend on them).  Most scalar OP ExtVector cases are handled by the
7729   // splat path anyway, which does what we want (convert, not bitcast).
7730   // What this rules out for ExtVectors is crazy things like char4*float.
7731   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7732   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7733 
7734   return areVectorTypesSameSize(srcTy, destTy);
7735 }
7736 
7737 /// Is this a legal conversion between two types, one of which is
7738 /// known to be a vector type?
7739 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7740   assert(destTy->isVectorType() || srcTy->isVectorType());
7741 
7742   switch (Context.getLangOpts().getLaxVectorConversions()) {
7743   case LangOptions::LaxVectorConversionKind::None:
7744     return false;
7745 
7746   case LangOptions::LaxVectorConversionKind::Integer:
7747     if (!srcTy->isIntegralOrEnumerationType()) {
7748       auto *Vec = srcTy->getAs<VectorType>();
7749       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7750         return false;
7751     }
7752     if (!destTy->isIntegralOrEnumerationType()) {
7753       auto *Vec = destTy->getAs<VectorType>();
7754       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7755         return false;
7756     }
7757     // OK, integer (vector) -> integer (vector) bitcast.
7758     break;
7759 
7760     case LangOptions::LaxVectorConversionKind::All:
7761     break;
7762   }
7763 
7764   return areLaxCompatibleVectorTypes(srcTy, destTy);
7765 }
7766 
7767 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7768                            CastKind &Kind) {
7769   if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7770     if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7771       return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7772              << DestTy << SrcTy << R;
7773     }
7774   } else if (SrcTy->isMatrixType()) {
7775     return Diag(R.getBegin(),
7776                 diag::err_invalid_conversion_between_matrix_and_type)
7777            << SrcTy << DestTy << R;
7778   } else if (DestTy->isMatrixType()) {
7779     return Diag(R.getBegin(),
7780                 diag::err_invalid_conversion_between_matrix_and_type)
7781            << DestTy << SrcTy << R;
7782   }
7783 
7784   Kind = CK_MatrixCast;
7785   return false;
7786 }
7787 
7788 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7789                            CastKind &Kind) {
7790   assert(VectorTy->isVectorType() && "Not a vector type!");
7791 
7792   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7793     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7794       return Diag(R.getBegin(),
7795                   Ty->isVectorType() ?
7796                   diag::err_invalid_conversion_between_vectors :
7797                   diag::err_invalid_conversion_between_vector_and_integer)
7798         << VectorTy << Ty << R;
7799   } else
7800     return Diag(R.getBegin(),
7801                 diag::err_invalid_conversion_between_vector_and_scalar)
7802       << VectorTy << Ty << R;
7803 
7804   Kind = CK_BitCast;
7805   return false;
7806 }
7807 
7808 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7809   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7810 
7811   if (DestElemTy == SplattedExpr->getType())
7812     return SplattedExpr;
7813 
7814   assert(DestElemTy->isFloatingType() ||
7815          DestElemTy->isIntegralOrEnumerationType());
7816 
7817   CastKind CK;
7818   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7819     // OpenCL requires that we convert `true` boolean expressions to -1, but
7820     // only when splatting vectors.
7821     if (DestElemTy->isFloatingType()) {
7822       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7823       // in two steps: boolean to signed integral, then to floating.
7824       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7825                                                  CK_BooleanToSignedIntegral);
7826       SplattedExpr = CastExprRes.get();
7827       CK = CK_IntegralToFloating;
7828     } else {
7829       CK = CK_BooleanToSignedIntegral;
7830     }
7831   } else {
7832     ExprResult CastExprRes = SplattedExpr;
7833     CK = PrepareScalarCast(CastExprRes, DestElemTy);
7834     if (CastExprRes.isInvalid())
7835       return ExprError();
7836     SplattedExpr = CastExprRes.get();
7837   }
7838   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7839 }
7840 
7841 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7842                                     Expr *CastExpr, CastKind &Kind) {
7843   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7844 
7845   QualType SrcTy = CastExpr->getType();
7846 
7847   // If SrcTy is a VectorType, the total size must match to explicitly cast to
7848   // an ExtVectorType.
7849   // In OpenCL, casts between vectors of different types are not allowed.
7850   // (See OpenCL 6.2).
7851   if (SrcTy->isVectorType()) {
7852     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7853         (getLangOpts().OpenCL &&
7854          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7855       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7856         << DestTy << SrcTy << R;
7857       return ExprError();
7858     }
7859     Kind = CK_BitCast;
7860     return CastExpr;
7861   }
7862 
7863   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
7864   // conversion will take place first from scalar to elt type, and then
7865   // splat from elt type to vector.
7866   if (SrcTy->isPointerType())
7867     return Diag(R.getBegin(),
7868                 diag::err_invalid_conversion_between_vector_and_scalar)
7869       << DestTy << SrcTy << R;
7870 
7871   Kind = CK_VectorSplat;
7872   return prepareVectorSplat(DestTy, CastExpr);
7873 }
7874 
7875 ExprResult
7876 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7877                     Declarator &D, ParsedType &Ty,
7878                     SourceLocation RParenLoc, Expr *CastExpr) {
7879   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7880          "ActOnCastExpr(): missing type or expr");
7881 
7882   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7883   if (D.isInvalidType())
7884     return ExprError();
7885 
7886   if (getLangOpts().CPlusPlus) {
7887     // Check that there are no default arguments (C++ only).
7888     CheckExtraCXXDefaultArguments(D);
7889   } else {
7890     // Make sure any TypoExprs have been dealt with.
7891     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7892     if (!Res.isUsable())
7893       return ExprError();
7894     CastExpr = Res.get();
7895   }
7896 
7897   checkUnusedDeclAttributes(D);
7898 
7899   QualType castType = castTInfo->getType();
7900   Ty = CreateParsedType(castType, castTInfo);
7901 
7902   bool isVectorLiteral = false;
7903 
7904   // Check for an altivec or OpenCL literal,
7905   // i.e. all the elements are integer constants.
7906   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7907   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7908   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7909        && castType->isVectorType() && (PE || PLE)) {
7910     if (PLE && PLE->getNumExprs() == 0) {
7911       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7912       return ExprError();
7913     }
7914     if (PE || PLE->getNumExprs() == 1) {
7915       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7916       if (!E->isTypeDependent() && !E->getType()->isVectorType())
7917         isVectorLiteral = true;
7918     }
7919     else
7920       isVectorLiteral = true;
7921   }
7922 
7923   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7924   // then handle it as such.
7925   if (isVectorLiteral)
7926     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7927 
7928   // If the Expr being casted is a ParenListExpr, handle it specially.
7929   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7930   // sequence of BinOp comma operators.
7931   if (isa<ParenListExpr>(CastExpr)) {
7932     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7933     if (Result.isInvalid()) return ExprError();
7934     CastExpr = Result.get();
7935   }
7936 
7937   if (getLangOpts().CPlusPlus && !castType->isVoidType())
7938     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7939 
7940   CheckTollFreeBridgeCast(castType, CastExpr);
7941 
7942   CheckObjCBridgeRelatedCast(castType, CastExpr);
7943 
7944   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7945 
7946   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7947 }
7948 
7949 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7950                                     SourceLocation RParenLoc, Expr *E,
7951                                     TypeSourceInfo *TInfo) {
7952   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7953          "Expected paren or paren list expression");
7954 
7955   Expr **exprs;
7956   unsigned numExprs;
7957   Expr *subExpr;
7958   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7959   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7960     LiteralLParenLoc = PE->getLParenLoc();
7961     LiteralRParenLoc = PE->getRParenLoc();
7962     exprs = PE->getExprs();
7963     numExprs = PE->getNumExprs();
7964   } else { // isa<ParenExpr> by assertion at function entrance
7965     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7966     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7967     subExpr = cast<ParenExpr>(E)->getSubExpr();
7968     exprs = &subExpr;
7969     numExprs = 1;
7970   }
7971 
7972   QualType Ty = TInfo->getType();
7973   assert(Ty->isVectorType() && "Expected vector type");
7974 
7975   SmallVector<Expr *, 8> initExprs;
7976   const VectorType *VTy = Ty->castAs<VectorType>();
7977   unsigned numElems = VTy->getNumElements();
7978 
7979   // '(...)' form of vector initialization in AltiVec: the number of
7980   // initializers must be one or must match the size of the vector.
7981   // If a single value is specified in the initializer then it will be
7982   // replicated to all the components of the vector
7983   if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,
7984                                  VTy->getElementType()))
7985     return ExprError();
7986   if (ShouldSplatAltivecScalarInCast(VTy)) {
7987     // The number of initializers must be one or must match the size of the
7988     // vector. If a single value is specified in the initializer then it will
7989     // be replicated to all the components of the vector
7990     if (numExprs == 1) {
7991       QualType ElemTy = VTy->getElementType();
7992       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7993       if (Literal.isInvalid())
7994         return ExprError();
7995       Literal = ImpCastExprToType(Literal.get(), ElemTy,
7996                                   PrepareScalarCast(Literal, ElemTy));
7997       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7998     }
7999     else if (numExprs < numElems) {
8000       Diag(E->getExprLoc(),
8001            diag::err_incorrect_number_of_vector_initializers);
8002       return ExprError();
8003     }
8004     else
8005       initExprs.append(exprs, exprs + numExprs);
8006   }
8007   else {
8008     // For OpenCL, when the number of initializers is a single value,
8009     // it will be replicated to all components of the vector.
8010     if (getLangOpts().OpenCL &&
8011         VTy->getVectorKind() == VectorType::GenericVector &&
8012         numExprs == 1) {
8013         QualType ElemTy = VTy->getElementType();
8014         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8015         if (Literal.isInvalid())
8016           return ExprError();
8017         Literal = ImpCastExprToType(Literal.get(), ElemTy,
8018                                     PrepareScalarCast(Literal, ElemTy));
8019         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8020     }
8021 
8022     initExprs.append(exprs, exprs + numExprs);
8023   }
8024   // FIXME: This means that pretty-printing the final AST will produce curly
8025   // braces instead of the original commas.
8026   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8027                                                    initExprs, LiteralRParenLoc);
8028   initE->setType(Ty);
8029   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8030 }
8031 
8032 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8033 /// the ParenListExpr into a sequence of comma binary operators.
8034 ExprResult
8035 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8036   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8037   if (!E)
8038     return OrigExpr;
8039 
8040   ExprResult Result(E->getExpr(0));
8041 
8042   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8043     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8044                         E->getExpr(i));
8045 
8046   if (Result.isInvalid()) return ExprError();
8047 
8048   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8049 }
8050 
8051 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8052                                     SourceLocation R,
8053                                     MultiExprArg Val) {
8054   return ParenListExpr::Create(Context, L, Val, R);
8055 }
8056 
8057 /// Emit a specialized diagnostic when one expression is a null pointer
8058 /// constant and the other is not a pointer.  Returns true if a diagnostic is
8059 /// emitted.
8060 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
8061                                       SourceLocation QuestionLoc) {
8062   Expr *NullExpr = LHSExpr;
8063   Expr *NonPointerExpr = RHSExpr;
8064   Expr::NullPointerConstantKind NullKind =
8065       NullExpr->isNullPointerConstant(Context,
8066                                       Expr::NPC_ValueDependentIsNotNull);
8067 
8068   if (NullKind == Expr::NPCK_NotNull) {
8069     NullExpr = RHSExpr;
8070     NonPointerExpr = LHSExpr;
8071     NullKind =
8072         NullExpr->isNullPointerConstant(Context,
8073                                         Expr::NPC_ValueDependentIsNotNull);
8074   }
8075 
8076   if (NullKind == Expr::NPCK_NotNull)
8077     return false;
8078 
8079   if (NullKind == Expr::NPCK_ZeroExpression)
8080     return false;
8081 
8082   if (NullKind == Expr::NPCK_ZeroLiteral) {
8083     // In this case, check to make sure that we got here from a "NULL"
8084     // string in the source code.
8085     NullExpr = NullExpr->IgnoreParenImpCasts();
8086     SourceLocation loc = NullExpr->getExprLoc();
8087     if (!findMacroSpelling(loc, "NULL"))
8088       return false;
8089   }
8090 
8091   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8092   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8093       << NonPointerExpr->getType() << DiagType
8094       << NonPointerExpr->getSourceRange();
8095   return true;
8096 }
8097 
8098 /// Return false if the condition expression is valid, true otherwise.
8099 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
8100   QualType CondTy = Cond->getType();
8101 
8102   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8103   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8104     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8105       << CondTy << Cond->getSourceRange();
8106     return true;
8107   }
8108 
8109   // C99 6.5.15p2
8110   if (CondTy->isScalarType()) return false;
8111 
8112   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8113     << CondTy << Cond->getSourceRange();
8114   return true;
8115 }
8116 
8117 /// Handle when one or both operands are void type.
8118 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
8119                                          ExprResult &RHS) {
8120     Expr *LHSExpr = LHS.get();
8121     Expr *RHSExpr = RHS.get();
8122 
8123     if (!LHSExpr->getType()->isVoidType())
8124       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8125           << RHSExpr->getSourceRange();
8126     if (!RHSExpr->getType()->isVoidType())
8127       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8128           << LHSExpr->getSourceRange();
8129     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
8130     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
8131     return S.Context.VoidTy;
8132 }
8133 
8134 /// Return false if the NullExpr can be promoted to PointerTy,
8135 /// true otherwise.
8136 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8137                                         QualType PointerTy) {
8138   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8139       !NullExpr.get()->isNullPointerConstant(S.Context,
8140                                             Expr::NPC_ValueDependentIsNull))
8141     return true;
8142 
8143   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8144   return false;
8145 }
8146 
8147 /// Checks compatibility between two pointers and return the resulting
8148 /// type.
8149 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8150                                                      ExprResult &RHS,
8151                                                      SourceLocation Loc) {
8152   QualType LHSTy = LHS.get()->getType();
8153   QualType RHSTy = RHS.get()->getType();
8154 
8155   if (S.Context.hasSameType(LHSTy, RHSTy)) {
8156     // Two identical pointers types are always compatible.
8157     return LHSTy;
8158   }
8159 
8160   QualType lhptee, rhptee;
8161 
8162   // Get the pointee types.
8163   bool IsBlockPointer = false;
8164   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8165     lhptee = LHSBTy->getPointeeType();
8166     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8167     IsBlockPointer = true;
8168   } else {
8169     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8170     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8171   }
8172 
8173   // C99 6.5.15p6: If both operands are pointers to compatible types or to
8174   // differently qualified versions of compatible types, the result type is
8175   // a pointer to an appropriately qualified version of the composite
8176   // type.
8177 
8178   // Only CVR-qualifiers exist in the standard, and the differently-qualified
8179   // clause doesn't make sense for our extensions. E.g. address space 2 should
8180   // be incompatible with address space 3: they may live on different devices or
8181   // anything.
8182   Qualifiers lhQual = lhptee.getQualifiers();
8183   Qualifiers rhQual = rhptee.getQualifiers();
8184 
8185   LangAS ResultAddrSpace = LangAS::Default;
8186   LangAS LAddrSpace = lhQual.getAddressSpace();
8187   LangAS RAddrSpace = rhQual.getAddressSpace();
8188 
8189   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8190   // spaces is disallowed.
8191   if (lhQual.isAddressSpaceSupersetOf(rhQual))
8192     ResultAddrSpace = LAddrSpace;
8193   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8194     ResultAddrSpace = RAddrSpace;
8195   else {
8196     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8197         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8198         << RHS.get()->getSourceRange();
8199     return QualType();
8200   }
8201 
8202   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8203   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8204   lhQual.removeCVRQualifiers();
8205   rhQual.removeCVRQualifiers();
8206 
8207   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8208   // (C99 6.7.3) for address spaces. We assume that the check should behave in
8209   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8210   // qual types are compatible iff
8211   //  * corresponded types are compatible
8212   //  * CVR qualifiers are equal
8213   //  * address spaces are equal
8214   // Thus for conditional operator we merge CVR and address space unqualified
8215   // pointees and if there is a composite type we return a pointer to it with
8216   // merged qualifiers.
8217   LHSCastKind =
8218       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8219   RHSCastKind =
8220       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8221   lhQual.removeAddressSpace();
8222   rhQual.removeAddressSpace();
8223 
8224   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8225   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8226 
8227   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
8228 
8229   if (CompositeTy.isNull()) {
8230     // In this situation, we assume void* type. No especially good
8231     // reason, but this is what gcc does, and we do have to pick
8232     // to get a consistent AST.
8233     QualType incompatTy;
8234     incompatTy = S.Context.getPointerType(
8235         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8236     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8237     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8238 
8239     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8240     // for casts between types with incompatible address space qualifiers.
8241     // For the following code the compiler produces casts between global and
8242     // local address spaces of the corresponded innermost pointees:
8243     // local int *global *a;
8244     // global int *global *b;
8245     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8246     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8247         << LHSTy << RHSTy << LHS.get()->getSourceRange()
8248         << RHS.get()->getSourceRange();
8249 
8250     return incompatTy;
8251   }
8252 
8253   // The pointer types are compatible.
8254   // In case of OpenCL ResultTy should have the address space qualifier
8255   // which is a superset of address spaces of both the 2nd and the 3rd
8256   // operands of the conditional operator.
8257   QualType ResultTy = [&, ResultAddrSpace]() {
8258     if (S.getLangOpts().OpenCL) {
8259       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8260       CompositeQuals.setAddressSpace(ResultAddrSpace);
8261       return S.Context
8262           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8263           .withCVRQualifiers(MergedCVRQual);
8264     }
8265     return CompositeTy.withCVRQualifiers(MergedCVRQual);
8266   }();
8267   if (IsBlockPointer)
8268     ResultTy = S.Context.getBlockPointerType(ResultTy);
8269   else
8270     ResultTy = S.Context.getPointerType(ResultTy);
8271 
8272   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8273   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8274   return ResultTy;
8275 }
8276 
8277 /// Return the resulting type when the operands are both block pointers.
8278 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
8279                                                           ExprResult &LHS,
8280                                                           ExprResult &RHS,
8281                                                           SourceLocation Loc) {
8282   QualType LHSTy = LHS.get()->getType();
8283   QualType RHSTy = RHS.get()->getType();
8284 
8285   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8286     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8287       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8288       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8289       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8290       return destType;
8291     }
8292     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8293       << LHSTy << RHSTy << LHS.get()->getSourceRange()
8294       << RHS.get()->getSourceRange();
8295     return QualType();
8296   }
8297 
8298   // We have 2 block pointer types.
8299   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8300 }
8301 
8302 /// Return the resulting type when the operands are both pointers.
8303 static QualType
8304 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
8305                                             ExprResult &RHS,
8306                                             SourceLocation Loc) {
8307   // get the pointer types
8308   QualType LHSTy = LHS.get()->getType();
8309   QualType RHSTy = RHS.get()->getType();
8310 
8311   // get the "pointed to" types
8312   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8313   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8314 
8315   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8316   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8317     // Figure out necessary qualifiers (C99 6.5.15p6)
8318     QualType destPointee
8319       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8320     QualType destType = S.Context.getPointerType(destPointee);
8321     // Add qualifiers if necessary.
8322     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8323     // Promote to void*.
8324     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8325     return destType;
8326   }
8327   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8328     QualType destPointee
8329       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8330     QualType destType = S.Context.getPointerType(destPointee);
8331     // Add qualifiers if necessary.
8332     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8333     // Promote to void*.
8334     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8335     return destType;
8336   }
8337 
8338   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8339 }
8340 
8341 /// Return false if the first expression is not an integer and the second
8342 /// expression is not a pointer, true otherwise.
8343 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8344                                         Expr* PointerExpr, SourceLocation Loc,
8345                                         bool IsIntFirstExpr) {
8346   if (!PointerExpr->getType()->isPointerType() ||
8347       !Int.get()->getType()->isIntegerType())
8348     return false;
8349 
8350   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8351   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8352 
8353   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8354     << Expr1->getType() << Expr2->getType()
8355     << Expr1->getSourceRange() << Expr2->getSourceRange();
8356   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8357                             CK_IntegralToPointer);
8358   return true;
8359 }
8360 
8361 /// Simple conversion between integer and floating point types.
8362 ///
8363 /// Used when handling the OpenCL conditional operator where the
8364 /// condition is a vector while the other operands are scalar.
8365 ///
8366 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8367 /// types are either integer or floating type. Between the two
8368 /// operands, the type with the higher rank is defined as the "result
8369 /// type". The other operand needs to be promoted to the same type. No
8370 /// other type promotion is allowed. We cannot use
8371 /// UsualArithmeticConversions() for this purpose, since it always
8372 /// promotes promotable types.
8373 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8374                                             ExprResult &RHS,
8375                                             SourceLocation QuestionLoc) {
8376   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8377   if (LHS.isInvalid())
8378     return QualType();
8379   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8380   if (RHS.isInvalid())
8381     return QualType();
8382 
8383   // For conversion purposes, we ignore any qualifiers.
8384   // For example, "const float" and "float" are equivalent.
8385   QualType LHSType =
8386     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8387   QualType RHSType =
8388     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8389 
8390   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8391     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8392       << LHSType << LHS.get()->getSourceRange();
8393     return QualType();
8394   }
8395 
8396   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8397     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8398       << RHSType << RHS.get()->getSourceRange();
8399     return QualType();
8400   }
8401 
8402   // If both types are identical, no conversion is needed.
8403   if (LHSType == RHSType)
8404     return LHSType;
8405 
8406   // Now handle "real" floating types (i.e. float, double, long double).
8407   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8408     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8409                                  /*IsCompAssign = */ false);
8410 
8411   // Finally, we have two differing integer types.
8412   return handleIntegerConversion<doIntegralCast, doIntegralCast>
8413   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8414 }
8415 
8416 /// Convert scalar operands to a vector that matches the
8417 ///        condition in length.
8418 ///
8419 /// Used when handling the OpenCL conditional operator where the
8420 /// condition is a vector while the other operands are scalar.
8421 ///
8422 /// We first compute the "result type" for the scalar operands
8423 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8424 /// into a vector of that type where the length matches the condition
8425 /// vector type. s6.11.6 requires that the element types of the result
8426 /// and the condition must have the same number of bits.
8427 static QualType
8428 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8429                               QualType CondTy, SourceLocation QuestionLoc) {
8430   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8431   if (ResTy.isNull()) return QualType();
8432 
8433   const VectorType *CV = CondTy->getAs<VectorType>();
8434   assert(CV);
8435 
8436   // Determine the vector result type
8437   unsigned NumElements = CV->getNumElements();
8438   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8439 
8440   // Ensure that all types have the same number of bits
8441   if (S.Context.getTypeSize(CV->getElementType())
8442       != S.Context.getTypeSize(ResTy)) {
8443     // Since VectorTy is created internally, it does not pretty print
8444     // with an OpenCL name. Instead, we just print a description.
8445     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8446     SmallString<64> Str;
8447     llvm::raw_svector_ostream OS(Str);
8448     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8449     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8450       << CondTy << OS.str();
8451     return QualType();
8452   }
8453 
8454   // Convert operands to the vector result type
8455   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8456   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8457 
8458   return VectorTy;
8459 }
8460 
8461 /// Return false if this is a valid OpenCL condition vector
8462 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8463                                        SourceLocation QuestionLoc) {
8464   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8465   // integral type.
8466   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8467   assert(CondTy);
8468   QualType EleTy = CondTy->getElementType();
8469   if (EleTy->isIntegerType()) return false;
8470 
8471   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8472     << Cond->getType() << Cond->getSourceRange();
8473   return true;
8474 }
8475 
8476 /// Return false if the vector condition type and the vector
8477 ///        result type are compatible.
8478 ///
8479 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8480 /// number of elements, and their element types have the same number
8481 /// of bits.
8482 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8483                               SourceLocation QuestionLoc) {
8484   const VectorType *CV = CondTy->getAs<VectorType>();
8485   const VectorType *RV = VecResTy->getAs<VectorType>();
8486   assert(CV && RV);
8487 
8488   if (CV->getNumElements() != RV->getNumElements()) {
8489     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8490       << CondTy << VecResTy;
8491     return true;
8492   }
8493 
8494   QualType CVE = CV->getElementType();
8495   QualType RVE = RV->getElementType();
8496 
8497   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8498     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8499       << CondTy << VecResTy;
8500     return true;
8501   }
8502 
8503   return false;
8504 }
8505 
8506 /// Return the resulting type for the conditional operator in
8507 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
8508 ///        s6.3.i) when the condition is a vector type.
8509 static QualType
8510 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8511                              ExprResult &LHS, ExprResult &RHS,
8512                              SourceLocation QuestionLoc) {
8513   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8514   if (Cond.isInvalid())
8515     return QualType();
8516   QualType CondTy = Cond.get()->getType();
8517 
8518   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8519     return QualType();
8520 
8521   // If either operand is a vector then find the vector type of the
8522   // result as specified in OpenCL v1.1 s6.3.i.
8523   if (LHS.get()->getType()->isVectorType() ||
8524       RHS.get()->getType()->isVectorType()) {
8525     bool IsBoolVecLang =
8526         !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8527     QualType VecResTy =
8528         S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8529                               /*isCompAssign*/ false,
8530                               /*AllowBothBool*/ true,
8531                               /*AllowBoolConversions*/ false,
8532                               /*AllowBooleanOperation*/ IsBoolVecLang,
8533                               /*ReportInvalid*/ true);
8534     if (VecResTy.isNull())
8535       return QualType();
8536     // The result type must match the condition type as specified in
8537     // OpenCL v1.1 s6.11.6.
8538     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8539       return QualType();
8540     return VecResTy;
8541   }
8542 
8543   // Both operands are scalar.
8544   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8545 }
8546 
8547 /// Return true if the Expr is block type
8548 static bool checkBlockType(Sema &S, const Expr *E) {
8549   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8550     QualType Ty = CE->getCallee()->getType();
8551     if (Ty->isBlockPointerType()) {
8552       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8553       return true;
8554     }
8555   }
8556   return false;
8557 }
8558 
8559 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8560 /// In that case, LHS = cond.
8561 /// C99 6.5.15
8562 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8563                                         ExprResult &RHS, ExprValueKind &VK,
8564                                         ExprObjectKind &OK,
8565                                         SourceLocation QuestionLoc) {
8566 
8567   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8568   if (!LHSResult.isUsable()) return QualType();
8569   LHS = LHSResult;
8570 
8571   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8572   if (!RHSResult.isUsable()) return QualType();
8573   RHS = RHSResult;
8574 
8575   // C++ is sufficiently different to merit its own checker.
8576   if (getLangOpts().CPlusPlus)
8577     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8578 
8579   VK = VK_PRValue;
8580   OK = OK_Ordinary;
8581 
8582   if (Context.isDependenceAllowed() &&
8583       (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8584        RHS.get()->isTypeDependent())) {
8585     assert(!getLangOpts().CPlusPlus);
8586     assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8587             RHS.get()->containsErrors()) &&
8588            "should only occur in error-recovery path.");
8589     return Context.DependentTy;
8590   }
8591 
8592   // The OpenCL operator with a vector condition is sufficiently
8593   // different to merit its own checker.
8594   if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8595       Cond.get()->getType()->isExtVectorType())
8596     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8597 
8598   // First, check the condition.
8599   Cond = UsualUnaryConversions(Cond.get());
8600   if (Cond.isInvalid())
8601     return QualType();
8602   if (checkCondition(*this, Cond.get(), QuestionLoc))
8603     return QualType();
8604 
8605   // Now check the two expressions.
8606   if (LHS.get()->getType()->isVectorType() ||
8607       RHS.get()->getType()->isVectorType())
8608     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8609                                /*AllowBothBool*/ true,
8610                                /*AllowBoolConversions*/ false,
8611                                /*AllowBooleanOperation*/ false,
8612                                /*ReportInvalid*/ true);
8613 
8614   QualType ResTy =
8615       UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8616   if (LHS.isInvalid() || RHS.isInvalid())
8617     return QualType();
8618 
8619   QualType LHSTy = LHS.get()->getType();
8620   QualType RHSTy = RHS.get()->getType();
8621 
8622   // Diagnose attempts to convert between __ibm128, __float128 and long double
8623   // where such conversions currently can't be handled.
8624   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8625     Diag(QuestionLoc,
8626          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8627       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8628     return QualType();
8629   }
8630 
8631   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8632   // selection operator (?:).
8633   if (getLangOpts().OpenCL &&
8634       ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8635     return QualType();
8636   }
8637 
8638   // If both operands have arithmetic type, do the usual arithmetic conversions
8639   // to find a common type: C99 6.5.15p3,5.
8640   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8641     // Disallow invalid arithmetic conversions, such as those between bit-
8642     // precise integers types of different sizes, or between a bit-precise
8643     // integer and another type.
8644     if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8645       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8646           << LHSTy << RHSTy << LHS.get()->getSourceRange()
8647           << RHS.get()->getSourceRange();
8648       return QualType();
8649     }
8650 
8651     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8652     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8653 
8654     return ResTy;
8655   }
8656 
8657   // And if they're both bfloat (which isn't arithmetic), that's fine too.
8658   if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8659     return LHSTy;
8660   }
8661 
8662   // If both operands are the same structure or union type, the result is that
8663   // type.
8664   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
8665     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8666       if (LHSRT->getDecl() == RHSRT->getDecl())
8667         // "If both the operands have structure or union type, the result has
8668         // that type."  This implies that CV qualifiers are dropped.
8669         return LHSTy.getUnqualifiedType();
8670     // FIXME: Type of conditional expression must be complete in C mode.
8671   }
8672 
8673   // C99 6.5.15p5: "If both operands have void type, the result has void type."
8674   // The following || allows only one side to be void (a GCC-ism).
8675   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8676     return checkConditionalVoidType(*this, LHS, RHS);
8677   }
8678 
8679   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8680   // the type of the other operand."
8681   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8682   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8683 
8684   // All objective-c pointer type analysis is done here.
8685   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8686                                                         QuestionLoc);
8687   if (LHS.isInvalid() || RHS.isInvalid())
8688     return QualType();
8689   if (!compositeType.isNull())
8690     return compositeType;
8691 
8692 
8693   // Handle block pointer types.
8694   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8695     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8696                                                      QuestionLoc);
8697 
8698   // Check constraints for C object pointers types (C99 6.5.15p3,6).
8699   if (LHSTy->isPointerType() && RHSTy->isPointerType())
8700     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8701                                                        QuestionLoc);
8702 
8703   // GCC compatibility: soften pointer/integer mismatch.  Note that
8704   // null pointers have been filtered out by this point.
8705   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8706       /*IsIntFirstExpr=*/true))
8707     return RHSTy;
8708   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8709       /*IsIntFirstExpr=*/false))
8710     return LHSTy;
8711 
8712   // Allow ?: operations in which both operands have the same
8713   // built-in sizeless type.
8714   if (LHSTy->isSizelessBuiltinType() && Context.hasSameType(LHSTy, RHSTy))
8715     return LHSTy;
8716 
8717   // Emit a better diagnostic if one of the expressions is a null pointer
8718   // constant and the other is not a pointer type. In this case, the user most
8719   // likely forgot to take the address of the other expression.
8720   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8721     return QualType();
8722 
8723   // Otherwise, the operands are not compatible.
8724   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8725     << LHSTy << RHSTy << LHS.get()->getSourceRange()
8726     << RHS.get()->getSourceRange();
8727   return QualType();
8728 }
8729 
8730 /// FindCompositeObjCPointerType - Helper method to find composite type of
8731 /// two objective-c pointer types of the two input expressions.
8732 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8733                                             SourceLocation QuestionLoc) {
8734   QualType LHSTy = LHS.get()->getType();
8735   QualType RHSTy = RHS.get()->getType();
8736 
8737   // Handle things like Class and struct objc_class*.  Here we case the result
8738   // to the pseudo-builtin, because that will be implicitly cast back to the
8739   // redefinition type if an attempt is made to access its fields.
8740   if (LHSTy->isObjCClassType() &&
8741       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8742     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8743     return LHSTy;
8744   }
8745   if (RHSTy->isObjCClassType() &&
8746       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8747     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8748     return RHSTy;
8749   }
8750   // And the same for struct objc_object* / id
8751   if (LHSTy->isObjCIdType() &&
8752       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8753     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8754     return LHSTy;
8755   }
8756   if (RHSTy->isObjCIdType() &&
8757       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8758     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8759     return RHSTy;
8760   }
8761   // And the same for struct objc_selector* / SEL
8762   if (Context.isObjCSelType(LHSTy) &&
8763       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8764     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8765     return LHSTy;
8766   }
8767   if (Context.isObjCSelType(RHSTy) &&
8768       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8769     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8770     return RHSTy;
8771   }
8772   // Check constraints for Objective-C object pointers types.
8773   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8774 
8775     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8776       // Two identical object pointer types are always compatible.
8777       return LHSTy;
8778     }
8779     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8780     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8781     QualType compositeType = LHSTy;
8782 
8783     // If both operands are interfaces and either operand can be
8784     // assigned to the other, use that type as the composite
8785     // type. This allows
8786     //   xxx ? (A*) a : (B*) b
8787     // where B is a subclass of A.
8788     //
8789     // Additionally, as for assignment, if either type is 'id'
8790     // allow silent coercion. Finally, if the types are
8791     // incompatible then make sure to use 'id' as the composite
8792     // type so the result is acceptable for sending messages to.
8793 
8794     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8795     // It could return the composite type.
8796     if (!(compositeType =
8797           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8798       // Nothing more to do.
8799     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8800       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8801     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8802       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8803     } else if ((LHSOPT->isObjCQualifiedIdType() ||
8804                 RHSOPT->isObjCQualifiedIdType()) &&
8805                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8806                                                          true)) {
8807       // Need to handle "id<xx>" explicitly.
8808       // GCC allows qualified id and any Objective-C type to devolve to
8809       // id. Currently localizing to here until clear this should be
8810       // part of ObjCQualifiedIdTypesAreCompatible.
8811       compositeType = Context.getObjCIdType();
8812     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8813       compositeType = Context.getObjCIdType();
8814     } else {
8815       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8816       << LHSTy << RHSTy
8817       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8818       QualType incompatTy = Context.getObjCIdType();
8819       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8820       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8821       return incompatTy;
8822     }
8823     // The object pointer types are compatible.
8824     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8825     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8826     return compositeType;
8827   }
8828   // Check Objective-C object pointer types and 'void *'
8829   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8830     if (getLangOpts().ObjCAutoRefCount) {
8831       // ARC forbids the implicit conversion of object pointers to 'void *',
8832       // so these types are not compatible.
8833       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8834           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8835       LHS = RHS = true;
8836       return QualType();
8837     }
8838     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8839     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8840     QualType destPointee
8841     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8842     QualType destType = Context.getPointerType(destPointee);
8843     // Add qualifiers if necessary.
8844     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8845     // Promote to void*.
8846     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8847     return destType;
8848   }
8849   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8850     if (getLangOpts().ObjCAutoRefCount) {
8851       // ARC forbids the implicit conversion of object pointers to 'void *',
8852       // so these types are not compatible.
8853       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8854           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8855       LHS = RHS = true;
8856       return QualType();
8857     }
8858     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8859     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8860     QualType destPointee
8861     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8862     QualType destType = Context.getPointerType(destPointee);
8863     // Add qualifiers if necessary.
8864     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8865     // Promote to void*.
8866     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8867     return destType;
8868   }
8869   return QualType();
8870 }
8871 
8872 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8873 /// ParenRange in parentheses.
8874 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8875                                const PartialDiagnostic &Note,
8876                                SourceRange ParenRange) {
8877   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8878   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8879       EndLoc.isValid()) {
8880     Self.Diag(Loc, Note)
8881       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8882       << FixItHint::CreateInsertion(EndLoc, ")");
8883   } else {
8884     // We can't display the parentheses, so just show the bare note.
8885     Self.Diag(Loc, Note) << ParenRange;
8886   }
8887 }
8888 
8889 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8890   return BinaryOperator::isAdditiveOp(Opc) ||
8891          BinaryOperator::isMultiplicativeOp(Opc) ||
8892          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8893   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8894   // not any of the logical operators.  Bitwise-xor is commonly used as a
8895   // logical-xor because there is no logical-xor operator.  The logical
8896   // operators, including uses of xor, have a high false positive rate for
8897   // precedence warnings.
8898 }
8899 
8900 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8901 /// expression, either using a built-in or overloaded operator,
8902 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8903 /// expression.
8904 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8905                                    Expr **RHSExprs) {
8906   // Don't strip parenthesis: we should not warn if E is in parenthesis.
8907   E = E->IgnoreImpCasts();
8908   E = E->IgnoreConversionOperatorSingleStep();
8909   E = E->IgnoreImpCasts();
8910   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8911     E = MTE->getSubExpr();
8912     E = E->IgnoreImpCasts();
8913   }
8914 
8915   // Built-in binary operator.
8916   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8917     if (IsArithmeticOp(OP->getOpcode())) {
8918       *Opcode = OP->getOpcode();
8919       *RHSExprs = OP->getRHS();
8920       return true;
8921     }
8922   }
8923 
8924   // Overloaded operator.
8925   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8926     if (Call->getNumArgs() != 2)
8927       return false;
8928 
8929     // Make sure this is really a binary operator that is safe to pass into
8930     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8931     OverloadedOperatorKind OO = Call->getOperator();
8932     if (OO < OO_Plus || OO > OO_Arrow ||
8933         OO == OO_PlusPlus || OO == OO_MinusMinus)
8934       return false;
8935 
8936     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8937     if (IsArithmeticOp(OpKind)) {
8938       *Opcode = OpKind;
8939       *RHSExprs = Call->getArg(1);
8940       return true;
8941     }
8942   }
8943 
8944   return false;
8945 }
8946 
8947 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8948 /// or is a logical expression such as (x==y) which has int type, but is
8949 /// commonly interpreted as boolean.
8950 static bool ExprLooksBoolean(Expr *E) {
8951   E = E->IgnoreParenImpCasts();
8952 
8953   if (E->getType()->isBooleanType())
8954     return true;
8955   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8956     return OP->isComparisonOp() || OP->isLogicalOp();
8957   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8958     return OP->getOpcode() == UO_LNot;
8959   if (E->getType()->isPointerType())
8960     return true;
8961   // FIXME: What about overloaded operator calls returning "unspecified boolean
8962   // type"s (commonly pointer-to-members)?
8963 
8964   return false;
8965 }
8966 
8967 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8968 /// and binary operator are mixed in a way that suggests the programmer assumed
8969 /// the conditional operator has higher precedence, for example:
8970 /// "int x = a + someBinaryCondition ? 1 : 2".
8971 static void DiagnoseConditionalPrecedence(Sema &Self,
8972                                           SourceLocation OpLoc,
8973                                           Expr *Condition,
8974                                           Expr *LHSExpr,
8975                                           Expr *RHSExpr) {
8976   BinaryOperatorKind CondOpcode;
8977   Expr *CondRHS;
8978 
8979   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8980     return;
8981   if (!ExprLooksBoolean(CondRHS))
8982     return;
8983 
8984   // The condition is an arithmetic binary expression, with a right-
8985   // hand side that looks boolean, so warn.
8986 
8987   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8988                         ? diag::warn_precedence_bitwise_conditional
8989                         : diag::warn_precedence_conditional;
8990 
8991   Self.Diag(OpLoc, DiagID)
8992       << Condition->getSourceRange()
8993       << BinaryOperator::getOpcodeStr(CondOpcode);
8994 
8995   SuggestParentheses(
8996       Self, OpLoc,
8997       Self.PDiag(diag::note_precedence_silence)
8998           << BinaryOperator::getOpcodeStr(CondOpcode),
8999       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9000 
9001   SuggestParentheses(Self, OpLoc,
9002                      Self.PDiag(diag::note_precedence_conditional_first),
9003                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9004 }
9005 
9006 /// Compute the nullability of a conditional expression.
9007 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
9008                                               QualType LHSTy, QualType RHSTy,
9009                                               ASTContext &Ctx) {
9010   if (!ResTy->isAnyPointerType())
9011     return ResTy;
9012 
9013   auto GetNullability = [&Ctx](QualType Ty) {
9014     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
9015     if (Kind) {
9016       // For our purposes, treat _Nullable_result as _Nullable.
9017       if (*Kind == NullabilityKind::NullableResult)
9018         return NullabilityKind::Nullable;
9019       return *Kind;
9020     }
9021     return NullabilityKind::Unspecified;
9022   };
9023 
9024   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9025   NullabilityKind MergedKind;
9026 
9027   // Compute nullability of a binary conditional expression.
9028   if (IsBin) {
9029     if (LHSKind == NullabilityKind::NonNull)
9030       MergedKind = NullabilityKind::NonNull;
9031     else
9032       MergedKind = RHSKind;
9033   // Compute nullability of a normal conditional expression.
9034   } else {
9035     if (LHSKind == NullabilityKind::Nullable ||
9036         RHSKind == NullabilityKind::Nullable)
9037       MergedKind = NullabilityKind::Nullable;
9038     else if (LHSKind == NullabilityKind::NonNull)
9039       MergedKind = RHSKind;
9040     else if (RHSKind == NullabilityKind::NonNull)
9041       MergedKind = LHSKind;
9042     else
9043       MergedKind = NullabilityKind::Unspecified;
9044   }
9045 
9046   // Return if ResTy already has the correct nullability.
9047   if (GetNullability(ResTy) == MergedKind)
9048     return ResTy;
9049 
9050   // Strip all nullability from ResTy.
9051   while (ResTy->getNullability(Ctx))
9052     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9053 
9054   // Create a new AttributedType with the new nullability kind.
9055   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9056   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9057 }
9058 
9059 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
9060 /// in the case of a the GNU conditional expr extension.
9061 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9062                                     SourceLocation ColonLoc,
9063                                     Expr *CondExpr, Expr *LHSExpr,
9064                                     Expr *RHSExpr) {
9065   if (!Context.isDependenceAllowed()) {
9066     // C cannot handle TypoExpr nodes in the condition because it
9067     // doesn't handle dependent types properly, so make sure any TypoExprs have
9068     // been dealt with before checking the operands.
9069     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9070     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9071     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9072 
9073     if (!CondResult.isUsable())
9074       return ExprError();
9075 
9076     if (LHSExpr) {
9077       if (!LHSResult.isUsable())
9078         return ExprError();
9079     }
9080 
9081     if (!RHSResult.isUsable())
9082       return ExprError();
9083 
9084     CondExpr = CondResult.get();
9085     LHSExpr = LHSResult.get();
9086     RHSExpr = RHSResult.get();
9087   }
9088 
9089   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9090   // was the condition.
9091   OpaqueValueExpr *opaqueValue = nullptr;
9092   Expr *commonExpr = nullptr;
9093   if (!LHSExpr) {
9094     commonExpr = CondExpr;
9095     // Lower out placeholder types first.  This is important so that we don't
9096     // try to capture a placeholder. This happens in few cases in C++; such
9097     // as Objective-C++'s dictionary subscripting syntax.
9098     if (commonExpr->hasPlaceholderType()) {
9099       ExprResult result = CheckPlaceholderExpr(commonExpr);
9100       if (!result.isUsable()) return ExprError();
9101       commonExpr = result.get();
9102     }
9103     // We usually want to apply unary conversions *before* saving, except
9104     // in the special case of a C++ l-value conditional.
9105     if (!(getLangOpts().CPlusPlus
9106           && !commonExpr->isTypeDependent()
9107           && commonExpr->getValueKind() == RHSExpr->getValueKind()
9108           && commonExpr->isGLValue()
9109           && commonExpr->isOrdinaryOrBitFieldObject()
9110           && RHSExpr->isOrdinaryOrBitFieldObject()
9111           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9112       ExprResult commonRes = UsualUnaryConversions(commonExpr);
9113       if (commonRes.isInvalid())
9114         return ExprError();
9115       commonExpr = commonRes.get();
9116     }
9117 
9118     // If the common expression is a class or array prvalue, materialize it
9119     // so that we can safely refer to it multiple times.
9120     if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9121                                     commonExpr->getType()->isArrayType())) {
9122       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9123       if (MatExpr.isInvalid())
9124         return ExprError();
9125       commonExpr = MatExpr.get();
9126     }
9127 
9128     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9129                                                 commonExpr->getType(),
9130                                                 commonExpr->getValueKind(),
9131                                                 commonExpr->getObjectKind(),
9132                                                 commonExpr);
9133     LHSExpr = CondExpr = opaqueValue;
9134   }
9135 
9136   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9137   ExprValueKind VK = VK_PRValue;
9138   ExprObjectKind OK = OK_Ordinary;
9139   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9140   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9141                                              VK, OK, QuestionLoc);
9142   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9143       RHS.isInvalid())
9144     return ExprError();
9145 
9146   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9147                                 RHS.get());
9148 
9149   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9150 
9151   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9152                                          Context);
9153 
9154   if (!commonExpr)
9155     return new (Context)
9156         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9157                             RHS.get(), result, VK, OK);
9158 
9159   return new (Context) BinaryConditionalOperator(
9160       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9161       ColonLoc, result, VK, OK);
9162 }
9163 
9164 // Check if we have a conversion between incompatible cmse function pointer
9165 // types, that is, a conversion between a function pointer with the
9166 // cmse_nonsecure_call attribute and one without.
9167 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9168                                           QualType ToType) {
9169   if (const auto *ToFn =
9170           dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9171     if (const auto *FromFn =
9172             dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9173       FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9174       FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9175 
9176       return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9177     }
9178   }
9179   return false;
9180 }
9181 
9182 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9183 // being closely modeled after the C99 spec:-). The odd characteristic of this
9184 // routine is it effectively iqnores the qualifiers on the top level pointee.
9185 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9186 // FIXME: add a couple examples in this comment.
9187 static Sema::AssignConvertType
9188 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
9189   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9190   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9191 
9192   // get the "pointed to" type (ignoring qualifiers at the top level)
9193   const Type *lhptee, *rhptee;
9194   Qualifiers lhq, rhq;
9195   std::tie(lhptee, lhq) =
9196       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9197   std::tie(rhptee, rhq) =
9198       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9199 
9200   Sema::AssignConvertType ConvTy = Sema::Compatible;
9201 
9202   // C99 6.5.16.1p1: This following citation is common to constraints
9203   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9204   // qualifiers of the type *pointed to* by the right;
9205 
9206   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9207   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9208       lhq.compatiblyIncludesObjCLifetime(rhq)) {
9209     // Ignore lifetime for further calculation.
9210     lhq.removeObjCLifetime();
9211     rhq.removeObjCLifetime();
9212   }
9213 
9214   if (!lhq.compatiblyIncludes(rhq)) {
9215     // Treat address-space mismatches as fatal.
9216     if (!lhq.isAddressSpaceSupersetOf(rhq))
9217       return Sema::IncompatiblePointerDiscardsQualifiers;
9218 
9219     // It's okay to add or remove GC or lifetime qualifiers when converting to
9220     // and from void*.
9221     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9222                         .compatiblyIncludes(
9223                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
9224              && (lhptee->isVoidType() || rhptee->isVoidType()))
9225       ; // keep old
9226 
9227     // Treat lifetime mismatches as fatal.
9228     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9229       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9230 
9231     // For GCC/MS compatibility, other qualifier mismatches are treated
9232     // as still compatible in C.
9233     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9234   }
9235 
9236   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9237   // incomplete type and the other is a pointer to a qualified or unqualified
9238   // version of void...
9239   if (lhptee->isVoidType()) {
9240     if (rhptee->isIncompleteOrObjectType())
9241       return ConvTy;
9242 
9243     // As an extension, we allow cast to/from void* to function pointer.
9244     assert(rhptee->isFunctionType());
9245     return Sema::FunctionVoidPointer;
9246   }
9247 
9248   if (rhptee->isVoidType()) {
9249     if (lhptee->isIncompleteOrObjectType())
9250       return ConvTy;
9251 
9252     // As an extension, we allow cast to/from void* to function pointer.
9253     assert(lhptee->isFunctionType());
9254     return Sema::FunctionVoidPointer;
9255   }
9256 
9257   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9258   // unqualified versions of compatible types, ...
9259   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9260   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9261     // Check if the pointee types are compatible ignoring the sign.
9262     // We explicitly check for char so that we catch "char" vs
9263     // "unsigned char" on systems where "char" is unsigned.
9264     if (lhptee->isCharType())
9265       ltrans = S.Context.UnsignedCharTy;
9266     else if (lhptee->hasSignedIntegerRepresentation())
9267       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9268 
9269     if (rhptee->isCharType())
9270       rtrans = S.Context.UnsignedCharTy;
9271     else if (rhptee->hasSignedIntegerRepresentation())
9272       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9273 
9274     if (ltrans == rtrans) {
9275       // Types are compatible ignoring the sign. Qualifier incompatibility
9276       // takes priority over sign incompatibility because the sign
9277       // warning can be disabled.
9278       if (ConvTy != Sema::Compatible)
9279         return ConvTy;
9280 
9281       return Sema::IncompatiblePointerSign;
9282     }
9283 
9284     // If we are a multi-level pointer, it's possible that our issue is simply
9285     // one of qualification - e.g. char ** -> const char ** is not allowed. If
9286     // the eventual target type is the same and the pointers have the same
9287     // level of indirection, this must be the issue.
9288     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9289       do {
9290         std::tie(lhptee, lhq) =
9291           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9292         std::tie(rhptee, rhq) =
9293           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9294 
9295         // Inconsistent address spaces at this point is invalid, even if the
9296         // address spaces would be compatible.
9297         // FIXME: This doesn't catch address space mismatches for pointers of
9298         // different nesting levels, like:
9299         //   __local int *** a;
9300         //   int ** b = a;
9301         // It's not clear how to actually determine when such pointers are
9302         // invalidly incompatible.
9303         if (lhq.getAddressSpace() != rhq.getAddressSpace())
9304           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9305 
9306       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9307 
9308       if (lhptee == rhptee)
9309         return Sema::IncompatibleNestedPointerQualifiers;
9310     }
9311 
9312     // General pointer incompatibility takes priority over qualifiers.
9313     if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9314       return Sema::IncompatibleFunctionPointer;
9315     return Sema::IncompatiblePointer;
9316   }
9317   if (!S.getLangOpts().CPlusPlus &&
9318       S.IsFunctionConversion(ltrans, rtrans, ltrans))
9319     return Sema::IncompatibleFunctionPointer;
9320   if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9321     return Sema::IncompatibleFunctionPointer;
9322   return ConvTy;
9323 }
9324 
9325 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9326 /// block pointer types are compatible or whether a block and normal pointer
9327 /// are compatible. It is more restrict than comparing two function pointer
9328 // types.
9329 static Sema::AssignConvertType
9330 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
9331                                     QualType RHSType) {
9332   assert(LHSType.isCanonical() && "LHS not canonicalized!");
9333   assert(RHSType.isCanonical() && "RHS not canonicalized!");
9334 
9335   QualType lhptee, rhptee;
9336 
9337   // get the "pointed to" type (ignoring qualifiers at the top level)
9338   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9339   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9340 
9341   // In C++, the types have to match exactly.
9342   if (S.getLangOpts().CPlusPlus)
9343     return Sema::IncompatibleBlockPointer;
9344 
9345   Sema::AssignConvertType ConvTy = Sema::Compatible;
9346 
9347   // For blocks we enforce that qualifiers are identical.
9348   Qualifiers LQuals = lhptee.getLocalQualifiers();
9349   Qualifiers RQuals = rhptee.getLocalQualifiers();
9350   if (S.getLangOpts().OpenCL) {
9351     LQuals.removeAddressSpace();
9352     RQuals.removeAddressSpace();
9353   }
9354   if (LQuals != RQuals)
9355     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9356 
9357   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9358   // assignment.
9359   // The current behavior is similar to C++ lambdas. A block might be
9360   // assigned to a variable iff its return type and parameters are compatible
9361   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9362   // an assignment. Presumably it should behave in way that a function pointer
9363   // assignment does in C, so for each parameter and return type:
9364   //  * CVR and address space of LHS should be a superset of CVR and address
9365   //  space of RHS.
9366   //  * unqualified types should be compatible.
9367   if (S.getLangOpts().OpenCL) {
9368     if (!S.Context.typesAreBlockPointerCompatible(
9369             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9370             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9371       return Sema::IncompatibleBlockPointer;
9372   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9373     return Sema::IncompatibleBlockPointer;
9374 
9375   return ConvTy;
9376 }
9377 
9378 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9379 /// for assignment compatibility.
9380 static Sema::AssignConvertType
9381 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9382                                    QualType RHSType) {
9383   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9384   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9385 
9386   if (LHSType->isObjCBuiltinType()) {
9387     // Class is not compatible with ObjC object pointers.
9388     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9389         !RHSType->isObjCQualifiedClassType())
9390       return Sema::IncompatiblePointer;
9391     return Sema::Compatible;
9392   }
9393   if (RHSType->isObjCBuiltinType()) {
9394     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9395         !LHSType->isObjCQualifiedClassType())
9396       return Sema::IncompatiblePointer;
9397     return Sema::Compatible;
9398   }
9399   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9400   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9401 
9402   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9403       // make an exception for id<P>
9404       !LHSType->isObjCQualifiedIdType())
9405     return Sema::CompatiblePointerDiscardsQualifiers;
9406 
9407   if (S.Context.typesAreCompatible(LHSType, RHSType))
9408     return Sema::Compatible;
9409   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9410     return Sema::IncompatibleObjCQualifiedId;
9411   return Sema::IncompatiblePointer;
9412 }
9413 
9414 Sema::AssignConvertType
9415 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9416                                  QualType LHSType, QualType RHSType) {
9417   // Fake up an opaque expression.  We don't actually care about what
9418   // cast operations are required, so if CheckAssignmentConstraints
9419   // adds casts to this they'll be wasted, but fortunately that doesn't
9420   // usually happen on valid code.
9421   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9422   ExprResult RHSPtr = &RHSExpr;
9423   CastKind K;
9424 
9425   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9426 }
9427 
9428 /// This helper function returns true if QT is a vector type that has element
9429 /// type ElementType.
9430 static bool isVector(QualType QT, QualType ElementType) {
9431   if (const VectorType *VT = QT->getAs<VectorType>())
9432     return VT->getElementType().getCanonicalType() == ElementType;
9433   return false;
9434 }
9435 
9436 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9437 /// has code to accommodate several GCC extensions when type checking
9438 /// pointers. Here are some objectionable examples that GCC considers warnings:
9439 ///
9440 ///  int a, *pint;
9441 ///  short *pshort;
9442 ///  struct foo *pfoo;
9443 ///
9444 ///  pint = pshort; // warning: assignment from incompatible pointer type
9445 ///  a = pint; // warning: assignment makes integer from pointer without a cast
9446 ///  pint = a; // warning: assignment makes pointer from integer without a cast
9447 ///  pint = pfoo; // warning: assignment from incompatible pointer type
9448 ///
9449 /// As a result, the code for dealing with pointers is more complex than the
9450 /// C99 spec dictates.
9451 ///
9452 /// Sets 'Kind' for any result kind except Incompatible.
9453 Sema::AssignConvertType
9454 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9455                                  CastKind &Kind, bool ConvertRHS) {
9456   QualType RHSType = RHS.get()->getType();
9457   QualType OrigLHSType = LHSType;
9458 
9459   // Get canonical types.  We're not formatting these types, just comparing
9460   // them.
9461   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9462   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9463 
9464   // Common case: no conversion required.
9465   if (LHSType == RHSType) {
9466     Kind = CK_NoOp;
9467     return Compatible;
9468   }
9469 
9470   // If the LHS has an __auto_type, there are no additional type constraints
9471   // to be worried about.
9472   if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9473     if (AT->isGNUAutoType()) {
9474       Kind = CK_NoOp;
9475       return Compatible;
9476     }
9477   }
9478 
9479   // If we have an atomic type, try a non-atomic assignment, then just add an
9480   // atomic qualification step.
9481   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9482     Sema::AssignConvertType result =
9483       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9484     if (result != Compatible)
9485       return result;
9486     if (Kind != CK_NoOp && ConvertRHS)
9487       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9488     Kind = CK_NonAtomicToAtomic;
9489     return Compatible;
9490   }
9491 
9492   // If the left-hand side is a reference type, then we are in a
9493   // (rare!) case where we've allowed the use of references in C,
9494   // e.g., as a parameter type in a built-in function. In this case,
9495   // just make sure that the type referenced is compatible with the
9496   // right-hand side type. The caller is responsible for adjusting
9497   // LHSType so that the resulting expression does not have reference
9498   // type.
9499   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9500     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9501       Kind = CK_LValueBitCast;
9502       return Compatible;
9503     }
9504     return Incompatible;
9505   }
9506 
9507   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9508   // to the same ExtVector type.
9509   if (LHSType->isExtVectorType()) {
9510     if (RHSType->isExtVectorType())
9511       return Incompatible;
9512     if (RHSType->isArithmeticType()) {
9513       // CK_VectorSplat does T -> vector T, so first cast to the element type.
9514       if (ConvertRHS)
9515         RHS = prepareVectorSplat(LHSType, RHS.get());
9516       Kind = CK_VectorSplat;
9517       return Compatible;
9518     }
9519   }
9520 
9521   // Conversions to or from vector type.
9522   if (LHSType->isVectorType() || RHSType->isVectorType()) {
9523     if (LHSType->isVectorType() && RHSType->isVectorType()) {
9524       // Allow assignments of an AltiVec vector type to an equivalent GCC
9525       // vector type and vice versa
9526       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9527         Kind = CK_BitCast;
9528         return Compatible;
9529       }
9530 
9531       // If we are allowing lax vector conversions, and LHS and RHS are both
9532       // vectors, the total size only needs to be the same. This is a bitcast;
9533       // no bits are changed but the result type is different.
9534       if (isLaxVectorConversion(RHSType, LHSType)) {
9535         Kind = CK_BitCast;
9536         return IncompatibleVectors;
9537       }
9538     }
9539 
9540     // When the RHS comes from another lax conversion (e.g. binops between
9541     // scalars and vectors) the result is canonicalized as a vector. When the
9542     // LHS is also a vector, the lax is allowed by the condition above. Handle
9543     // the case where LHS is a scalar.
9544     if (LHSType->isScalarType()) {
9545       const VectorType *VecType = RHSType->getAs<VectorType>();
9546       if (VecType && VecType->getNumElements() == 1 &&
9547           isLaxVectorConversion(RHSType, LHSType)) {
9548         ExprResult *VecExpr = &RHS;
9549         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9550         Kind = CK_BitCast;
9551         return Compatible;
9552       }
9553     }
9554 
9555     // Allow assignments between fixed-length and sizeless SVE vectors.
9556     if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9557         (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9558       if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9559           Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9560         Kind = CK_BitCast;
9561         return Compatible;
9562       }
9563 
9564     return Incompatible;
9565   }
9566 
9567   // Diagnose attempts to convert between __ibm128, __float128 and long double
9568   // where such conversions currently can't be handled.
9569   if (unsupportedTypeConversion(*this, LHSType, RHSType))
9570     return Incompatible;
9571 
9572   // Disallow assigning a _Complex to a real type in C++ mode since it simply
9573   // discards the imaginary part.
9574   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9575       !LHSType->getAs<ComplexType>())
9576     return Incompatible;
9577 
9578   // Arithmetic conversions.
9579   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9580       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9581     if (ConvertRHS)
9582       Kind = PrepareScalarCast(RHS, LHSType);
9583     return Compatible;
9584   }
9585 
9586   // Conversions to normal pointers.
9587   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9588     // U* -> T*
9589     if (isa<PointerType>(RHSType)) {
9590       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9591       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9592       if (AddrSpaceL != AddrSpaceR)
9593         Kind = CK_AddressSpaceConversion;
9594       else if (Context.hasCvrSimilarType(RHSType, LHSType))
9595         Kind = CK_NoOp;
9596       else
9597         Kind = CK_BitCast;
9598       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9599     }
9600 
9601     // int -> T*
9602     if (RHSType->isIntegerType()) {
9603       Kind = CK_IntegralToPointer; // FIXME: null?
9604       return IntToPointer;
9605     }
9606 
9607     // C pointers are not compatible with ObjC object pointers,
9608     // with two exceptions:
9609     if (isa<ObjCObjectPointerType>(RHSType)) {
9610       //  - conversions to void*
9611       if (LHSPointer->getPointeeType()->isVoidType()) {
9612         Kind = CK_BitCast;
9613         return Compatible;
9614       }
9615 
9616       //  - conversions from 'Class' to the redefinition type
9617       if (RHSType->isObjCClassType() &&
9618           Context.hasSameType(LHSType,
9619                               Context.getObjCClassRedefinitionType())) {
9620         Kind = CK_BitCast;
9621         return Compatible;
9622       }
9623 
9624       Kind = CK_BitCast;
9625       return IncompatiblePointer;
9626     }
9627 
9628     // U^ -> void*
9629     if (RHSType->getAs<BlockPointerType>()) {
9630       if (LHSPointer->getPointeeType()->isVoidType()) {
9631         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9632         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9633                                 ->getPointeeType()
9634                                 .getAddressSpace();
9635         Kind =
9636             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9637         return Compatible;
9638       }
9639     }
9640 
9641     return Incompatible;
9642   }
9643 
9644   // Conversions to block pointers.
9645   if (isa<BlockPointerType>(LHSType)) {
9646     // U^ -> T^
9647     if (RHSType->isBlockPointerType()) {
9648       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9649                               ->getPointeeType()
9650                               .getAddressSpace();
9651       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9652                               ->getPointeeType()
9653                               .getAddressSpace();
9654       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9655       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9656     }
9657 
9658     // int or null -> T^
9659     if (RHSType->isIntegerType()) {
9660       Kind = CK_IntegralToPointer; // FIXME: null
9661       return IntToBlockPointer;
9662     }
9663 
9664     // id -> T^
9665     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9666       Kind = CK_AnyPointerToBlockPointerCast;
9667       return Compatible;
9668     }
9669 
9670     // void* -> T^
9671     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9672       if (RHSPT->getPointeeType()->isVoidType()) {
9673         Kind = CK_AnyPointerToBlockPointerCast;
9674         return Compatible;
9675       }
9676 
9677     return Incompatible;
9678   }
9679 
9680   // Conversions to Objective-C pointers.
9681   if (isa<ObjCObjectPointerType>(LHSType)) {
9682     // A* -> B*
9683     if (RHSType->isObjCObjectPointerType()) {
9684       Kind = CK_BitCast;
9685       Sema::AssignConvertType result =
9686         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9687       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9688           result == Compatible &&
9689           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9690         result = IncompatibleObjCWeakRef;
9691       return result;
9692     }
9693 
9694     // int or null -> A*
9695     if (RHSType->isIntegerType()) {
9696       Kind = CK_IntegralToPointer; // FIXME: null
9697       return IntToPointer;
9698     }
9699 
9700     // In general, C pointers are not compatible with ObjC object pointers,
9701     // with two exceptions:
9702     if (isa<PointerType>(RHSType)) {
9703       Kind = CK_CPointerToObjCPointerCast;
9704 
9705       //  - conversions from 'void*'
9706       if (RHSType->isVoidPointerType()) {
9707         return Compatible;
9708       }
9709 
9710       //  - conversions to 'Class' from its redefinition type
9711       if (LHSType->isObjCClassType() &&
9712           Context.hasSameType(RHSType,
9713                               Context.getObjCClassRedefinitionType())) {
9714         return Compatible;
9715       }
9716 
9717       return IncompatiblePointer;
9718     }
9719 
9720     // Only under strict condition T^ is compatible with an Objective-C pointer.
9721     if (RHSType->isBlockPointerType() &&
9722         LHSType->isBlockCompatibleObjCPointerType(Context)) {
9723       if (ConvertRHS)
9724         maybeExtendBlockObject(RHS);
9725       Kind = CK_BlockPointerToObjCPointerCast;
9726       return Compatible;
9727     }
9728 
9729     return Incompatible;
9730   }
9731 
9732   // Conversions from pointers that are not covered by the above.
9733   if (isa<PointerType>(RHSType)) {
9734     // T* -> _Bool
9735     if (LHSType == Context.BoolTy) {
9736       Kind = CK_PointerToBoolean;
9737       return Compatible;
9738     }
9739 
9740     // T* -> int
9741     if (LHSType->isIntegerType()) {
9742       Kind = CK_PointerToIntegral;
9743       return PointerToInt;
9744     }
9745 
9746     return Incompatible;
9747   }
9748 
9749   // Conversions from Objective-C pointers that are not covered by the above.
9750   if (isa<ObjCObjectPointerType>(RHSType)) {
9751     // T* -> _Bool
9752     if (LHSType == Context.BoolTy) {
9753       Kind = CK_PointerToBoolean;
9754       return Compatible;
9755     }
9756 
9757     // T* -> int
9758     if (LHSType->isIntegerType()) {
9759       Kind = CK_PointerToIntegral;
9760       return PointerToInt;
9761     }
9762 
9763     return Incompatible;
9764   }
9765 
9766   // struct A -> struct B
9767   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9768     if (Context.typesAreCompatible(LHSType, RHSType)) {
9769       Kind = CK_NoOp;
9770       return Compatible;
9771     }
9772   }
9773 
9774   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9775     Kind = CK_IntToOCLSampler;
9776     return Compatible;
9777   }
9778 
9779   return Incompatible;
9780 }
9781 
9782 /// Constructs a transparent union from an expression that is
9783 /// used to initialize the transparent union.
9784 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9785                                       ExprResult &EResult, QualType UnionType,
9786                                       FieldDecl *Field) {
9787   // Build an initializer list that designates the appropriate member
9788   // of the transparent union.
9789   Expr *E = EResult.get();
9790   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9791                                                    E, SourceLocation());
9792   Initializer->setType(UnionType);
9793   Initializer->setInitializedFieldInUnion(Field);
9794 
9795   // Build a compound literal constructing a value of the transparent
9796   // union type from this initializer list.
9797   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9798   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9799                                         VK_PRValue, Initializer, false);
9800 }
9801 
9802 Sema::AssignConvertType
9803 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9804                                                ExprResult &RHS) {
9805   QualType RHSType = RHS.get()->getType();
9806 
9807   // If the ArgType is a Union type, we want to handle a potential
9808   // transparent_union GCC extension.
9809   const RecordType *UT = ArgType->getAsUnionType();
9810   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9811     return Incompatible;
9812 
9813   // The field to initialize within the transparent union.
9814   RecordDecl *UD = UT->getDecl();
9815   FieldDecl *InitField = nullptr;
9816   // It's compatible if the expression matches any of the fields.
9817   for (auto *it : UD->fields()) {
9818     if (it->getType()->isPointerType()) {
9819       // If the transparent union contains a pointer type, we allow:
9820       // 1) void pointer
9821       // 2) null pointer constant
9822       if (RHSType->isPointerType())
9823         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9824           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9825           InitField = it;
9826           break;
9827         }
9828 
9829       if (RHS.get()->isNullPointerConstant(Context,
9830                                            Expr::NPC_ValueDependentIsNull)) {
9831         RHS = ImpCastExprToType(RHS.get(), it->getType(),
9832                                 CK_NullToPointer);
9833         InitField = it;
9834         break;
9835       }
9836     }
9837 
9838     CastKind Kind;
9839     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9840           == Compatible) {
9841       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9842       InitField = it;
9843       break;
9844     }
9845   }
9846 
9847   if (!InitField)
9848     return Incompatible;
9849 
9850   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9851   return Compatible;
9852 }
9853 
9854 Sema::AssignConvertType
9855 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9856                                        bool Diagnose,
9857                                        bool DiagnoseCFAudited,
9858                                        bool ConvertRHS) {
9859   // We need to be able to tell the caller whether we diagnosed a problem, if
9860   // they ask us to issue diagnostics.
9861   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9862 
9863   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9864   // we can't avoid *all* modifications at the moment, so we need some somewhere
9865   // to put the updated value.
9866   ExprResult LocalRHS = CallerRHS;
9867   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9868 
9869   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9870     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9871       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9872           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9873         Diag(RHS.get()->getExprLoc(),
9874              diag::warn_noderef_to_dereferenceable_pointer)
9875             << RHS.get()->getSourceRange();
9876       }
9877     }
9878   }
9879 
9880   if (getLangOpts().CPlusPlus) {
9881     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9882       // C++ 5.17p3: If the left operand is not of class type, the
9883       // expression is implicitly converted (C++ 4) to the
9884       // cv-unqualified type of the left operand.
9885       QualType RHSType = RHS.get()->getType();
9886       if (Diagnose) {
9887         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9888                                         AA_Assigning);
9889       } else {
9890         ImplicitConversionSequence ICS =
9891             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9892                                   /*SuppressUserConversions=*/false,
9893                                   AllowedExplicit::None,
9894                                   /*InOverloadResolution=*/false,
9895                                   /*CStyle=*/false,
9896                                   /*AllowObjCWritebackConversion=*/false);
9897         if (ICS.isFailure())
9898           return Incompatible;
9899         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9900                                         ICS, AA_Assigning);
9901       }
9902       if (RHS.isInvalid())
9903         return Incompatible;
9904       Sema::AssignConvertType result = Compatible;
9905       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9906           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9907         result = IncompatibleObjCWeakRef;
9908       return result;
9909     }
9910 
9911     // FIXME: Currently, we fall through and treat C++ classes like C
9912     // structures.
9913     // FIXME: We also fall through for atomics; not sure what should
9914     // happen there, though.
9915   } else if (RHS.get()->getType() == Context.OverloadTy) {
9916     // As a set of extensions to C, we support overloading on functions. These
9917     // functions need to be resolved here.
9918     DeclAccessPair DAP;
9919     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9920             RHS.get(), LHSType, /*Complain=*/false, DAP))
9921       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9922     else
9923       return Incompatible;
9924   }
9925 
9926   // C99 6.5.16.1p1: the left operand is a pointer and the right is
9927   // a null pointer constant.
9928   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9929        LHSType->isBlockPointerType()) &&
9930       RHS.get()->isNullPointerConstant(Context,
9931                                        Expr::NPC_ValueDependentIsNull)) {
9932     if (Diagnose || ConvertRHS) {
9933       CastKind Kind;
9934       CXXCastPath Path;
9935       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9936                              /*IgnoreBaseAccess=*/false, Diagnose);
9937       if (ConvertRHS)
9938         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9939     }
9940     return Compatible;
9941   }
9942 
9943   // OpenCL queue_t type assignment.
9944   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9945                                  Context, Expr::NPC_ValueDependentIsNull)) {
9946     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9947     return Compatible;
9948   }
9949 
9950   // This check seems unnatural, however it is necessary to ensure the proper
9951   // conversion of functions/arrays. If the conversion were done for all
9952   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9953   // expressions that suppress this implicit conversion (&, sizeof).
9954   //
9955   // Suppress this for references: C++ 8.5.3p5.
9956   if (!LHSType->isReferenceType()) {
9957     // FIXME: We potentially allocate here even if ConvertRHS is false.
9958     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9959     if (RHS.isInvalid())
9960       return Incompatible;
9961   }
9962   CastKind Kind;
9963   Sema::AssignConvertType result =
9964     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9965 
9966   // C99 6.5.16.1p2: The value of the right operand is converted to the
9967   // type of the assignment expression.
9968   // CheckAssignmentConstraints allows the left-hand side to be a reference,
9969   // so that we can use references in built-in functions even in C.
9970   // The getNonReferenceType() call makes sure that the resulting expression
9971   // does not have reference type.
9972   if (result != Incompatible && RHS.get()->getType() != LHSType) {
9973     QualType Ty = LHSType.getNonLValueExprType(Context);
9974     Expr *E = RHS.get();
9975 
9976     // Check for various Objective-C errors. If we are not reporting
9977     // diagnostics and just checking for errors, e.g., during overload
9978     // resolution, return Incompatible to indicate the failure.
9979     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9980         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9981                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
9982       if (!Diagnose)
9983         return Incompatible;
9984     }
9985     if (getLangOpts().ObjC &&
9986         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9987                                            E->getType(), E, Diagnose) ||
9988          CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9989       if (!Diagnose)
9990         return Incompatible;
9991       // Replace the expression with a corrected version and continue so we
9992       // can find further errors.
9993       RHS = E;
9994       return Compatible;
9995     }
9996 
9997     if (ConvertRHS)
9998       RHS = ImpCastExprToType(E, Ty, Kind);
9999   }
10000 
10001   return result;
10002 }
10003 
10004 namespace {
10005 /// The original operand to an operator, prior to the application of the usual
10006 /// arithmetic conversions and converting the arguments of a builtin operator
10007 /// candidate.
10008 struct OriginalOperand {
10009   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10010     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10011       Op = MTE->getSubExpr();
10012     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10013       Op = BTE->getSubExpr();
10014     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10015       Orig = ICE->getSubExprAsWritten();
10016       Conversion = ICE->getConversionFunction();
10017     }
10018   }
10019 
10020   QualType getType() const { return Orig->getType(); }
10021 
10022   Expr *Orig;
10023   NamedDecl *Conversion;
10024 };
10025 }
10026 
10027 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
10028                                ExprResult &RHS) {
10029   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10030 
10031   Diag(Loc, diag::err_typecheck_invalid_operands)
10032     << OrigLHS.getType() << OrigRHS.getType()
10033     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10034 
10035   // If a user-defined conversion was applied to either of the operands prior
10036   // to applying the built-in operator rules, tell the user about it.
10037   if (OrigLHS.Conversion) {
10038     Diag(OrigLHS.Conversion->getLocation(),
10039          diag::note_typecheck_invalid_operands_converted)
10040       << 0 << LHS.get()->getType();
10041   }
10042   if (OrigRHS.Conversion) {
10043     Diag(OrigRHS.Conversion->getLocation(),
10044          diag::note_typecheck_invalid_operands_converted)
10045       << 1 << RHS.get()->getType();
10046   }
10047 
10048   return QualType();
10049 }
10050 
10051 // Diagnose cases where a scalar was implicitly converted to a vector and
10052 // diagnose the underlying types. Otherwise, diagnose the error
10053 // as invalid vector logical operands for non-C++ cases.
10054 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
10055                                             ExprResult &RHS) {
10056   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10057   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10058 
10059   bool LHSNatVec = LHSType->isVectorType();
10060   bool RHSNatVec = RHSType->isVectorType();
10061 
10062   if (!(LHSNatVec && RHSNatVec)) {
10063     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10064     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10065     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10066         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10067         << Vector->getSourceRange();
10068     return QualType();
10069   }
10070 
10071   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10072       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10073       << RHS.get()->getSourceRange();
10074 
10075   return QualType();
10076 }
10077 
10078 /// Try to convert a value of non-vector type to a vector type by converting
10079 /// the type to the element type of the vector and then performing a splat.
10080 /// If the language is OpenCL, we only use conversions that promote scalar
10081 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10082 /// for float->int.
10083 ///
10084 /// OpenCL V2.0 6.2.6.p2:
10085 /// An error shall occur if any scalar operand type has greater rank
10086 /// than the type of the vector element.
10087 ///
10088 /// \param scalar - if non-null, actually perform the conversions
10089 /// \return true if the operation fails (but without diagnosing the failure)
10090 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
10091                                      QualType scalarTy,
10092                                      QualType vectorEltTy,
10093                                      QualType vectorTy,
10094                                      unsigned &DiagID) {
10095   // The conversion to apply to the scalar before splatting it,
10096   // if necessary.
10097   CastKind scalarCast = CK_NoOp;
10098 
10099   if (vectorEltTy->isIntegralType(S.Context)) {
10100     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10101         (scalarTy->isIntegerType() &&
10102          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10103       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10104       return true;
10105     }
10106     if (!scalarTy->isIntegralType(S.Context))
10107       return true;
10108     scalarCast = CK_IntegralCast;
10109   } else if (vectorEltTy->isRealFloatingType()) {
10110     if (scalarTy->isRealFloatingType()) {
10111       if (S.getLangOpts().OpenCL &&
10112           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10113         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10114         return true;
10115       }
10116       scalarCast = CK_FloatingCast;
10117     }
10118     else if (scalarTy->isIntegralType(S.Context))
10119       scalarCast = CK_IntegralToFloating;
10120     else
10121       return true;
10122   } else {
10123     return true;
10124   }
10125 
10126   // Adjust scalar if desired.
10127   if (scalar) {
10128     if (scalarCast != CK_NoOp)
10129       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10130     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10131   }
10132   return false;
10133 }
10134 
10135 /// Convert vector E to a vector with the same number of elements but different
10136 /// element type.
10137 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10138   const auto *VecTy = E->getType()->getAs<VectorType>();
10139   assert(VecTy && "Expression E must be a vector");
10140   QualType NewVecTy =
10141       VecTy->isExtVectorType()
10142           ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10143           : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10144                                     VecTy->getVectorKind());
10145 
10146   // Look through the implicit cast. Return the subexpression if its type is
10147   // NewVecTy.
10148   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10149     if (ICE->getSubExpr()->getType() == NewVecTy)
10150       return ICE->getSubExpr();
10151 
10152   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10153   return S.ImpCastExprToType(E, NewVecTy, Cast);
10154 }
10155 
10156 /// Test if a (constant) integer Int can be casted to another integer type
10157 /// IntTy without losing precision.
10158 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
10159                                       QualType OtherIntTy) {
10160   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10161 
10162   // Reject cases where the value of the Int is unknown as that would
10163   // possibly cause truncation, but accept cases where the scalar can be
10164   // demoted without loss of precision.
10165   Expr::EvalResult EVResult;
10166   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10167   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10168   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10169   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10170 
10171   if (CstInt) {
10172     // If the scalar is constant and is of a higher order and has more active
10173     // bits that the vector element type, reject it.
10174     llvm::APSInt Result = EVResult.Val.getInt();
10175     unsigned NumBits = IntSigned
10176                            ? (Result.isNegative() ? Result.getMinSignedBits()
10177                                                   : Result.getActiveBits())
10178                            : Result.getActiveBits();
10179     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10180       return true;
10181 
10182     // If the signedness of the scalar type and the vector element type
10183     // differs and the number of bits is greater than that of the vector
10184     // element reject it.
10185     return (IntSigned != OtherIntSigned &&
10186             NumBits > S.Context.getIntWidth(OtherIntTy));
10187   }
10188 
10189   // Reject cases where the value of the scalar is not constant and it's
10190   // order is greater than that of the vector element type.
10191   return (Order < 0);
10192 }
10193 
10194 /// Test if a (constant) integer Int can be casted to floating point type
10195 /// FloatTy without losing precision.
10196 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
10197                                      QualType FloatTy) {
10198   QualType IntTy = Int->get()->getType().getUnqualifiedType();
10199 
10200   // Determine if the integer constant can be expressed as a floating point
10201   // number of the appropriate type.
10202   Expr::EvalResult EVResult;
10203   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10204 
10205   uint64_t Bits = 0;
10206   if (CstInt) {
10207     // Reject constants that would be truncated if they were converted to
10208     // the floating point type. Test by simple to/from conversion.
10209     // FIXME: Ideally the conversion to an APFloat and from an APFloat
10210     //        could be avoided if there was a convertFromAPInt method
10211     //        which could signal back if implicit truncation occurred.
10212     llvm::APSInt Result = EVResult.Val.getInt();
10213     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10214     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10215                            llvm::APFloat::rmTowardZero);
10216     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10217                              !IntTy->hasSignedIntegerRepresentation());
10218     bool Ignored = false;
10219     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10220                            &Ignored);
10221     if (Result != ConvertBack)
10222       return true;
10223   } else {
10224     // Reject types that cannot be fully encoded into the mantissa of
10225     // the float.
10226     Bits = S.Context.getTypeSize(IntTy);
10227     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10228         S.Context.getFloatTypeSemantics(FloatTy));
10229     if (Bits > FloatPrec)
10230       return true;
10231   }
10232 
10233   return false;
10234 }
10235 
10236 /// Attempt to convert and splat Scalar into a vector whose types matches
10237 /// Vector following GCC conversion rules. The rule is that implicit
10238 /// conversion can occur when Scalar can be casted to match Vector's element
10239 /// type without causing truncation of Scalar.
10240 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
10241                                         ExprResult *Vector) {
10242   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10243   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10244   const auto *VT = VectorTy->castAs<VectorType>();
10245 
10246   assert(!isa<ExtVectorType>(VT) &&
10247          "ExtVectorTypes should not be handled here!");
10248 
10249   QualType VectorEltTy = VT->getElementType();
10250 
10251   // Reject cases where the vector element type or the scalar element type are
10252   // not integral or floating point types.
10253   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10254     return true;
10255 
10256   // The conversion to apply to the scalar before splatting it,
10257   // if necessary.
10258   CastKind ScalarCast = CK_NoOp;
10259 
10260   // Accept cases where the vector elements are integers and the scalar is
10261   // an integer.
10262   // FIXME: Notionally if the scalar was a floating point value with a precise
10263   //        integral representation, we could cast it to an appropriate integer
10264   //        type and then perform the rest of the checks here. GCC will perform
10265   //        this conversion in some cases as determined by the input language.
10266   //        We should accept it on a language independent basis.
10267   if (VectorEltTy->isIntegralType(S.Context) &&
10268       ScalarTy->isIntegralType(S.Context) &&
10269       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10270 
10271     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10272       return true;
10273 
10274     ScalarCast = CK_IntegralCast;
10275   } else if (VectorEltTy->isIntegralType(S.Context) &&
10276              ScalarTy->isRealFloatingType()) {
10277     if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10278       ScalarCast = CK_FloatingToIntegral;
10279     else
10280       return true;
10281   } else if (VectorEltTy->isRealFloatingType()) {
10282     if (ScalarTy->isRealFloatingType()) {
10283 
10284       // Reject cases where the scalar type is not a constant and has a higher
10285       // Order than the vector element type.
10286       llvm::APFloat Result(0.0);
10287 
10288       // Determine whether this is a constant scalar. In the event that the
10289       // value is dependent (and thus cannot be evaluated by the constant
10290       // evaluator), skip the evaluation. This will then diagnose once the
10291       // expression is instantiated.
10292       bool CstScalar = Scalar->get()->isValueDependent() ||
10293                        Scalar->get()->EvaluateAsFloat(Result, S.Context);
10294       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10295       if (!CstScalar && Order < 0)
10296         return true;
10297 
10298       // If the scalar cannot be safely casted to the vector element type,
10299       // reject it.
10300       if (CstScalar) {
10301         bool Truncated = false;
10302         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10303                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
10304         if (Truncated)
10305           return true;
10306       }
10307 
10308       ScalarCast = CK_FloatingCast;
10309     } else if (ScalarTy->isIntegralType(S.Context)) {
10310       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10311         return true;
10312 
10313       ScalarCast = CK_IntegralToFloating;
10314     } else
10315       return true;
10316   } else if (ScalarTy->isEnumeralType())
10317     return true;
10318 
10319   // Adjust scalar if desired.
10320   if (Scalar) {
10321     if (ScalarCast != CK_NoOp)
10322       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10323     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10324   }
10325   return false;
10326 }
10327 
10328 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10329                                    SourceLocation Loc, bool IsCompAssign,
10330                                    bool AllowBothBool,
10331                                    bool AllowBoolConversions,
10332                                    bool AllowBoolOperation,
10333                                    bool ReportInvalid) {
10334   if (!IsCompAssign) {
10335     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10336     if (LHS.isInvalid())
10337       return QualType();
10338   }
10339   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10340   if (RHS.isInvalid())
10341     return QualType();
10342 
10343   // For conversion purposes, we ignore any qualifiers.
10344   // For example, "const float" and "float" are equivalent.
10345   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10346   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10347 
10348   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10349   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10350   assert(LHSVecType || RHSVecType);
10351 
10352   if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
10353       (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
10354     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10355 
10356   // AltiVec-style "vector bool op vector bool" combinations are allowed
10357   // for some operators but not others.
10358   if (!AllowBothBool &&
10359       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10360       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10361     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10362 
10363   // This operation may not be performed on boolean vectors.
10364   if (!AllowBoolOperation &&
10365       (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10366     return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10367 
10368   // If the vector types are identical, return.
10369   if (Context.hasSameType(LHSType, RHSType))
10370     return LHSType;
10371 
10372   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10373   if (LHSVecType && RHSVecType &&
10374       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10375     if (isa<ExtVectorType>(LHSVecType)) {
10376       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10377       return LHSType;
10378     }
10379 
10380     if (!IsCompAssign)
10381       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10382     return RHSType;
10383   }
10384 
10385   // AllowBoolConversions says that bool and non-bool AltiVec vectors
10386   // can be mixed, with the result being the non-bool type.  The non-bool
10387   // operand must have integer element type.
10388   if (AllowBoolConversions && LHSVecType && RHSVecType &&
10389       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10390       (Context.getTypeSize(LHSVecType->getElementType()) ==
10391        Context.getTypeSize(RHSVecType->getElementType()))) {
10392     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10393         LHSVecType->getElementType()->isIntegerType() &&
10394         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10395       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10396       return LHSType;
10397     }
10398     if (!IsCompAssign &&
10399         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10400         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10401         RHSVecType->getElementType()->isIntegerType()) {
10402       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10403       return RHSType;
10404     }
10405   }
10406 
10407   // Expressions containing fixed-length and sizeless SVE vectors are invalid
10408   // since the ambiguity can affect the ABI.
10409   auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10410     const VectorType *VecType = SecondType->getAs<VectorType>();
10411     return FirstType->isSizelessBuiltinType() && VecType &&
10412            (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10413             VecType->getVectorKind() ==
10414                 VectorType::SveFixedLengthPredicateVector);
10415   };
10416 
10417   if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10418     Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10419     return QualType();
10420   }
10421 
10422   // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10423   // since the ambiguity can affect the ABI.
10424   auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10425     const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10426     const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10427 
10428     if (FirstVecType && SecondVecType)
10429       return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10430              (SecondVecType->getVectorKind() ==
10431                   VectorType::SveFixedLengthDataVector ||
10432               SecondVecType->getVectorKind() ==
10433                   VectorType::SveFixedLengthPredicateVector);
10434 
10435     return FirstType->isSizelessBuiltinType() && SecondVecType &&
10436            SecondVecType->getVectorKind() == VectorType::GenericVector;
10437   };
10438 
10439   if (IsSveGnuConversion(LHSType, RHSType) ||
10440       IsSveGnuConversion(RHSType, LHSType)) {
10441     Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10442     return QualType();
10443   }
10444 
10445   // If there's a vector type and a scalar, try to convert the scalar to
10446   // the vector element type and splat.
10447   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10448   if (!RHSVecType) {
10449     if (isa<ExtVectorType>(LHSVecType)) {
10450       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10451                                     LHSVecType->getElementType(), LHSType,
10452                                     DiagID))
10453         return LHSType;
10454     } else {
10455       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10456         return LHSType;
10457     }
10458   }
10459   if (!LHSVecType) {
10460     if (isa<ExtVectorType>(RHSVecType)) {
10461       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10462                                     LHSType, RHSVecType->getElementType(),
10463                                     RHSType, DiagID))
10464         return RHSType;
10465     } else {
10466       if (LHS.get()->isLValue() ||
10467           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10468         return RHSType;
10469     }
10470   }
10471 
10472   // FIXME: The code below also handles conversion between vectors and
10473   // non-scalars, we should break this down into fine grained specific checks
10474   // and emit proper diagnostics.
10475   QualType VecType = LHSVecType ? LHSType : RHSType;
10476   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10477   QualType OtherType = LHSVecType ? RHSType : LHSType;
10478   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10479   if (isLaxVectorConversion(OtherType, VecType)) {
10480     // If we're allowing lax vector conversions, only the total (data) size
10481     // needs to be the same. For non compound assignment, if one of the types is
10482     // scalar, the result is always the vector type.
10483     if (!IsCompAssign) {
10484       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10485       return VecType;
10486     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10487     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10488     // type. Note that this is already done by non-compound assignments in
10489     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10490     // <1 x T> -> T. The result is also a vector type.
10491     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10492                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10493       ExprResult *RHSExpr = &RHS;
10494       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10495       return VecType;
10496     }
10497   }
10498 
10499   // Okay, the expression is invalid.
10500 
10501   // If there's a non-vector, non-real operand, diagnose that.
10502   if ((!RHSVecType && !RHSType->isRealType()) ||
10503       (!LHSVecType && !LHSType->isRealType())) {
10504     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10505       << LHSType << RHSType
10506       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10507     return QualType();
10508   }
10509 
10510   // OpenCL V1.1 6.2.6.p1:
10511   // If the operands are of more than one vector type, then an error shall
10512   // occur. Implicit conversions between vector types are not permitted, per
10513   // section 6.2.1.
10514   if (getLangOpts().OpenCL &&
10515       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10516       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10517     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10518                                                            << RHSType;
10519     return QualType();
10520   }
10521 
10522 
10523   // If there is a vector type that is not a ExtVector and a scalar, we reach
10524   // this point if scalar could not be converted to the vector's element type
10525   // without truncation.
10526   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10527       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10528     QualType Scalar = LHSVecType ? RHSType : LHSType;
10529     QualType Vector = LHSVecType ? LHSType : RHSType;
10530     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10531     Diag(Loc,
10532          diag::err_typecheck_vector_not_convertable_implict_truncation)
10533         << ScalarOrVector << Scalar << Vector;
10534 
10535     return QualType();
10536   }
10537 
10538   // Otherwise, use the generic diagnostic.
10539   Diag(Loc, DiagID)
10540     << LHSType << RHSType
10541     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10542   return QualType();
10543 }
10544 
10545 QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10546                                            SourceLocation Loc,
10547                                            bool IsCompAssign,
10548                                            ArithConvKind OperationKind) {
10549   if (!IsCompAssign) {
10550     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10551     if (LHS.isInvalid())
10552       return QualType();
10553   }
10554   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10555   if (RHS.isInvalid())
10556     return QualType();
10557 
10558   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10559   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10560 
10561   unsigned DiagID = diag::err_typecheck_invalid_operands;
10562   if ((OperationKind == ACK_Arithmetic) &&
10563       (LHSType->castAs<BuiltinType>()->isSVEBool() ||
10564        RHSType->castAs<BuiltinType>()->isSVEBool())) {
10565     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10566                       << RHS.get()->getSourceRange();
10567     return QualType();
10568   }
10569 
10570   if (Context.hasSameType(LHSType, RHSType))
10571     return LHSType;
10572 
10573   auto tryScalableVectorConvert = [this](ExprResult *Src, QualType SrcType,
10574                                          QualType DestType) {
10575     const QualType DestBaseType = DestType->getSveEltType(Context);
10576     if (DestBaseType->getUnqualifiedDesugaredType() ==
10577         SrcType->getUnqualifiedDesugaredType()) {
10578       unsigned DiagID = diag::err_typecheck_invalid_operands;
10579       if (!tryVectorConvertAndSplat(*this, Src, SrcType, DestBaseType, DestType,
10580                                     DiagID))
10581         return DestType;
10582     }
10583     return QualType();
10584   };
10585 
10586   if (LHSType->isVLSTBuiltinType() && !RHSType->isVLSTBuiltinType()) {
10587     auto DestType = tryScalableVectorConvert(&RHS, RHSType, LHSType);
10588     if (DestType == QualType())
10589       return InvalidOperands(Loc, LHS, RHS);
10590     return DestType;
10591   }
10592 
10593   if (RHSType->isVLSTBuiltinType() && !LHSType->isVLSTBuiltinType()) {
10594     auto DestType = tryScalableVectorConvert((IsCompAssign ? nullptr : &LHS),
10595                                              LHSType, RHSType);
10596     if (DestType == QualType())
10597       return InvalidOperands(Loc, LHS, RHS);
10598     return DestType;
10599   }
10600 
10601   Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10602                     << RHS.get()->getSourceRange();
10603   return QualType();
10604 }
10605 
10606 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10607 // expression.  These are mainly cases where the null pointer is used as an
10608 // integer instead of a pointer.
10609 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10610                                 SourceLocation Loc, bool IsCompare) {
10611   // The canonical way to check for a GNU null is with isNullPointerConstant,
10612   // but we use a bit of a hack here for speed; this is a relatively
10613   // hot path, and isNullPointerConstant is slow.
10614   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10615   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10616 
10617   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10618 
10619   // Avoid analyzing cases where the result will either be invalid (and
10620   // diagnosed as such) or entirely valid and not something to warn about.
10621   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10622       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10623     return;
10624 
10625   // Comparison operations would not make sense with a null pointer no matter
10626   // what the other expression is.
10627   if (!IsCompare) {
10628     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10629         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10630         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10631     return;
10632   }
10633 
10634   // The rest of the operations only make sense with a null pointer
10635   // if the other expression is a pointer.
10636   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10637       NonNullType->canDecayToPointerType())
10638     return;
10639 
10640   S.Diag(Loc, diag::warn_null_in_comparison_operation)
10641       << LHSNull /* LHS is NULL */ << NonNullType
10642       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10643 }
10644 
10645 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10646                                           SourceLocation Loc) {
10647   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10648   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10649   if (!LUE || !RUE)
10650     return;
10651   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10652       RUE->getKind() != UETT_SizeOf)
10653     return;
10654 
10655   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10656   QualType LHSTy = LHSArg->getType();
10657   QualType RHSTy;
10658 
10659   if (RUE->isArgumentType())
10660     RHSTy = RUE->getArgumentType().getNonReferenceType();
10661   else
10662     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10663 
10664   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10665     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10666       return;
10667 
10668     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10669     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10670       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10671         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10672             << LHSArgDecl;
10673     }
10674   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10675     QualType ArrayElemTy = ArrayTy->getElementType();
10676     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10677         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10678         RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10679         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10680       return;
10681     S.Diag(Loc, diag::warn_division_sizeof_array)
10682         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10683     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10684       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10685         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10686             << LHSArgDecl;
10687     }
10688 
10689     S.Diag(Loc, diag::note_precedence_silence) << RHS;
10690   }
10691 }
10692 
10693 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10694                                                ExprResult &RHS,
10695                                                SourceLocation Loc, bool IsDiv) {
10696   // Check for division/remainder by zero.
10697   Expr::EvalResult RHSValue;
10698   if (!RHS.get()->isValueDependent() &&
10699       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10700       RHSValue.Val.getInt() == 0)
10701     S.DiagRuntimeBehavior(Loc, RHS.get(),
10702                           S.PDiag(diag::warn_remainder_division_by_zero)
10703                             << IsDiv << RHS.get()->getSourceRange());
10704 }
10705 
10706 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10707                                            SourceLocation Loc,
10708                                            bool IsCompAssign, bool IsDiv) {
10709   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10710 
10711   QualType LHSTy = LHS.get()->getType();
10712   QualType RHSTy = RHS.get()->getType();
10713   if (LHSTy->isVectorType() || RHSTy->isVectorType())
10714     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10715                                /*AllowBothBool*/ getLangOpts().AltiVec,
10716                                /*AllowBoolConversions*/ false,
10717                                /*AllowBooleanOperation*/ false,
10718                                /*ReportInvalid*/ true);
10719   if (LHSTy->isVLSTBuiltinType() || RHSTy->isVLSTBuiltinType())
10720     return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10721                                        ACK_Arithmetic);
10722   if (!IsDiv &&
10723       (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10724     return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10725   // For division, only matrix-by-scalar is supported. Other combinations with
10726   // matrix types are invalid.
10727   if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10728     return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10729 
10730   QualType compType = UsualArithmeticConversions(
10731       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10732   if (LHS.isInvalid() || RHS.isInvalid())
10733     return QualType();
10734 
10735 
10736   if (compType.isNull() || !compType->isArithmeticType())
10737     return InvalidOperands(Loc, LHS, RHS);
10738   if (IsDiv) {
10739     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10740     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10741   }
10742   return compType;
10743 }
10744 
10745 QualType Sema::CheckRemainderOperands(
10746   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10747   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10748 
10749   if (LHS.get()->getType()->isVectorType() ||
10750       RHS.get()->getType()->isVectorType()) {
10751     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10752         RHS.get()->getType()->hasIntegerRepresentation())
10753       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10754                                  /*AllowBothBool*/ getLangOpts().AltiVec,
10755                                  /*AllowBoolConversions*/ false,
10756                                  /*AllowBooleanOperation*/ false,
10757                                  /*ReportInvalid*/ true);
10758     return InvalidOperands(Loc, LHS, RHS);
10759   }
10760 
10761   if (LHS.get()->getType()->isVLSTBuiltinType() ||
10762       RHS.get()->getType()->isVLSTBuiltinType()) {
10763     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10764         RHS.get()->getType()->hasIntegerRepresentation())
10765       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10766                                          ACK_Arithmetic);
10767 
10768     return InvalidOperands(Loc, LHS, RHS);
10769   }
10770 
10771   QualType compType = UsualArithmeticConversions(
10772       LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10773   if (LHS.isInvalid() || RHS.isInvalid())
10774     return QualType();
10775 
10776   if (compType.isNull() || !compType->isIntegerType())
10777     return InvalidOperands(Loc, LHS, RHS);
10778   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10779   return compType;
10780 }
10781 
10782 /// Diagnose invalid arithmetic on two void pointers.
10783 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10784                                                 Expr *LHSExpr, Expr *RHSExpr) {
10785   S.Diag(Loc, S.getLangOpts().CPlusPlus
10786                 ? diag::err_typecheck_pointer_arith_void_type
10787                 : diag::ext_gnu_void_ptr)
10788     << 1 /* two pointers */ << LHSExpr->getSourceRange()
10789                             << RHSExpr->getSourceRange();
10790 }
10791 
10792 /// Diagnose invalid arithmetic on a void pointer.
10793 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10794                                             Expr *Pointer) {
10795   S.Diag(Loc, S.getLangOpts().CPlusPlus
10796                 ? diag::err_typecheck_pointer_arith_void_type
10797                 : diag::ext_gnu_void_ptr)
10798     << 0 /* one pointer */ << Pointer->getSourceRange();
10799 }
10800 
10801 /// Diagnose invalid arithmetic on a null pointer.
10802 ///
10803 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10804 /// idiom, which we recognize as a GNU extension.
10805 ///
10806 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10807                                             Expr *Pointer, bool IsGNUIdiom) {
10808   if (IsGNUIdiom)
10809     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10810       << Pointer->getSourceRange();
10811   else
10812     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10813       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10814 }
10815 
10816 /// Diagnose invalid subraction on a null pointer.
10817 ///
10818 static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
10819                                              Expr *Pointer, bool BothNull) {
10820   // Null - null is valid in C++ [expr.add]p7
10821   if (BothNull && S.getLangOpts().CPlusPlus)
10822     return;
10823 
10824   // Is this s a macro from a system header?
10825   if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
10826     return;
10827 
10828   S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
10829       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10830 }
10831 
10832 /// Diagnose invalid arithmetic on two function pointers.
10833 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10834                                                     Expr *LHS, Expr *RHS) {
10835   assert(LHS->getType()->isAnyPointerType());
10836   assert(RHS->getType()->isAnyPointerType());
10837   S.Diag(Loc, S.getLangOpts().CPlusPlus
10838                 ? diag::err_typecheck_pointer_arith_function_type
10839                 : diag::ext_gnu_ptr_func_arith)
10840     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10841     // We only show the second type if it differs from the first.
10842     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10843                                                    RHS->getType())
10844     << RHS->getType()->getPointeeType()
10845     << LHS->getSourceRange() << RHS->getSourceRange();
10846 }
10847 
10848 /// Diagnose invalid arithmetic on a function pointer.
10849 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10850                                                 Expr *Pointer) {
10851   assert(Pointer->getType()->isAnyPointerType());
10852   S.Diag(Loc, S.getLangOpts().CPlusPlus
10853                 ? diag::err_typecheck_pointer_arith_function_type
10854                 : diag::ext_gnu_ptr_func_arith)
10855     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10856     << 0 /* one pointer, so only one type */
10857     << Pointer->getSourceRange();
10858 }
10859 
10860 /// Emit error if Operand is incomplete pointer type
10861 ///
10862 /// \returns True if pointer has incomplete type
10863 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10864                                                  Expr *Operand) {
10865   QualType ResType = Operand->getType();
10866   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10867     ResType = ResAtomicType->getValueType();
10868 
10869   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10870   QualType PointeeTy = ResType->getPointeeType();
10871   return S.RequireCompleteSizedType(
10872       Loc, PointeeTy,
10873       diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10874       Operand->getSourceRange());
10875 }
10876 
10877 /// Check the validity of an arithmetic pointer operand.
10878 ///
10879 /// If the operand has pointer type, this code will check for pointer types
10880 /// which are invalid in arithmetic operations. These will be diagnosed
10881 /// appropriately, including whether or not the use is supported as an
10882 /// extension.
10883 ///
10884 /// \returns True when the operand is valid to use (even if as an extension).
10885 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10886                                             Expr *Operand) {
10887   QualType ResType = Operand->getType();
10888   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10889     ResType = ResAtomicType->getValueType();
10890 
10891   if (!ResType->isAnyPointerType()) return true;
10892 
10893   QualType PointeeTy = ResType->getPointeeType();
10894   if (PointeeTy->isVoidType()) {
10895     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10896     return !S.getLangOpts().CPlusPlus;
10897   }
10898   if (PointeeTy->isFunctionType()) {
10899     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10900     return !S.getLangOpts().CPlusPlus;
10901   }
10902 
10903   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10904 
10905   return true;
10906 }
10907 
10908 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10909 /// operands.
10910 ///
10911 /// This routine will diagnose any invalid arithmetic on pointer operands much
10912 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10913 /// for emitting a single diagnostic even for operations where both LHS and RHS
10914 /// are (potentially problematic) pointers.
10915 ///
10916 /// \returns True when the operand is valid to use (even if as an extension).
10917 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10918                                                 Expr *LHSExpr, Expr *RHSExpr) {
10919   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10920   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10921   if (!isLHSPointer && !isRHSPointer) return true;
10922 
10923   QualType LHSPointeeTy, RHSPointeeTy;
10924   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10925   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10926 
10927   // if both are pointers check if operation is valid wrt address spaces
10928   if (isLHSPointer && isRHSPointer) {
10929     if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10930       S.Diag(Loc,
10931              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10932           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10933           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10934       return false;
10935     }
10936   }
10937 
10938   // Check for arithmetic on pointers to incomplete types.
10939   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10940   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10941   if (isLHSVoidPtr || isRHSVoidPtr) {
10942     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10943     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10944     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10945 
10946     return !S.getLangOpts().CPlusPlus;
10947   }
10948 
10949   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10950   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10951   if (isLHSFuncPtr || isRHSFuncPtr) {
10952     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10953     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10954                                                                 RHSExpr);
10955     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10956 
10957     return !S.getLangOpts().CPlusPlus;
10958   }
10959 
10960   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10961     return false;
10962   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10963     return false;
10964 
10965   return true;
10966 }
10967 
10968 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10969 /// literal.
10970 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10971                                   Expr *LHSExpr, Expr *RHSExpr) {
10972   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10973   Expr* IndexExpr = RHSExpr;
10974   if (!StrExpr) {
10975     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10976     IndexExpr = LHSExpr;
10977   }
10978 
10979   bool IsStringPlusInt = StrExpr &&
10980       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10981   if (!IsStringPlusInt || IndexExpr->isValueDependent())
10982     return;
10983 
10984   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10985   Self.Diag(OpLoc, diag::warn_string_plus_int)
10986       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10987 
10988   // Only print a fixit for "str" + int, not for int + "str".
10989   if (IndexExpr == RHSExpr) {
10990     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10991     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10992         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10993         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10994         << FixItHint::CreateInsertion(EndLoc, "]");
10995   } else
10996     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10997 }
10998 
10999 /// Emit a warning when adding a char literal to a string.
11000 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11001                                    Expr *LHSExpr, Expr *RHSExpr) {
11002   const Expr *StringRefExpr = LHSExpr;
11003   const CharacterLiteral *CharExpr =
11004       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11005 
11006   if (!CharExpr) {
11007     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11008     StringRefExpr = RHSExpr;
11009   }
11010 
11011   if (!CharExpr || !StringRefExpr)
11012     return;
11013 
11014   const QualType StringType = StringRefExpr->getType();
11015 
11016   // Return if not a PointerType.
11017   if (!StringType->isAnyPointerType())
11018     return;
11019 
11020   // Return if not a CharacterType.
11021   if (!StringType->getPointeeType()->isAnyCharacterType())
11022     return;
11023 
11024   ASTContext &Ctx = Self.getASTContext();
11025   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11026 
11027   const QualType CharType = CharExpr->getType();
11028   if (!CharType->isAnyCharacterType() &&
11029       CharType->isIntegerType() &&
11030       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11031     Self.Diag(OpLoc, diag::warn_string_plus_char)
11032         << DiagRange << Ctx.CharTy;
11033   } else {
11034     Self.Diag(OpLoc, diag::warn_string_plus_char)
11035         << DiagRange << CharExpr->getType();
11036   }
11037 
11038   // Only print a fixit for str + char, not for char + str.
11039   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11040     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11041     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11042         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11043         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
11044         << FixItHint::CreateInsertion(EndLoc, "]");
11045   } else {
11046     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11047   }
11048 }
11049 
11050 /// Emit error when two pointers are incompatible.
11051 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
11052                                            Expr *LHSExpr, Expr *RHSExpr) {
11053   assert(LHSExpr->getType()->isAnyPointerType());
11054   assert(RHSExpr->getType()->isAnyPointerType());
11055   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11056     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11057     << RHSExpr->getSourceRange();
11058 }
11059 
11060 // C99 6.5.6
11061 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11062                                      SourceLocation Loc, BinaryOperatorKind Opc,
11063                                      QualType* CompLHSTy) {
11064   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11065 
11066   if (LHS.get()->getType()->isVectorType() ||
11067       RHS.get()->getType()->isVectorType()) {
11068     QualType compType =
11069         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11070                             /*AllowBothBool*/ getLangOpts().AltiVec,
11071                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11072                             /*AllowBooleanOperation*/ false,
11073                             /*ReportInvalid*/ true);
11074     if (CompLHSTy) *CompLHSTy = compType;
11075     return compType;
11076   }
11077 
11078   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11079       RHS.get()->getType()->isVLSTBuiltinType()) {
11080     QualType compType =
11081         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11082     if (CompLHSTy)
11083       *CompLHSTy = compType;
11084     return compType;
11085   }
11086 
11087   if (LHS.get()->getType()->isConstantMatrixType() ||
11088       RHS.get()->getType()->isConstantMatrixType()) {
11089     QualType compType =
11090         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11091     if (CompLHSTy)
11092       *CompLHSTy = compType;
11093     return compType;
11094   }
11095 
11096   QualType compType = UsualArithmeticConversions(
11097       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11098   if (LHS.isInvalid() || RHS.isInvalid())
11099     return QualType();
11100 
11101   // Diagnose "string literal" '+' int and string '+' "char literal".
11102   if (Opc == BO_Add) {
11103     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11104     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11105   }
11106 
11107   // handle the common case first (both operands are arithmetic).
11108   if (!compType.isNull() && compType->isArithmeticType()) {
11109     if (CompLHSTy) *CompLHSTy = compType;
11110     return compType;
11111   }
11112 
11113   // Type-checking.  Ultimately the pointer's going to be in PExp;
11114   // note that we bias towards the LHS being the pointer.
11115   Expr *PExp = LHS.get(), *IExp = RHS.get();
11116 
11117   bool isObjCPointer;
11118   if (PExp->getType()->isPointerType()) {
11119     isObjCPointer = false;
11120   } else if (PExp->getType()->isObjCObjectPointerType()) {
11121     isObjCPointer = true;
11122   } else {
11123     std::swap(PExp, IExp);
11124     if (PExp->getType()->isPointerType()) {
11125       isObjCPointer = false;
11126     } else if (PExp->getType()->isObjCObjectPointerType()) {
11127       isObjCPointer = true;
11128     } else {
11129       return InvalidOperands(Loc, LHS, RHS);
11130     }
11131   }
11132   assert(PExp->getType()->isAnyPointerType());
11133 
11134   if (!IExp->getType()->isIntegerType())
11135     return InvalidOperands(Loc, LHS, RHS);
11136 
11137   // Adding to a null pointer results in undefined behavior.
11138   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11139           Context, Expr::NPC_ValueDependentIsNotNull)) {
11140     // In C++ adding zero to a null pointer is defined.
11141     Expr::EvalResult KnownVal;
11142     if (!getLangOpts().CPlusPlus ||
11143         (!IExp->isValueDependent() &&
11144          (!IExp->EvaluateAsInt(KnownVal, Context) ||
11145           KnownVal.Val.getInt() != 0))) {
11146       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11147       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11148           Context, BO_Add, PExp, IExp);
11149       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11150     }
11151   }
11152 
11153   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11154     return QualType();
11155 
11156   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11157     return QualType();
11158 
11159   // Check array bounds for pointer arithemtic
11160   CheckArrayAccess(PExp, IExp);
11161 
11162   if (CompLHSTy) {
11163     QualType LHSTy = Context.isPromotableBitField(LHS.get());
11164     if (LHSTy.isNull()) {
11165       LHSTy = LHS.get()->getType();
11166       if (LHSTy->isPromotableIntegerType())
11167         LHSTy = Context.getPromotedIntegerType(LHSTy);
11168     }
11169     *CompLHSTy = LHSTy;
11170   }
11171 
11172   return PExp->getType();
11173 }
11174 
11175 // C99 6.5.6
11176 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11177                                         SourceLocation Loc,
11178                                         QualType* CompLHSTy) {
11179   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11180 
11181   if (LHS.get()->getType()->isVectorType() ||
11182       RHS.get()->getType()->isVectorType()) {
11183     QualType compType =
11184         CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11185                             /*AllowBothBool*/ getLangOpts().AltiVec,
11186                             /*AllowBoolConversions*/ getLangOpts().ZVector,
11187                             /*AllowBooleanOperation*/ false,
11188                             /*ReportInvalid*/ true);
11189     if (CompLHSTy) *CompLHSTy = compType;
11190     return compType;
11191   }
11192 
11193   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11194       RHS.get()->getType()->isVLSTBuiltinType()) {
11195     QualType compType =
11196         CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11197     if (CompLHSTy)
11198       *CompLHSTy = compType;
11199     return compType;
11200   }
11201 
11202   if (LHS.get()->getType()->isConstantMatrixType() ||
11203       RHS.get()->getType()->isConstantMatrixType()) {
11204     QualType compType =
11205         CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11206     if (CompLHSTy)
11207       *CompLHSTy = compType;
11208     return compType;
11209   }
11210 
11211   QualType compType = UsualArithmeticConversions(
11212       LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11213   if (LHS.isInvalid() || RHS.isInvalid())
11214     return QualType();
11215 
11216   // Enforce type constraints: C99 6.5.6p3.
11217 
11218   // Handle the common case first (both operands are arithmetic).
11219   if (!compType.isNull() && compType->isArithmeticType()) {
11220     if (CompLHSTy) *CompLHSTy = compType;
11221     return compType;
11222   }
11223 
11224   // Either ptr - int   or   ptr - ptr.
11225   if (LHS.get()->getType()->isAnyPointerType()) {
11226     QualType lpointee = LHS.get()->getType()->getPointeeType();
11227 
11228     // Diagnose bad cases where we step over interface counts.
11229     if (LHS.get()->getType()->isObjCObjectPointerType() &&
11230         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11231       return QualType();
11232 
11233     // The result type of a pointer-int computation is the pointer type.
11234     if (RHS.get()->getType()->isIntegerType()) {
11235       // Subtracting from a null pointer should produce a warning.
11236       // The last argument to the diagnose call says this doesn't match the
11237       // GNU int-to-pointer idiom.
11238       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
11239                                            Expr::NPC_ValueDependentIsNotNull)) {
11240         // In C++ adding zero to a null pointer is defined.
11241         Expr::EvalResult KnownVal;
11242         if (!getLangOpts().CPlusPlus ||
11243             (!RHS.get()->isValueDependent() &&
11244              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11245               KnownVal.Val.getInt() != 0))) {
11246           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11247         }
11248       }
11249 
11250       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11251         return QualType();
11252 
11253       // Check array bounds for pointer arithemtic
11254       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11255                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11256 
11257       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11258       return LHS.get()->getType();
11259     }
11260 
11261     // Handle pointer-pointer subtractions.
11262     if (const PointerType *RHSPTy
11263           = RHS.get()->getType()->getAs<PointerType>()) {
11264       QualType rpointee = RHSPTy->getPointeeType();
11265 
11266       if (getLangOpts().CPlusPlus) {
11267         // Pointee types must be the same: C++ [expr.add]
11268         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11269           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11270         }
11271       } else {
11272         // Pointee types must be compatible C99 6.5.6p3
11273         if (!Context.typesAreCompatible(
11274                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11275                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11276           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11277           return QualType();
11278         }
11279       }
11280 
11281       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
11282                                                LHS.get(), RHS.get()))
11283         return QualType();
11284 
11285       bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11286           Context, Expr::NPC_ValueDependentIsNotNull);
11287       bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11288           Context, Expr::NPC_ValueDependentIsNotNull);
11289 
11290       // Subtracting nullptr or from nullptr is suspect
11291       if (LHSIsNullPtr)
11292         diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11293       if (RHSIsNullPtr)
11294         diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11295 
11296       // The pointee type may have zero size.  As an extension, a structure or
11297       // union may have zero size or an array may have zero length.  In this
11298       // case subtraction does not make sense.
11299       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11300         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11301         if (ElementSize.isZero()) {
11302           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11303             << rpointee.getUnqualifiedType()
11304             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11305         }
11306       }
11307 
11308       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11309       return Context.getPointerDiffType();
11310     }
11311   }
11312 
11313   return InvalidOperands(Loc, LHS, RHS);
11314 }
11315 
11316 static bool isScopedEnumerationType(QualType T) {
11317   if (const EnumType *ET = T->getAs<EnumType>())
11318     return ET->getDecl()->isScoped();
11319   return false;
11320 }
11321 
11322 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11323                                    SourceLocation Loc, BinaryOperatorKind Opc,
11324                                    QualType LHSType) {
11325   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11326   // so skip remaining warnings as we don't want to modify values within Sema.
11327   if (S.getLangOpts().OpenCL)
11328     return;
11329 
11330   // Check right/shifter operand
11331   Expr::EvalResult RHSResult;
11332   if (RHS.get()->isValueDependent() ||
11333       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11334     return;
11335   llvm::APSInt Right = RHSResult.Val.getInt();
11336 
11337   if (Right.isNegative()) {
11338     S.DiagRuntimeBehavior(Loc, RHS.get(),
11339                           S.PDiag(diag::warn_shift_negative)
11340                             << RHS.get()->getSourceRange());
11341     return;
11342   }
11343 
11344   QualType LHSExprType = LHS.get()->getType();
11345   uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11346   if (LHSExprType->isBitIntType())
11347     LeftSize = S.Context.getIntWidth(LHSExprType);
11348   else if (LHSExprType->isFixedPointType()) {
11349     auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11350     LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11351   }
11352   llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
11353   if (Right.uge(LeftBits)) {
11354     S.DiagRuntimeBehavior(Loc, RHS.get(),
11355                           S.PDiag(diag::warn_shift_gt_typewidth)
11356                             << RHS.get()->getSourceRange());
11357     return;
11358   }
11359 
11360   // FIXME: We probably need to handle fixed point types specially here.
11361   if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11362     return;
11363 
11364   // When left shifting an ICE which is signed, we can check for overflow which
11365   // according to C++ standards prior to C++2a has undefined behavior
11366   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11367   // more than the maximum value representable in the result type, so never
11368   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11369   // expression is still probably a bug.)
11370   Expr::EvalResult LHSResult;
11371   if (LHS.get()->isValueDependent() ||
11372       LHSType->hasUnsignedIntegerRepresentation() ||
11373       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11374     return;
11375   llvm::APSInt Left = LHSResult.Val.getInt();
11376 
11377   // If LHS does not have a signed type and non-negative value
11378   // then, the behavior is undefined before C++2a. Warn about it.
11379   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
11380       !S.getLangOpts().CPlusPlus20) {
11381     S.DiagRuntimeBehavior(Loc, LHS.get(),
11382                           S.PDiag(diag::warn_shift_lhs_negative)
11383                             << LHS.get()->getSourceRange());
11384     return;
11385   }
11386 
11387   llvm::APInt ResultBits =
11388       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
11389   if (LeftBits.uge(ResultBits))
11390     return;
11391   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11392   Result = Result.shl(Right);
11393 
11394   // Print the bit representation of the signed integer as an unsigned
11395   // hexadecimal number.
11396   SmallString<40> HexResult;
11397   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11398 
11399   // If we are only missing a sign bit, this is less likely to result in actual
11400   // bugs -- if the result is cast back to an unsigned type, it will have the
11401   // expected value. Thus we place this behind a different warning that can be
11402   // turned off separately if needed.
11403   if (LeftBits == ResultBits - 1) {
11404     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11405         << HexResult << LHSType
11406         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11407     return;
11408   }
11409 
11410   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11411     << HexResult.str() << Result.getMinSignedBits() << LHSType
11412     << Left.getBitWidth() << LHS.get()->getSourceRange()
11413     << RHS.get()->getSourceRange();
11414 }
11415 
11416 /// Return the resulting type when a vector is shifted
11417 ///        by a scalar or vector shift amount.
11418 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
11419                                  SourceLocation Loc, bool IsCompAssign) {
11420   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11421   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11422       !LHS.get()->getType()->isVectorType()) {
11423     S.Diag(Loc, diag::err_shift_rhs_only_vector)
11424       << RHS.get()->getType() << LHS.get()->getType()
11425       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11426     return QualType();
11427   }
11428 
11429   if (!IsCompAssign) {
11430     LHS = S.UsualUnaryConversions(LHS.get());
11431     if (LHS.isInvalid()) return QualType();
11432   }
11433 
11434   RHS = S.UsualUnaryConversions(RHS.get());
11435   if (RHS.isInvalid()) return QualType();
11436 
11437   QualType LHSType = LHS.get()->getType();
11438   // Note that LHS might be a scalar because the routine calls not only in
11439   // OpenCL case.
11440   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11441   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11442 
11443   // Note that RHS might not be a vector.
11444   QualType RHSType = RHS.get()->getType();
11445   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11446   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11447 
11448   // Do not allow shifts for boolean vectors.
11449   if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11450       (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11451     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11452         << LHS.get()->getType() << RHS.get()->getType()
11453         << LHS.get()->getSourceRange();
11454     return QualType();
11455   }
11456 
11457   // The operands need to be integers.
11458   if (!LHSEleType->isIntegerType()) {
11459     S.Diag(Loc, diag::err_typecheck_expect_int)
11460       << LHS.get()->getType() << LHS.get()->getSourceRange();
11461     return QualType();
11462   }
11463 
11464   if (!RHSEleType->isIntegerType()) {
11465     S.Diag(Loc, diag::err_typecheck_expect_int)
11466       << RHS.get()->getType() << RHS.get()->getSourceRange();
11467     return QualType();
11468   }
11469 
11470   if (!LHSVecTy) {
11471     assert(RHSVecTy);
11472     if (IsCompAssign)
11473       return RHSType;
11474     if (LHSEleType != RHSEleType) {
11475       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11476       LHSEleType = RHSEleType;
11477     }
11478     QualType VecTy =
11479         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11480     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11481     LHSType = VecTy;
11482   } else if (RHSVecTy) {
11483     // OpenCL v1.1 s6.3.j says that for vector types, the operators
11484     // are applied component-wise. So if RHS is a vector, then ensure
11485     // that the number of elements is the same as LHS...
11486     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11487       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11488         << LHS.get()->getType() << RHS.get()->getType()
11489         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11490       return QualType();
11491     }
11492     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11493       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11494       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11495       if (LHSBT != RHSBT &&
11496           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11497         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11498             << LHS.get()->getType() << RHS.get()->getType()
11499             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11500       }
11501     }
11502   } else {
11503     // ...else expand RHS to match the number of elements in LHS.
11504     QualType VecTy =
11505       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11506     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11507   }
11508 
11509   return LHSType;
11510 }
11511 
11512 static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11513                                          ExprResult &RHS, SourceLocation Loc,
11514                                          bool IsCompAssign) {
11515   if (!IsCompAssign) {
11516     LHS = S.UsualUnaryConversions(LHS.get());
11517     if (LHS.isInvalid())
11518       return QualType();
11519   }
11520 
11521   RHS = S.UsualUnaryConversions(RHS.get());
11522   if (RHS.isInvalid())
11523     return QualType();
11524 
11525   QualType LHSType = LHS.get()->getType();
11526   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11527   QualType LHSEleType = LHSType->isVLSTBuiltinType()
11528                             ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11529                             : LHSType;
11530 
11531   // Note that RHS might not be a vector
11532   QualType RHSType = RHS.get()->getType();
11533   const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11534   QualType RHSEleType = RHSType->isVLSTBuiltinType()
11535                             ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11536                             : RHSType;
11537 
11538   if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11539       (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11540     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11541         << LHSType << RHSType << LHS.get()->getSourceRange();
11542     return QualType();
11543   }
11544 
11545   if (!LHSEleType->isIntegerType()) {
11546     S.Diag(Loc, diag::err_typecheck_expect_int)
11547         << LHS.get()->getType() << LHS.get()->getSourceRange();
11548     return QualType();
11549   }
11550 
11551   if (!RHSEleType->isIntegerType()) {
11552     S.Diag(Loc, diag::err_typecheck_expect_int)
11553         << RHS.get()->getType() << RHS.get()->getSourceRange();
11554     return QualType();
11555   }
11556 
11557   if (LHSType->isVLSTBuiltinType() && RHSType->isVLSTBuiltinType() &&
11558       (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11559        S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11560     S.Diag(Loc, diag::err_typecheck_invalid_operands)
11561         << LHSType << RHSType << LHS.get()->getSourceRange()
11562         << RHS.get()->getSourceRange();
11563     return QualType();
11564   }
11565 
11566   if (!LHSType->isVLSTBuiltinType()) {
11567     assert(RHSType->isVLSTBuiltinType());
11568     if (IsCompAssign)
11569       return RHSType;
11570     if (LHSEleType != RHSEleType) {
11571       LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11572       LHSEleType = RHSEleType;
11573     }
11574     const llvm::ElementCount VecSize =
11575         S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11576     QualType VecTy =
11577         S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11578     LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11579     LHSType = VecTy;
11580   } else if (RHSBuiltinTy && RHSBuiltinTy->isVLSTBuiltinType()) {
11581     if (S.Context.getTypeSize(RHSBuiltinTy) !=
11582         S.Context.getTypeSize(LHSBuiltinTy)) {
11583       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11584           << LHSType << RHSType << LHS.get()->getSourceRange()
11585           << RHS.get()->getSourceRange();
11586       return QualType();
11587     }
11588   } else {
11589     const llvm::ElementCount VecSize =
11590         S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11591     if (LHSEleType != RHSEleType) {
11592       RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11593       RHSEleType = LHSEleType;
11594     }
11595     QualType VecTy =
11596         S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11597     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11598   }
11599 
11600   return LHSType;
11601 }
11602 
11603 // C99 6.5.7
11604 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11605                                   SourceLocation Loc, BinaryOperatorKind Opc,
11606                                   bool IsCompAssign) {
11607   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11608 
11609   // Vector shifts promote their scalar inputs to vector type.
11610   if (LHS.get()->getType()->isVectorType() ||
11611       RHS.get()->getType()->isVectorType()) {
11612     if (LangOpts.ZVector) {
11613       // The shift operators for the z vector extensions work basically
11614       // like general shifts, except that neither the LHS nor the RHS is
11615       // allowed to be a "vector bool".
11616       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11617         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11618           return InvalidOperands(Loc, LHS, RHS);
11619       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11620         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11621           return InvalidOperands(Loc, LHS, RHS);
11622     }
11623     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11624   }
11625 
11626   if (LHS.get()->getType()->isVLSTBuiltinType() ||
11627       RHS.get()->getType()->isVLSTBuiltinType())
11628     return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11629 
11630   // Shifts don't perform usual arithmetic conversions, they just do integer
11631   // promotions on each operand. C99 6.5.7p3
11632 
11633   // For the LHS, do usual unary conversions, but then reset them away
11634   // if this is a compound assignment.
11635   ExprResult OldLHS = LHS;
11636   LHS = UsualUnaryConversions(LHS.get());
11637   if (LHS.isInvalid())
11638     return QualType();
11639   QualType LHSType = LHS.get()->getType();
11640   if (IsCompAssign) LHS = OldLHS;
11641 
11642   // The RHS is simpler.
11643   RHS = UsualUnaryConversions(RHS.get());
11644   if (RHS.isInvalid())
11645     return QualType();
11646   QualType RHSType = RHS.get()->getType();
11647 
11648   // C99 6.5.7p2: Each of the operands shall have integer type.
11649   // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11650   if ((!LHSType->isFixedPointOrIntegerType() &&
11651        !LHSType->hasIntegerRepresentation()) ||
11652       !RHSType->hasIntegerRepresentation())
11653     return InvalidOperands(Loc, LHS, RHS);
11654 
11655   // C++0x: Don't allow scoped enums. FIXME: Use something better than
11656   // hasIntegerRepresentation() above instead of this.
11657   if (isScopedEnumerationType(LHSType) ||
11658       isScopedEnumerationType(RHSType)) {
11659     return InvalidOperands(Loc, LHS, RHS);
11660   }
11661   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11662 
11663   // "The type of the result is that of the promoted left operand."
11664   return LHSType;
11665 }
11666 
11667 /// Diagnose bad pointer comparisons.
11668 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11669                                               ExprResult &LHS, ExprResult &RHS,
11670                                               bool IsError) {
11671   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11672                       : diag::ext_typecheck_comparison_of_distinct_pointers)
11673     << LHS.get()->getType() << RHS.get()->getType()
11674     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11675 }
11676 
11677 /// Returns false if the pointers are converted to a composite type,
11678 /// true otherwise.
11679 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11680                                            ExprResult &LHS, ExprResult &RHS) {
11681   // C++ [expr.rel]p2:
11682   //   [...] Pointer conversions (4.10) and qualification
11683   //   conversions (4.4) are performed on pointer operands (or on
11684   //   a pointer operand and a null pointer constant) to bring
11685   //   them to their composite pointer type. [...]
11686   //
11687   // C++ [expr.eq]p1 uses the same notion for (in)equality
11688   // comparisons of pointers.
11689 
11690   QualType LHSType = LHS.get()->getType();
11691   QualType RHSType = RHS.get()->getType();
11692   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11693          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11694 
11695   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11696   if (T.isNull()) {
11697     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11698         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11699       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11700     else
11701       S.InvalidOperands(Loc, LHS, RHS);
11702     return true;
11703   }
11704 
11705   return false;
11706 }
11707 
11708 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11709                                                     ExprResult &LHS,
11710                                                     ExprResult &RHS,
11711                                                     bool IsError) {
11712   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11713                       : diag::ext_typecheck_comparison_of_fptr_to_void)
11714     << LHS.get()->getType() << RHS.get()->getType()
11715     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11716 }
11717 
11718 static bool isObjCObjectLiteral(ExprResult &E) {
11719   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11720   case Stmt::ObjCArrayLiteralClass:
11721   case Stmt::ObjCDictionaryLiteralClass:
11722   case Stmt::ObjCStringLiteralClass:
11723   case Stmt::ObjCBoxedExprClass:
11724     return true;
11725   default:
11726     // Note that ObjCBoolLiteral is NOT an object literal!
11727     return false;
11728   }
11729 }
11730 
11731 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11732   const ObjCObjectPointerType *Type =
11733     LHS->getType()->getAs<ObjCObjectPointerType>();
11734 
11735   // If this is not actually an Objective-C object, bail out.
11736   if (!Type)
11737     return false;
11738 
11739   // Get the LHS object's interface type.
11740   QualType InterfaceType = Type->getPointeeType();
11741 
11742   // If the RHS isn't an Objective-C object, bail out.
11743   if (!RHS->getType()->isObjCObjectPointerType())
11744     return false;
11745 
11746   // Try to find the -isEqual: method.
11747   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11748   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11749                                                       InterfaceType,
11750                                                       /*IsInstance=*/true);
11751   if (!Method) {
11752     if (Type->isObjCIdType()) {
11753       // For 'id', just check the global pool.
11754       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11755                                                   /*receiverId=*/true);
11756     } else {
11757       // Check protocols.
11758       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11759                                              /*IsInstance=*/true);
11760     }
11761   }
11762 
11763   if (!Method)
11764     return false;
11765 
11766   QualType T = Method->parameters()[0]->getType();
11767   if (!T->isObjCObjectPointerType())
11768     return false;
11769 
11770   QualType R = Method->getReturnType();
11771   if (!R->isScalarType())
11772     return false;
11773 
11774   return true;
11775 }
11776 
11777 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11778   FromE = FromE->IgnoreParenImpCasts();
11779   switch (FromE->getStmtClass()) {
11780     default:
11781       break;
11782     case Stmt::ObjCStringLiteralClass:
11783       // "string literal"
11784       return LK_String;
11785     case Stmt::ObjCArrayLiteralClass:
11786       // "array literal"
11787       return LK_Array;
11788     case Stmt::ObjCDictionaryLiteralClass:
11789       // "dictionary literal"
11790       return LK_Dictionary;
11791     case Stmt::BlockExprClass:
11792       return LK_Block;
11793     case Stmt::ObjCBoxedExprClass: {
11794       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11795       switch (Inner->getStmtClass()) {
11796         case Stmt::IntegerLiteralClass:
11797         case Stmt::FloatingLiteralClass:
11798         case Stmt::CharacterLiteralClass:
11799         case Stmt::ObjCBoolLiteralExprClass:
11800         case Stmt::CXXBoolLiteralExprClass:
11801           // "numeric literal"
11802           return LK_Numeric;
11803         case Stmt::ImplicitCastExprClass: {
11804           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11805           // Boolean literals can be represented by implicit casts.
11806           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11807             return LK_Numeric;
11808           break;
11809         }
11810         default:
11811           break;
11812       }
11813       return LK_Boxed;
11814     }
11815   }
11816   return LK_None;
11817 }
11818 
11819 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11820                                           ExprResult &LHS, ExprResult &RHS,
11821                                           BinaryOperator::Opcode Opc){
11822   Expr *Literal;
11823   Expr *Other;
11824   if (isObjCObjectLiteral(LHS)) {
11825     Literal = LHS.get();
11826     Other = RHS.get();
11827   } else {
11828     Literal = RHS.get();
11829     Other = LHS.get();
11830   }
11831 
11832   // Don't warn on comparisons against nil.
11833   Other = Other->IgnoreParenCasts();
11834   if (Other->isNullPointerConstant(S.getASTContext(),
11835                                    Expr::NPC_ValueDependentIsNotNull))
11836     return;
11837 
11838   // This should be kept in sync with warn_objc_literal_comparison.
11839   // LK_String should always be after the other literals, since it has its own
11840   // warning flag.
11841   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11842   assert(LiteralKind != Sema::LK_Block);
11843   if (LiteralKind == Sema::LK_None) {
11844     llvm_unreachable("Unknown Objective-C object literal kind");
11845   }
11846 
11847   if (LiteralKind == Sema::LK_String)
11848     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11849       << Literal->getSourceRange();
11850   else
11851     S.Diag(Loc, diag::warn_objc_literal_comparison)
11852       << LiteralKind << Literal->getSourceRange();
11853 
11854   if (BinaryOperator::isEqualityOp(Opc) &&
11855       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11856     SourceLocation Start = LHS.get()->getBeginLoc();
11857     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11858     CharSourceRange OpRange =
11859       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11860 
11861     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11862       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11863       << FixItHint::CreateReplacement(OpRange, " isEqual:")
11864       << FixItHint::CreateInsertion(End, "]");
11865   }
11866 }
11867 
11868 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11869 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11870                                            ExprResult &RHS, SourceLocation Loc,
11871                                            BinaryOperatorKind Opc) {
11872   // Check that left hand side is !something.
11873   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11874   if (!UO || UO->getOpcode() != UO_LNot) return;
11875 
11876   // Only check if the right hand side is non-bool arithmetic type.
11877   if (RHS.get()->isKnownToHaveBooleanValue()) return;
11878 
11879   // Make sure that the something in !something is not bool.
11880   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11881   if (SubExpr->isKnownToHaveBooleanValue()) return;
11882 
11883   // Emit warning.
11884   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11885   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11886       << Loc << IsBitwiseOp;
11887 
11888   // First note suggest !(x < y)
11889   SourceLocation FirstOpen = SubExpr->getBeginLoc();
11890   SourceLocation FirstClose = RHS.get()->getEndLoc();
11891   FirstClose = S.getLocForEndOfToken(FirstClose);
11892   if (FirstClose.isInvalid())
11893     FirstOpen = SourceLocation();
11894   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11895       << IsBitwiseOp
11896       << FixItHint::CreateInsertion(FirstOpen, "(")
11897       << FixItHint::CreateInsertion(FirstClose, ")");
11898 
11899   // Second note suggests (!x) < y
11900   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11901   SourceLocation SecondClose = LHS.get()->getEndLoc();
11902   SecondClose = S.getLocForEndOfToken(SecondClose);
11903   if (SecondClose.isInvalid())
11904     SecondOpen = SourceLocation();
11905   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11906       << FixItHint::CreateInsertion(SecondOpen, "(")
11907       << FixItHint::CreateInsertion(SecondClose, ")");
11908 }
11909 
11910 // Returns true if E refers to a non-weak array.
11911 static bool checkForArray(const Expr *E) {
11912   const ValueDecl *D = nullptr;
11913   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11914     D = DR->getDecl();
11915   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11916     if (Mem->isImplicitAccess())
11917       D = Mem->getMemberDecl();
11918   }
11919   if (!D)
11920     return false;
11921   return D->getType()->isArrayType() && !D->isWeak();
11922 }
11923 
11924 /// Diagnose some forms of syntactically-obvious tautological comparison.
11925 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11926                                            Expr *LHS, Expr *RHS,
11927                                            BinaryOperatorKind Opc) {
11928   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11929   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11930 
11931   QualType LHSType = LHS->getType();
11932   QualType RHSType = RHS->getType();
11933   if (LHSType->hasFloatingRepresentation() ||
11934       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11935       S.inTemplateInstantiation())
11936     return;
11937 
11938   // Comparisons between two array types are ill-formed for operator<=>, so
11939   // we shouldn't emit any additional warnings about it.
11940   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11941     return;
11942 
11943   // For non-floating point types, check for self-comparisons of the form
11944   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11945   // often indicate logic errors in the program.
11946   //
11947   // NOTE: Don't warn about comparison expressions resulting from macro
11948   // expansion. Also don't warn about comparisons which are only self
11949   // comparisons within a template instantiation. The warnings should catch
11950   // obvious cases in the definition of the template anyways. The idea is to
11951   // warn when the typed comparison operator will always evaluate to the same
11952   // result.
11953 
11954   // Used for indexing into %select in warn_comparison_always
11955   enum {
11956     AlwaysConstant,
11957     AlwaysTrue,
11958     AlwaysFalse,
11959     AlwaysEqual, // std::strong_ordering::equal from operator<=>
11960   };
11961 
11962   // C++2a [depr.array.comp]:
11963   //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11964   //   operands of array type are deprecated.
11965   if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11966       RHSStripped->getType()->isArrayType()) {
11967     S.Diag(Loc, diag::warn_depr_array_comparison)
11968         << LHS->getSourceRange() << RHS->getSourceRange()
11969         << LHSStripped->getType() << RHSStripped->getType();
11970     // Carry on to produce the tautological comparison warning, if this
11971     // expression is potentially-evaluated, we can resolve the array to a
11972     // non-weak declaration, and so on.
11973   }
11974 
11975   if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11976     if (Expr::isSameComparisonOperand(LHS, RHS)) {
11977       unsigned Result;
11978       switch (Opc) {
11979       case BO_EQ:
11980       case BO_LE:
11981       case BO_GE:
11982         Result = AlwaysTrue;
11983         break;
11984       case BO_NE:
11985       case BO_LT:
11986       case BO_GT:
11987         Result = AlwaysFalse;
11988         break;
11989       case BO_Cmp:
11990         Result = AlwaysEqual;
11991         break;
11992       default:
11993         Result = AlwaysConstant;
11994         break;
11995       }
11996       S.DiagRuntimeBehavior(Loc, nullptr,
11997                             S.PDiag(diag::warn_comparison_always)
11998                                 << 0 /*self-comparison*/
11999                                 << Result);
12000     } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12001       // What is it always going to evaluate to?
12002       unsigned Result;
12003       switch (Opc) {
12004       case BO_EQ: // e.g. array1 == array2
12005         Result = AlwaysFalse;
12006         break;
12007       case BO_NE: // e.g. array1 != array2
12008         Result = AlwaysTrue;
12009         break;
12010       default: // e.g. array1 <= array2
12011         // The best we can say is 'a constant'
12012         Result = AlwaysConstant;
12013         break;
12014       }
12015       S.DiagRuntimeBehavior(Loc, nullptr,
12016                             S.PDiag(diag::warn_comparison_always)
12017                                 << 1 /*array comparison*/
12018                                 << Result);
12019     }
12020   }
12021 
12022   if (isa<CastExpr>(LHSStripped))
12023     LHSStripped = LHSStripped->IgnoreParenCasts();
12024   if (isa<CastExpr>(RHSStripped))
12025     RHSStripped = RHSStripped->IgnoreParenCasts();
12026 
12027   // Warn about comparisons against a string constant (unless the other
12028   // operand is null); the user probably wants string comparison function.
12029   Expr *LiteralString = nullptr;
12030   Expr *LiteralStringStripped = nullptr;
12031   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12032       !RHSStripped->isNullPointerConstant(S.Context,
12033                                           Expr::NPC_ValueDependentIsNull)) {
12034     LiteralString = LHS;
12035     LiteralStringStripped = LHSStripped;
12036   } else if ((isa<StringLiteral>(RHSStripped) ||
12037               isa<ObjCEncodeExpr>(RHSStripped)) &&
12038              !LHSStripped->isNullPointerConstant(S.Context,
12039                                           Expr::NPC_ValueDependentIsNull)) {
12040     LiteralString = RHS;
12041     LiteralStringStripped = RHSStripped;
12042   }
12043 
12044   if (LiteralString) {
12045     S.DiagRuntimeBehavior(Loc, nullptr,
12046                           S.PDiag(diag::warn_stringcompare)
12047                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
12048                               << LiteralString->getSourceRange());
12049   }
12050 }
12051 
12052 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
12053   switch (CK) {
12054   default: {
12055 #ifndef NDEBUG
12056     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12057                  << "\n";
12058 #endif
12059     llvm_unreachable("unhandled cast kind");
12060   }
12061   case CK_UserDefinedConversion:
12062     return ICK_Identity;
12063   case CK_LValueToRValue:
12064     return ICK_Lvalue_To_Rvalue;
12065   case CK_ArrayToPointerDecay:
12066     return ICK_Array_To_Pointer;
12067   case CK_FunctionToPointerDecay:
12068     return ICK_Function_To_Pointer;
12069   case CK_IntegralCast:
12070     return ICK_Integral_Conversion;
12071   case CK_FloatingCast:
12072     return ICK_Floating_Conversion;
12073   case CK_IntegralToFloating:
12074   case CK_FloatingToIntegral:
12075     return ICK_Floating_Integral;
12076   case CK_IntegralComplexCast:
12077   case CK_FloatingComplexCast:
12078   case CK_FloatingComplexToIntegralComplex:
12079   case CK_IntegralComplexToFloatingComplex:
12080     return ICK_Complex_Conversion;
12081   case CK_FloatingComplexToReal:
12082   case CK_FloatingRealToComplex:
12083   case CK_IntegralComplexToReal:
12084   case CK_IntegralRealToComplex:
12085     return ICK_Complex_Real;
12086   }
12087 }
12088 
12089 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12090                                              QualType FromType,
12091                                              SourceLocation Loc) {
12092   // Check for a narrowing implicit conversion.
12093   StandardConversionSequence SCS;
12094   SCS.setAsIdentityConversion();
12095   SCS.setToType(0, FromType);
12096   SCS.setToType(1, ToType);
12097   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12098     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12099 
12100   APValue PreNarrowingValue;
12101   QualType PreNarrowingType;
12102   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12103                                PreNarrowingType,
12104                                /*IgnoreFloatToIntegralConversion*/ true)) {
12105   case NK_Dependent_Narrowing:
12106     // Implicit conversion to a narrower type, but the expression is
12107     // value-dependent so we can't tell whether it's actually narrowing.
12108   case NK_Not_Narrowing:
12109     return false;
12110 
12111   case NK_Constant_Narrowing:
12112     // Implicit conversion to a narrower type, and the value is not a constant
12113     // expression.
12114     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12115         << /*Constant*/ 1
12116         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12117     return true;
12118 
12119   case NK_Variable_Narrowing:
12120     // Implicit conversion to a narrower type, and the value is not a constant
12121     // expression.
12122   case NK_Type_Narrowing:
12123     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12124         << /*Constant*/ 0 << FromType << ToType;
12125     // TODO: It's not a constant expression, but what if the user intended it
12126     // to be? Can we produce notes to help them figure out why it isn't?
12127     return true;
12128   }
12129   llvm_unreachable("unhandled case in switch");
12130 }
12131 
12132 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
12133                                                          ExprResult &LHS,
12134                                                          ExprResult &RHS,
12135                                                          SourceLocation Loc) {
12136   QualType LHSType = LHS.get()->getType();
12137   QualType RHSType = RHS.get()->getType();
12138   // Dig out the original argument type and expression before implicit casts
12139   // were applied. These are the types/expressions we need to check the
12140   // [expr.spaceship] requirements against.
12141   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12142   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12143   QualType LHSStrippedType = LHSStripped.get()->getType();
12144   QualType RHSStrippedType = RHSStripped.get()->getType();
12145 
12146   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12147   // other is not, the program is ill-formed.
12148   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12149     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12150     return QualType();
12151   }
12152 
12153   // FIXME: Consider combining this with checkEnumArithmeticConversions.
12154   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12155                     RHSStrippedType->isEnumeralType();
12156   if (NumEnumArgs == 1) {
12157     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12158     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12159     if (OtherTy->hasFloatingRepresentation()) {
12160       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12161       return QualType();
12162     }
12163   }
12164   if (NumEnumArgs == 2) {
12165     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12166     // type E, the operator yields the result of converting the operands
12167     // to the underlying type of E and applying <=> to the converted operands.
12168     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12169       S.InvalidOperands(Loc, LHS, RHS);
12170       return QualType();
12171     }
12172     QualType IntType =
12173         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12174     assert(IntType->isArithmeticType());
12175 
12176     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12177     // promote the boolean type, and all other promotable integer types, to
12178     // avoid this.
12179     if (IntType->isPromotableIntegerType())
12180       IntType = S.Context.getPromotedIntegerType(IntType);
12181 
12182     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12183     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12184     LHSType = RHSType = IntType;
12185   }
12186 
12187   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12188   // usual arithmetic conversions are applied to the operands.
12189   QualType Type =
12190       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12191   if (LHS.isInvalid() || RHS.isInvalid())
12192     return QualType();
12193   if (Type.isNull())
12194     return S.InvalidOperands(Loc, LHS, RHS);
12195 
12196   Optional<ComparisonCategoryType> CCT =
12197       getComparisonCategoryForBuiltinCmp(Type);
12198   if (!CCT)
12199     return S.InvalidOperands(Loc, LHS, RHS);
12200 
12201   bool HasNarrowing = checkThreeWayNarrowingConversion(
12202       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12203   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12204                                                    RHS.get()->getBeginLoc());
12205   if (HasNarrowing)
12206     return QualType();
12207 
12208   assert(!Type.isNull() && "composite type for <=> has not been set");
12209 
12210   return S.CheckComparisonCategoryType(
12211       *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
12212 }
12213 
12214 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
12215                                                  ExprResult &RHS,
12216                                                  SourceLocation Loc,
12217                                                  BinaryOperatorKind Opc) {
12218   if (Opc == BO_Cmp)
12219     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12220 
12221   // C99 6.5.8p3 / C99 6.5.9p4
12222   QualType Type =
12223       S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
12224   if (LHS.isInvalid() || RHS.isInvalid())
12225     return QualType();
12226   if (Type.isNull())
12227     return S.InvalidOperands(Loc, LHS, RHS);
12228   assert(Type->isArithmeticType() || Type->isEnumeralType());
12229 
12230   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12231     return S.InvalidOperands(Loc, LHS, RHS);
12232 
12233   // Check for comparisons of floating point operands using != and ==.
12234   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
12235     S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12236 
12237   // The result of comparisons is 'bool' in C++, 'int' in C.
12238   return S.Context.getLogicalOperationType();
12239 }
12240 
12241 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12242   if (!NullE.get()->getType()->isAnyPointerType())
12243     return;
12244   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12245   if (!E.get()->getType()->isAnyPointerType() &&
12246       E.get()->isNullPointerConstant(Context,
12247                                      Expr::NPC_ValueDependentIsNotNull) ==
12248         Expr::NPCK_ZeroExpression) {
12249     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12250       if (CL->getValue() == 0)
12251         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12252             << NullValue
12253             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12254                                             NullValue ? "NULL" : "(void *)0");
12255     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12256         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12257         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12258         if (T == Context.CharTy)
12259           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12260               << NullValue
12261               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12262                                               NullValue ? "NULL" : "(void *)0");
12263       }
12264   }
12265 }
12266 
12267 // C99 6.5.8, C++ [expr.rel]
12268 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
12269                                     SourceLocation Loc,
12270                                     BinaryOperatorKind Opc) {
12271   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12272   bool IsThreeWay = Opc == BO_Cmp;
12273   bool IsOrdered = IsRelational || IsThreeWay;
12274   auto IsAnyPointerType = [](ExprResult E) {
12275     QualType Ty = E.get()->getType();
12276     return Ty->isPointerType() || Ty->isMemberPointerType();
12277   };
12278 
12279   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12280   // type, array-to-pointer, ..., conversions are performed on both operands to
12281   // bring them to their composite type.
12282   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12283   // any type-related checks.
12284   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12285     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12286     if (LHS.isInvalid())
12287       return QualType();
12288     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12289     if (RHS.isInvalid())
12290       return QualType();
12291   } else {
12292     LHS = DefaultLvalueConversion(LHS.get());
12293     if (LHS.isInvalid())
12294       return QualType();
12295     RHS = DefaultLvalueConversion(RHS.get());
12296     if (RHS.isInvalid())
12297       return QualType();
12298   }
12299 
12300   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12301   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12302     CheckPtrComparisonWithNullChar(LHS, RHS);
12303     CheckPtrComparisonWithNullChar(RHS, LHS);
12304   }
12305 
12306   // Handle vector comparisons separately.
12307   if (LHS.get()->getType()->isVectorType() ||
12308       RHS.get()->getType()->isVectorType())
12309     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12310 
12311   if (LHS.get()->getType()->isVLSTBuiltinType() ||
12312       RHS.get()->getType()->isVLSTBuiltinType())
12313     return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12314 
12315   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12316   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12317 
12318   QualType LHSType = LHS.get()->getType();
12319   QualType RHSType = RHS.get()->getType();
12320   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12321       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12322     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12323 
12324   const Expr::NullPointerConstantKind LHSNullKind =
12325       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12326   const Expr::NullPointerConstantKind RHSNullKind =
12327       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
12328   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12329   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12330 
12331   auto computeResultTy = [&]() {
12332     if (Opc != BO_Cmp)
12333       return Context.getLogicalOperationType();
12334     assert(getLangOpts().CPlusPlus);
12335     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12336 
12337     QualType CompositeTy = LHS.get()->getType();
12338     assert(!CompositeTy->isReferenceType());
12339 
12340     Optional<ComparisonCategoryType> CCT =
12341         getComparisonCategoryForBuiltinCmp(CompositeTy);
12342     if (!CCT)
12343       return InvalidOperands(Loc, LHS, RHS);
12344 
12345     if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12346       // P0946R0: Comparisons between a null pointer constant and an object
12347       // pointer result in std::strong_equality, which is ill-formed under
12348       // P1959R0.
12349       Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12350           << (LHSIsNull ? LHS.get()->getSourceRange()
12351                         : RHS.get()->getSourceRange());
12352       return QualType();
12353     }
12354 
12355     return CheckComparisonCategoryType(
12356         *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
12357   };
12358 
12359   if (!IsOrdered && LHSIsNull != RHSIsNull) {
12360     bool IsEquality = Opc == BO_EQ;
12361     if (RHSIsNull)
12362       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12363                                    RHS.get()->getSourceRange());
12364     else
12365       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12366                                    LHS.get()->getSourceRange());
12367   }
12368 
12369   if (IsOrdered && LHSType->isFunctionPointerType() &&
12370       RHSType->isFunctionPointerType()) {
12371     // Valid unless a relational comparison of function pointers
12372     bool IsError = Opc == BO_Cmp;
12373     auto DiagID =
12374         IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12375         : getLangOpts().CPlusPlus
12376             ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12377             : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12378     Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12379                       << RHS.get()->getSourceRange();
12380     if (IsError)
12381       return QualType();
12382   }
12383 
12384   if ((LHSType->isIntegerType() && !LHSIsNull) ||
12385       (RHSType->isIntegerType() && !RHSIsNull)) {
12386     // Skip normal pointer conversion checks in this case; we have better
12387     // diagnostics for this below.
12388   } else if (getLangOpts().CPlusPlus) {
12389     // Equality comparison of a function pointer to a void pointer is invalid,
12390     // but we allow it as an extension.
12391     // FIXME: If we really want to allow this, should it be part of composite
12392     // pointer type computation so it works in conditionals too?
12393     if (!IsOrdered &&
12394         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12395          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12396       // This is a gcc extension compatibility comparison.
12397       // In a SFINAE context, we treat this as a hard error to maintain
12398       // conformance with the C++ standard.
12399       diagnoseFunctionPointerToVoidComparison(
12400           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12401 
12402       if (isSFINAEContext())
12403         return QualType();
12404 
12405       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12406       return computeResultTy();
12407     }
12408 
12409     // C++ [expr.eq]p2:
12410     //   If at least one operand is a pointer [...] bring them to their
12411     //   composite pointer type.
12412     // C++ [expr.spaceship]p6
12413     //  If at least one of the operands is of pointer type, [...] bring them
12414     //  to their composite pointer type.
12415     // C++ [expr.rel]p2:
12416     //   If both operands are pointers, [...] bring them to their composite
12417     //   pointer type.
12418     // For <=>, the only valid non-pointer types are arrays and functions, and
12419     // we already decayed those, so this is really the same as the relational
12420     // comparison rule.
12421     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12422             (IsOrdered ? 2 : 1) &&
12423         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12424                                          RHSType->isObjCObjectPointerType()))) {
12425       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12426         return QualType();
12427       return computeResultTy();
12428     }
12429   } else if (LHSType->isPointerType() &&
12430              RHSType->isPointerType()) { // C99 6.5.8p2
12431     // All of the following pointer-related warnings are GCC extensions, except
12432     // when handling null pointer constants.
12433     QualType LCanPointeeTy =
12434       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12435     QualType RCanPointeeTy =
12436       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12437 
12438     // C99 6.5.9p2 and C99 6.5.8p2
12439     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12440                                    RCanPointeeTy.getUnqualifiedType())) {
12441       if (IsRelational) {
12442         // Pointers both need to point to complete or incomplete types
12443         if ((LCanPointeeTy->isIncompleteType() !=
12444              RCanPointeeTy->isIncompleteType()) &&
12445             !getLangOpts().C11) {
12446           Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12447               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12448               << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12449               << RCanPointeeTy->isIncompleteType();
12450         }
12451       }
12452     } else if (!IsRelational &&
12453                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12454       // Valid unless comparison between non-null pointer and function pointer
12455       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12456           && !LHSIsNull && !RHSIsNull)
12457         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12458                                                 /*isError*/false);
12459     } else {
12460       // Invalid
12461       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12462     }
12463     if (LCanPointeeTy != RCanPointeeTy) {
12464       // Treat NULL constant as a special case in OpenCL.
12465       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12466         if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12467           Diag(Loc,
12468                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12469               << LHSType << RHSType << 0 /* comparison */
12470               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12471         }
12472       }
12473       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12474       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12475       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12476                                                : CK_BitCast;
12477       if (LHSIsNull && !RHSIsNull)
12478         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12479       else
12480         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12481     }
12482     return computeResultTy();
12483   }
12484 
12485   if (getLangOpts().CPlusPlus) {
12486     // C++ [expr.eq]p4:
12487     //   Two operands of type std::nullptr_t or one operand of type
12488     //   std::nullptr_t and the other a null pointer constant compare equal.
12489     if (!IsOrdered && LHSIsNull && RHSIsNull) {
12490       if (LHSType->isNullPtrType()) {
12491         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12492         return computeResultTy();
12493       }
12494       if (RHSType->isNullPtrType()) {
12495         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12496         return computeResultTy();
12497       }
12498     }
12499 
12500     // Comparison of Objective-C pointers and block pointers against nullptr_t.
12501     // These aren't covered by the composite pointer type rules.
12502     if (!IsOrdered && RHSType->isNullPtrType() &&
12503         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12504       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12505       return computeResultTy();
12506     }
12507     if (!IsOrdered && LHSType->isNullPtrType() &&
12508         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12509       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12510       return computeResultTy();
12511     }
12512 
12513     if (IsRelational &&
12514         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12515          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12516       // HACK: Relational comparison of nullptr_t against a pointer type is
12517       // invalid per DR583, but we allow it within std::less<> and friends,
12518       // since otherwise common uses of it break.
12519       // FIXME: Consider removing this hack once LWG fixes std::less<> and
12520       // friends to have std::nullptr_t overload candidates.
12521       DeclContext *DC = CurContext;
12522       if (isa<FunctionDecl>(DC))
12523         DC = DC->getParent();
12524       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12525         if (CTSD->isInStdNamespace() &&
12526             llvm::StringSwitch<bool>(CTSD->getName())
12527                 .Cases("less", "less_equal", "greater", "greater_equal", true)
12528                 .Default(false)) {
12529           if (RHSType->isNullPtrType())
12530             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12531           else
12532             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12533           return computeResultTy();
12534         }
12535       }
12536     }
12537 
12538     // C++ [expr.eq]p2:
12539     //   If at least one operand is a pointer to member, [...] bring them to
12540     //   their composite pointer type.
12541     if (!IsOrdered &&
12542         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12543       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12544         return QualType();
12545       else
12546         return computeResultTy();
12547     }
12548   }
12549 
12550   // Handle block pointer types.
12551   if (!IsOrdered && LHSType->isBlockPointerType() &&
12552       RHSType->isBlockPointerType()) {
12553     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12554     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12555 
12556     if (!LHSIsNull && !RHSIsNull &&
12557         !Context.typesAreCompatible(lpointee, rpointee)) {
12558       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12559         << LHSType << RHSType << LHS.get()->getSourceRange()
12560         << RHS.get()->getSourceRange();
12561     }
12562     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12563     return computeResultTy();
12564   }
12565 
12566   // Allow block pointers to be compared with null pointer constants.
12567   if (!IsOrdered
12568       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12569           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12570     if (!LHSIsNull && !RHSIsNull) {
12571       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12572              ->getPointeeType()->isVoidType())
12573             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12574                 ->getPointeeType()->isVoidType())))
12575         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12576           << LHSType << RHSType << LHS.get()->getSourceRange()
12577           << RHS.get()->getSourceRange();
12578     }
12579     if (LHSIsNull && !RHSIsNull)
12580       LHS = ImpCastExprToType(LHS.get(), RHSType,
12581                               RHSType->isPointerType() ? CK_BitCast
12582                                 : CK_AnyPointerToBlockPointerCast);
12583     else
12584       RHS = ImpCastExprToType(RHS.get(), LHSType,
12585                               LHSType->isPointerType() ? CK_BitCast
12586                                 : CK_AnyPointerToBlockPointerCast);
12587     return computeResultTy();
12588   }
12589 
12590   if (LHSType->isObjCObjectPointerType() ||
12591       RHSType->isObjCObjectPointerType()) {
12592     const PointerType *LPT = LHSType->getAs<PointerType>();
12593     const PointerType *RPT = RHSType->getAs<PointerType>();
12594     if (LPT || RPT) {
12595       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12596       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12597 
12598       if (!LPtrToVoid && !RPtrToVoid &&
12599           !Context.typesAreCompatible(LHSType, RHSType)) {
12600         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12601                                           /*isError*/false);
12602       }
12603       // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12604       // the RHS, but we have test coverage for this behavior.
12605       // FIXME: Consider using convertPointersToCompositeType in C++.
12606       if (LHSIsNull && !RHSIsNull) {
12607         Expr *E = LHS.get();
12608         if (getLangOpts().ObjCAutoRefCount)
12609           CheckObjCConversion(SourceRange(), RHSType, E,
12610                               CCK_ImplicitConversion);
12611         LHS = ImpCastExprToType(E, RHSType,
12612                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12613       }
12614       else {
12615         Expr *E = RHS.get();
12616         if (getLangOpts().ObjCAutoRefCount)
12617           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12618                               /*Diagnose=*/true,
12619                               /*DiagnoseCFAudited=*/false, Opc);
12620         RHS = ImpCastExprToType(E, LHSType,
12621                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12622       }
12623       return computeResultTy();
12624     }
12625     if (LHSType->isObjCObjectPointerType() &&
12626         RHSType->isObjCObjectPointerType()) {
12627       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12628         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12629                                           /*isError*/false);
12630       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12631         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12632 
12633       if (LHSIsNull && !RHSIsNull)
12634         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12635       else
12636         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12637       return computeResultTy();
12638     }
12639 
12640     if (!IsOrdered && LHSType->isBlockPointerType() &&
12641         RHSType->isBlockCompatibleObjCPointerType(Context)) {
12642       LHS = ImpCastExprToType(LHS.get(), RHSType,
12643                               CK_BlockPointerToObjCPointerCast);
12644       return computeResultTy();
12645     } else if (!IsOrdered &&
12646                LHSType->isBlockCompatibleObjCPointerType(Context) &&
12647                RHSType->isBlockPointerType()) {
12648       RHS = ImpCastExprToType(RHS.get(), LHSType,
12649                               CK_BlockPointerToObjCPointerCast);
12650       return computeResultTy();
12651     }
12652   }
12653   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12654       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12655     unsigned DiagID = 0;
12656     bool isError = false;
12657     if (LangOpts.DebuggerSupport) {
12658       // Under a debugger, allow the comparison of pointers to integers,
12659       // since users tend to want to compare addresses.
12660     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12661                (RHSIsNull && RHSType->isIntegerType())) {
12662       if (IsOrdered) {
12663         isError = getLangOpts().CPlusPlus;
12664         DiagID =
12665           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12666                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12667       }
12668     } else if (getLangOpts().CPlusPlus) {
12669       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12670       isError = true;
12671     } else if (IsOrdered)
12672       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12673     else
12674       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12675 
12676     if (DiagID) {
12677       Diag(Loc, DiagID)
12678         << LHSType << RHSType << LHS.get()->getSourceRange()
12679         << RHS.get()->getSourceRange();
12680       if (isError)
12681         return QualType();
12682     }
12683 
12684     if (LHSType->isIntegerType())
12685       LHS = ImpCastExprToType(LHS.get(), RHSType,
12686                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12687     else
12688       RHS = ImpCastExprToType(RHS.get(), LHSType,
12689                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12690     return computeResultTy();
12691   }
12692 
12693   // Handle block pointers.
12694   if (!IsOrdered && RHSIsNull
12695       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12696     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12697     return computeResultTy();
12698   }
12699   if (!IsOrdered && LHSIsNull
12700       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12701     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12702     return computeResultTy();
12703   }
12704 
12705   if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12706     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12707       return computeResultTy();
12708     }
12709 
12710     if (LHSType->isQueueT() && RHSType->isQueueT()) {
12711       return computeResultTy();
12712     }
12713 
12714     if (LHSIsNull && RHSType->isQueueT()) {
12715       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12716       return computeResultTy();
12717     }
12718 
12719     if (LHSType->isQueueT() && RHSIsNull) {
12720       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12721       return computeResultTy();
12722     }
12723   }
12724 
12725   return InvalidOperands(Loc, LHS, RHS);
12726 }
12727 
12728 // Return a signed ext_vector_type that is of identical size and number of
12729 // elements. For floating point vectors, return an integer type of identical
12730 // size and number of elements. In the non ext_vector_type case, search from
12731 // the largest type to the smallest type to avoid cases where long long == long,
12732 // where long gets picked over long long.
12733 QualType Sema::GetSignedVectorType(QualType V) {
12734   const VectorType *VTy = V->castAs<VectorType>();
12735   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12736 
12737   if (isa<ExtVectorType>(VTy)) {
12738     if (VTy->isExtVectorBoolType())
12739       return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
12740     if (TypeSize == Context.getTypeSize(Context.CharTy))
12741       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12742     if (TypeSize == Context.getTypeSize(Context.ShortTy))
12743       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12744     if (TypeSize == Context.getTypeSize(Context.IntTy))
12745       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12746     if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12747       return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
12748     if (TypeSize == Context.getTypeSize(Context.LongTy))
12749       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12750     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12751            "Unhandled vector element size in vector compare");
12752     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12753   }
12754 
12755   if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12756     return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
12757                                  VectorType::GenericVector);
12758   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12759     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12760                                  VectorType::GenericVector);
12761   if (TypeSize == Context.getTypeSize(Context.LongTy))
12762     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12763                                  VectorType::GenericVector);
12764   if (TypeSize == Context.getTypeSize(Context.IntTy))
12765     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12766                                  VectorType::GenericVector);
12767   if (TypeSize == Context.getTypeSize(Context.ShortTy))
12768     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12769                                  VectorType::GenericVector);
12770   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12771          "Unhandled vector element size in vector compare");
12772   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12773                                VectorType::GenericVector);
12774 }
12775 
12776 QualType Sema::GetSignedSizelessVectorType(QualType V) {
12777   const BuiltinType *VTy = V->castAs<BuiltinType>();
12778   assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12779 
12780   const QualType ETy = V->getSveEltType(Context);
12781   const auto TypeSize = Context.getTypeSize(ETy);
12782 
12783   const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12784   const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12785   return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12786 }
12787 
12788 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12789 /// operates on extended vector types.  Instead of producing an IntTy result,
12790 /// like a scalar comparison, a vector comparison produces a vector of integer
12791 /// types.
12792 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12793                                           SourceLocation Loc,
12794                                           BinaryOperatorKind Opc) {
12795   if (Opc == BO_Cmp) {
12796     Diag(Loc, diag::err_three_way_vector_comparison);
12797     return QualType();
12798   }
12799 
12800   // Check to make sure we're operating on vectors of the same type and width,
12801   // Allowing one side to be a scalar of element type.
12802   QualType vType =
12803       CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12804                           /*AllowBothBool*/ true,
12805                           /*AllowBoolConversions*/ getLangOpts().ZVector,
12806                           /*AllowBooleanOperation*/ true,
12807                           /*ReportInvalid*/ true);
12808   if (vType.isNull())
12809     return vType;
12810 
12811   QualType LHSType = LHS.get()->getType();
12812 
12813   // Determine the return type of a vector compare. By default clang will return
12814   // a scalar for all vector compares except vector bool and vector pixel.
12815   // With the gcc compiler we will always return a vector type and with the xl
12816   // compiler we will always return a scalar type. This switch allows choosing
12817   // which behavior is prefered.
12818   if (getLangOpts().AltiVec) {
12819     switch (getLangOpts().getAltivecSrcCompat()) {
12820     case LangOptions::AltivecSrcCompatKind::Mixed:
12821       // If AltiVec, the comparison results in a numeric type, i.e.
12822       // bool for C++, int for C
12823       if (vType->castAs<VectorType>()->getVectorKind() ==
12824           VectorType::AltiVecVector)
12825         return Context.getLogicalOperationType();
12826       else
12827         Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12828       break;
12829     case LangOptions::AltivecSrcCompatKind::GCC:
12830       // For GCC we always return the vector type.
12831       break;
12832     case LangOptions::AltivecSrcCompatKind::XL:
12833       return Context.getLogicalOperationType();
12834       break;
12835     }
12836   }
12837 
12838   // For non-floating point types, check for self-comparisons of the form
12839   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12840   // often indicate logic errors in the program.
12841   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12842 
12843   // Check for comparisons of floating point operands using != and ==.
12844   if (BinaryOperator::isEqualityOp(Opc) &&
12845       LHSType->hasFloatingRepresentation()) {
12846     assert(RHS.get()->getType()->hasFloatingRepresentation());
12847     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12848   }
12849 
12850   // Return a signed type for the vector.
12851   return GetSignedVectorType(vType);
12852 }
12853 
12854 QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
12855                                                   ExprResult &RHS,
12856                                                   SourceLocation Loc,
12857                                                   BinaryOperatorKind Opc) {
12858   if (Opc == BO_Cmp) {
12859     Diag(Loc, diag::err_three_way_vector_comparison);
12860     return QualType();
12861   }
12862 
12863   // Check to make sure we're operating on vectors of the same type and width,
12864   // Allowing one side to be a scalar of element type.
12865   QualType vType = CheckSizelessVectorOperands(
12866       LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12867 
12868   if (vType.isNull())
12869     return vType;
12870 
12871   QualType LHSType = LHS.get()->getType();
12872 
12873   // For non-floating point types, check for self-comparisons of the form
12874   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
12875   // often indicate logic errors in the program.
12876   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12877 
12878   // Check for comparisons of floating point operands using != and ==.
12879   if (BinaryOperator::isEqualityOp(Opc) &&
12880       LHSType->hasFloatingRepresentation()) {
12881     assert(RHS.get()->getType()->hasFloatingRepresentation());
12882     CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12883   }
12884 
12885   const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12886   const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12887 
12888   if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12889       RHSBuiltinTy->isSVEBool())
12890     return LHSType;
12891 
12892   // Return a signed type for the vector.
12893   return GetSignedSizelessVectorType(vType);
12894 }
12895 
12896 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12897                                     const ExprResult &XorRHS,
12898                                     const SourceLocation Loc) {
12899   // Do not diagnose macros.
12900   if (Loc.isMacroID())
12901     return;
12902 
12903   // Do not diagnose if both LHS and RHS are macros.
12904   if (XorLHS.get()->getExprLoc().isMacroID() &&
12905       XorRHS.get()->getExprLoc().isMacroID())
12906     return;
12907 
12908   bool Negative = false;
12909   bool ExplicitPlus = false;
12910   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12911   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12912 
12913   if (!LHSInt)
12914     return;
12915   if (!RHSInt) {
12916     // Check negative literals.
12917     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12918       UnaryOperatorKind Opc = UO->getOpcode();
12919       if (Opc != UO_Minus && Opc != UO_Plus)
12920         return;
12921       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12922       if (!RHSInt)
12923         return;
12924       Negative = (Opc == UO_Minus);
12925       ExplicitPlus = !Negative;
12926     } else {
12927       return;
12928     }
12929   }
12930 
12931   const llvm::APInt &LeftSideValue = LHSInt->getValue();
12932   llvm::APInt RightSideValue = RHSInt->getValue();
12933   if (LeftSideValue != 2 && LeftSideValue != 10)
12934     return;
12935 
12936   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12937     return;
12938 
12939   CharSourceRange ExprRange = CharSourceRange::getCharRange(
12940       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12941   llvm::StringRef ExprStr =
12942       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12943 
12944   CharSourceRange XorRange =
12945       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12946   llvm::StringRef XorStr =
12947       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12948   // Do not diagnose if xor keyword/macro is used.
12949   if (XorStr == "xor")
12950     return;
12951 
12952   std::string LHSStr = std::string(Lexer::getSourceText(
12953       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12954       S.getSourceManager(), S.getLangOpts()));
12955   std::string RHSStr = std::string(Lexer::getSourceText(
12956       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12957       S.getSourceManager(), S.getLangOpts()));
12958 
12959   if (Negative) {
12960     RightSideValue = -RightSideValue;
12961     RHSStr = "-" + RHSStr;
12962   } else if (ExplicitPlus) {
12963     RHSStr = "+" + RHSStr;
12964   }
12965 
12966   StringRef LHSStrRef = LHSStr;
12967   StringRef RHSStrRef = RHSStr;
12968   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12969   // literals.
12970   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12971       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12972       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12973       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12974       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12975       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12976       LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12977     return;
12978 
12979   bool SuggestXor =
12980       S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12981   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12982   int64_t RightSideIntValue = RightSideValue.getSExtValue();
12983   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12984     std::string SuggestedExpr = "1 << " + RHSStr;
12985     bool Overflow = false;
12986     llvm::APInt One = (LeftSideValue - 1);
12987     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12988     if (Overflow) {
12989       if (RightSideIntValue < 64)
12990         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12991             << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12992             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12993       else if (RightSideIntValue == 64)
12994         S.Diag(Loc, diag::warn_xor_used_as_pow)
12995             << ExprStr << toString(XorValue, 10, true);
12996       else
12997         return;
12998     } else {
12999       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13000           << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13001           << toString(PowValue, 10, true)
13002           << FixItHint::CreateReplacement(
13003                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13004     }
13005 
13006     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13007         << ("0x2 ^ " + RHSStr) << SuggestXor;
13008   } else if (LeftSideValue == 10) {
13009     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13010     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13011         << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13012         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13013     S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13014         << ("0xA ^ " + RHSStr) << SuggestXor;
13015   }
13016 }
13017 
13018 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13019                                           SourceLocation Loc) {
13020   // Ensure that either both operands are of the same vector type, or
13021   // one operand is of a vector type and the other is of its element type.
13022   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13023                                        /*AllowBothBool*/ true,
13024                                        /*AllowBoolConversions*/ false,
13025                                        /*AllowBooleanOperation*/ false,
13026                                        /*ReportInvalid*/ false);
13027   if (vType.isNull())
13028     return InvalidOperands(Loc, LHS, RHS);
13029   if (getLangOpts().OpenCL &&
13030       getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13031       vType->hasFloatingRepresentation())
13032     return InvalidOperands(Loc, LHS, RHS);
13033   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13034   //        usage of the logical operators && and || with vectors in C. This
13035   //        check could be notionally dropped.
13036   if (!getLangOpts().CPlusPlus &&
13037       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13038     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13039 
13040   return GetSignedVectorType(LHS.get()->getType());
13041 }
13042 
13043 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13044                                               SourceLocation Loc,
13045                                               bool IsCompAssign) {
13046   if (!IsCompAssign) {
13047     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13048     if (LHS.isInvalid())
13049       return QualType();
13050   }
13051   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13052   if (RHS.isInvalid())
13053     return QualType();
13054 
13055   // For conversion purposes, we ignore any qualifiers.
13056   // For example, "const float" and "float" are equivalent.
13057   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13058   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13059 
13060   const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13061   const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13062   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13063 
13064   if (Context.hasSameType(LHSType, RHSType))
13065     return LHSType;
13066 
13067   // Type conversion may change LHS/RHS. Keep copies to the original results, in
13068   // case we have to return InvalidOperands.
13069   ExprResult OriginalLHS = LHS;
13070   ExprResult OriginalRHS = RHS;
13071   if (LHSMatType && !RHSMatType) {
13072     RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13073     if (!RHS.isInvalid())
13074       return LHSType;
13075 
13076     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13077   }
13078 
13079   if (!LHSMatType && RHSMatType) {
13080     LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13081     if (!LHS.isInvalid())
13082       return RHSType;
13083     return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13084   }
13085 
13086   return InvalidOperands(Loc, LHS, RHS);
13087 }
13088 
13089 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13090                                            SourceLocation Loc,
13091                                            bool IsCompAssign) {
13092   if (!IsCompAssign) {
13093     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
13094     if (LHS.isInvalid())
13095       return QualType();
13096   }
13097   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
13098   if (RHS.isInvalid())
13099     return QualType();
13100 
13101   auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13102   auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13103   assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13104 
13105   if (LHSMatType && RHSMatType) {
13106     if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13107       return InvalidOperands(Loc, LHS, RHS);
13108 
13109     if (!Context.hasSameType(LHSMatType->getElementType(),
13110                              RHSMatType->getElementType()))
13111       return InvalidOperands(Loc, LHS, RHS);
13112 
13113     return Context.getConstantMatrixType(LHSMatType->getElementType(),
13114                                          LHSMatType->getNumRows(),
13115                                          RHSMatType->getNumColumns());
13116   }
13117   return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13118 }
13119 
13120 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
13121   switch (Opc) {
13122   default:
13123     return false;
13124   case BO_And:
13125   case BO_AndAssign:
13126   case BO_Or:
13127   case BO_OrAssign:
13128   case BO_Xor:
13129   case BO_XorAssign:
13130     return true;
13131   }
13132 }
13133 
13134 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13135                                            SourceLocation Loc,
13136                                            BinaryOperatorKind Opc) {
13137   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13138 
13139   bool IsCompAssign =
13140       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13141 
13142   bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13143 
13144   if (LHS.get()->getType()->isVectorType() ||
13145       RHS.get()->getType()->isVectorType()) {
13146     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13147         RHS.get()->getType()->hasIntegerRepresentation())
13148       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13149                                  /*AllowBothBool*/ true,
13150                                  /*AllowBoolConversions*/ getLangOpts().ZVector,
13151                                  /*AllowBooleanOperation*/ LegalBoolVecOperator,
13152                                  /*ReportInvalid*/ true);
13153     return InvalidOperands(Loc, LHS, RHS);
13154   }
13155 
13156   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13157       RHS.get()->getType()->isVLSTBuiltinType()) {
13158     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13159         RHS.get()->getType()->hasIntegerRepresentation())
13160       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13161                                          ACK_BitwiseOp);
13162     return InvalidOperands(Loc, LHS, RHS);
13163   }
13164 
13165   if (LHS.get()->getType()->isVLSTBuiltinType() ||
13166       RHS.get()->getType()->isVLSTBuiltinType()) {
13167     if (LHS.get()->getType()->hasIntegerRepresentation() &&
13168         RHS.get()->getType()->hasIntegerRepresentation())
13169       return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13170                                          ACK_BitwiseOp);
13171     return InvalidOperands(Loc, LHS, RHS);
13172   }
13173 
13174   if (Opc == BO_And)
13175     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13176 
13177   if (LHS.get()->getType()->hasFloatingRepresentation() ||
13178       RHS.get()->getType()->hasFloatingRepresentation())
13179     return InvalidOperands(Loc, LHS, RHS);
13180 
13181   ExprResult LHSResult = LHS, RHSResult = RHS;
13182   QualType compType = UsualArithmeticConversions(
13183       LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13184   if (LHSResult.isInvalid() || RHSResult.isInvalid())
13185     return QualType();
13186   LHS = LHSResult.get();
13187   RHS = RHSResult.get();
13188 
13189   if (Opc == BO_Xor)
13190     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13191 
13192   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13193     return compType;
13194   return InvalidOperands(Loc, LHS, RHS);
13195 }
13196 
13197 // C99 6.5.[13,14]
13198 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
13199                                            SourceLocation Loc,
13200                                            BinaryOperatorKind Opc) {
13201   // Check vector operands differently.
13202   if (LHS.get()->getType()->isVectorType() ||
13203       RHS.get()->getType()->isVectorType())
13204     return CheckVectorLogicalOperands(LHS, RHS, Loc);
13205 
13206   bool EnumConstantInBoolContext = false;
13207   for (const ExprResult &HS : {LHS, RHS}) {
13208     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13209       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13210       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13211         EnumConstantInBoolContext = true;
13212     }
13213   }
13214 
13215   if (EnumConstantInBoolContext)
13216     Diag(Loc, diag::warn_enum_constant_in_bool_context);
13217 
13218   // Diagnose cases where the user write a logical and/or but probably meant a
13219   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
13220   // is a constant.
13221   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13222       !LHS.get()->getType()->isBooleanType() &&
13223       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13224       // Don't warn in macros or template instantiations.
13225       !Loc.isMacroID() && !inTemplateInstantiation()) {
13226     // If the RHS can be constant folded, and if it constant folds to something
13227     // that isn't 0 or 1 (which indicate a potential logical operation that
13228     // happened to fold to true/false) then warn.
13229     // Parens on the RHS are ignored.
13230     Expr::EvalResult EVResult;
13231     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13232       llvm::APSInt Result = EVResult.Val.getInt();
13233       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
13234            !RHS.get()->getExprLoc().isMacroID()) ||
13235           (Result != 0 && Result != 1)) {
13236         Diag(Loc, diag::warn_logical_instead_of_bitwise)
13237             << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13238         // Suggest replacing the logical operator with the bitwise version
13239         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13240             << (Opc == BO_LAnd ? "&" : "|")
13241             << FixItHint::CreateReplacement(
13242                    SourceRange(Loc, getLocForEndOfToken(Loc)),
13243                    Opc == BO_LAnd ? "&" : "|");
13244         if (Opc == BO_LAnd)
13245           // Suggest replacing "Foo() && kNonZero" with "Foo()"
13246           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13247               << FixItHint::CreateRemoval(
13248                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
13249                                  RHS.get()->getEndLoc()));
13250       }
13251     }
13252   }
13253 
13254   if (!Context.getLangOpts().CPlusPlus) {
13255     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13256     // not operate on the built-in scalar and vector float types.
13257     if (Context.getLangOpts().OpenCL &&
13258         Context.getLangOpts().OpenCLVersion < 120) {
13259       if (LHS.get()->getType()->isFloatingType() ||
13260           RHS.get()->getType()->isFloatingType())
13261         return InvalidOperands(Loc, LHS, RHS);
13262     }
13263 
13264     LHS = UsualUnaryConversions(LHS.get());
13265     if (LHS.isInvalid())
13266       return QualType();
13267 
13268     RHS = UsualUnaryConversions(RHS.get());
13269     if (RHS.isInvalid())
13270       return QualType();
13271 
13272     if (!LHS.get()->getType()->isScalarType() ||
13273         !RHS.get()->getType()->isScalarType())
13274       return InvalidOperands(Loc, LHS, RHS);
13275 
13276     return Context.IntTy;
13277   }
13278 
13279   // The following is safe because we only use this method for
13280   // non-overloadable operands.
13281 
13282   // C++ [expr.log.and]p1
13283   // C++ [expr.log.or]p1
13284   // The operands are both contextually converted to type bool.
13285   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
13286   if (LHSRes.isInvalid())
13287     return InvalidOperands(Loc, LHS, RHS);
13288   LHS = LHSRes;
13289 
13290   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
13291   if (RHSRes.isInvalid())
13292     return InvalidOperands(Loc, LHS, RHS);
13293   RHS = RHSRes;
13294 
13295   // C++ [expr.log.and]p2
13296   // C++ [expr.log.or]p2
13297   // The result is a bool.
13298   return Context.BoolTy;
13299 }
13300 
13301 static bool IsReadonlyMessage(Expr *E, Sema &S) {
13302   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13303   if (!ME) return false;
13304   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13305   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13306       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13307   if (!Base) return false;
13308   return Base->getMethodDecl() != nullptr;
13309 }
13310 
13311 /// Is the given expression (which must be 'const') a reference to a
13312 /// variable which was originally non-const, but which has become
13313 /// 'const' due to being captured within a block?
13314 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13315 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
13316   assert(E->isLValue() && E->getType().isConstQualified());
13317   E = E->IgnoreParens();
13318 
13319   // Must be a reference to a declaration from an enclosing scope.
13320   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13321   if (!DRE) return NCCK_None;
13322   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13323 
13324   // The declaration must be a variable which is not declared 'const'.
13325   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13326   if (!var) return NCCK_None;
13327   if (var->getType().isConstQualified()) return NCCK_None;
13328   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13329 
13330   // Decide whether the first capture was for a block or a lambda.
13331   DeclContext *DC = S.CurContext, *Prev = nullptr;
13332   // Decide whether the first capture was for a block or a lambda.
13333   while (DC) {
13334     // For init-capture, it is possible that the variable belongs to the
13335     // template pattern of the current context.
13336     if (auto *FD = dyn_cast<FunctionDecl>(DC))
13337       if (var->isInitCapture() &&
13338           FD->getTemplateInstantiationPattern() == var->getDeclContext())
13339         break;
13340     if (DC == var->getDeclContext())
13341       break;
13342     Prev = DC;
13343     DC = DC->getParent();
13344   }
13345   // Unless we have an init-capture, we've gone one step too far.
13346   if (!var->isInitCapture())
13347     DC = Prev;
13348   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13349 }
13350 
13351 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13352   Ty = Ty.getNonReferenceType();
13353   if (IsDereference && Ty->isPointerType())
13354     Ty = Ty->getPointeeType();
13355   return !Ty.isConstQualified();
13356 }
13357 
13358 // Update err_typecheck_assign_const and note_typecheck_assign_const
13359 // when this enum is changed.
13360 enum {
13361   ConstFunction,
13362   ConstVariable,
13363   ConstMember,
13364   ConstMethod,
13365   NestedConstMember,
13366   ConstUnknown,  // Keep as last element
13367 };
13368 
13369 /// Emit the "read-only variable not assignable" error and print notes to give
13370 /// more information about why the variable is not assignable, such as pointing
13371 /// to the declaration of a const variable, showing that a method is const, or
13372 /// that the function is returning a const reference.
13373 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13374                                     SourceLocation Loc) {
13375   SourceRange ExprRange = E->getSourceRange();
13376 
13377   // Only emit one error on the first const found.  All other consts will emit
13378   // a note to the error.
13379   bool DiagnosticEmitted = false;
13380 
13381   // Track if the current expression is the result of a dereference, and if the
13382   // next checked expression is the result of a dereference.
13383   bool IsDereference = false;
13384   bool NextIsDereference = false;
13385 
13386   // Loop to process MemberExpr chains.
13387   while (true) {
13388     IsDereference = NextIsDereference;
13389 
13390     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13391     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13392       NextIsDereference = ME->isArrow();
13393       const ValueDecl *VD = ME->getMemberDecl();
13394       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13395         // Mutable fields can be modified even if the class is const.
13396         if (Field->isMutable()) {
13397           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13398           break;
13399         }
13400 
13401         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13402           if (!DiagnosticEmitted) {
13403             S.Diag(Loc, diag::err_typecheck_assign_const)
13404                 << ExprRange << ConstMember << false /*static*/ << Field
13405                 << Field->getType();
13406             DiagnosticEmitted = true;
13407           }
13408           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13409               << ConstMember << false /*static*/ << Field << Field->getType()
13410               << Field->getSourceRange();
13411         }
13412         E = ME->getBase();
13413         continue;
13414       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13415         if (VDecl->getType().isConstQualified()) {
13416           if (!DiagnosticEmitted) {
13417             S.Diag(Loc, diag::err_typecheck_assign_const)
13418                 << ExprRange << ConstMember << true /*static*/ << VDecl
13419                 << VDecl->getType();
13420             DiagnosticEmitted = true;
13421           }
13422           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13423               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13424               << VDecl->getSourceRange();
13425         }
13426         // Static fields do not inherit constness from parents.
13427         break;
13428       }
13429       break; // End MemberExpr
13430     } else if (const ArraySubscriptExpr *ASE =
13431                    dyn_cast<ArraySubscriptExpr>(E)) {
13432       E = ASE->getBase()->IgnoreParenImpCasts();
13433       continue;
13434     } else if (const ExtVectorElementExpr *EVE =
13435                    dyn_cast<ExtVectorElementExpr>(E)) {
13436       E = EVE->getBase()->IgnoreParenImpCasts();
13437       continue;
13438     }
13439     break;
13440   }
13441 
13442   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13443     // Function calls
13444     const FunctionDecl *FD = CE->getDirectCallee();
13445     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13446       if (!DiagnosticEmitted) {
13447         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13448                                                       << ConstFunction << FD;
13449         DiagnosticEmitted = true;
13450       }
13451       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13452              diag::note_typecheck_assign_const)
13453           << ConstFunction << FD << FD->getReturnType()
13454           << FD->getReturnTypeSourceRange();
13455     }
13456   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13457     // Point to variable declaration.
13458     if (const ValueDecl *VD = DRE->getDecl()) {
13459       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13460         if (!DiagnosticEmitted) {
13461           S.Diag(Loc, diag::err_typecheck_assign_const)
13462               << ExprRange << ConstVariable << VD << VD->getType();
13463           DiagnosticEmitted = true;
13464         }
13465         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13466             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13467       }
13468     }
13469   } else if (isa<CXXThisExpr>(E)) {
13470     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13471       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13472         if (MD->isConst()) {
13473           if (!DiagnosticEmitted) {
13474             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13475                                                           << ConstMethod << MD;
13476             DiagnosticEmitted = true;
13477           }
13478           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13479               << ConstMethod << MD << MD->getSourceRange();
13480         }
13481       }
13482     }
13483   }
13484 
13485   if (DiagnosticEmitted)
13486     return;
13487 
13488   // Can't determine a more specific message, so display the generic error.
13489   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13490 }
13491 
13492 enum OriginalExprKind {
13493   OEK_Variable,
13494   OEK_Member,
13495   OEK_LValue
13496 };
13497 
13498 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
13499                                          const RecordType *Ty,
13500                                          SourceLocation Loc, SourceRange Range,
13501                                          OriginalExprKind OEK,
13502                                          bool &DiagnosticEmitted) {
13503   std::vector<const RecordType *> RecordTypeList;
13504   RecordTypeList.push_back(Ty);
13505   unsigned NextToCheckIndex = 0;
13506   // We walk the record hierarchy breadth-first to ensure that we print
13507   // diagnostics in field nesting order.
13508   while (RecordTypeList.size() > NextToCheckIndex) {
13509     bool IsNested = NextToCheckIndex > 0;
13510     for (const FieldDecl *Field :
13511          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13512       // First, check every field for constness.
13513       QualType FieldTy = Field->getType();
13514       if (FieldTy.isConstQualified()) {
13515         if (!DiagnosticEmitted) {
13516           S.Diag(Loc, diag::err_typecheck_assign_const)
13517               << Range << NestedConstMember << OEK << VD
13518               << IsNested << Field;
13519           DiagnosticEmitted = true;
13520         }
13521         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13522             << NestedConstMember << IsNested << Field
13523             << FieldTy << Field->getSourceRange();
13524       }
13525 
13526       // Then we append it to the list to check next in order.
13527       FieldTy = FieldTy.getCanonicalType();
13528       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13529         if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13530           RecordTypeList.push_back(FieldRecTy);
13531       }
13532     }
13533     ++NextToCheckIndex;
13534   }
13535 }
13536 
13537 /// Emit an error for the case where a record we are trying to assign to has a
13538 /// const-qualified field somewhere in its hierarchy.
13539 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13540                                          SourceLocation Loc) {
13541   QualType Ty = E->getType();
13542   assert(Ty->isRecordType() && "lvalue was not record?");
13543   SourceRange Range = E->getSourceRange();
13544   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13545   bool DiagEmitted = false;
13546 
13547   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13548     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13549             Range, OEK_Member, DiagEmitted);
13550   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13551     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13552             Range, OEK_Variable, DiagEmitted);
13553   else
13554     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13555             Range, OEK_LValue, DiagEmitted);
13556   if (!DiagEmitted)
13557     DiagnoseConstAssignment(S, E, Loc);
13558 }
13559 
13560 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
13561 /// emit an error and return true.  If so, return false.
13562 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13563   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13564 
13565   S.CheckShadowingDeclModification(E, Loc);
13566 
13567   SourceLocation OrigLoc = Loc;
13568   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
13569                                                               &Loc);
13570   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13571     IsLV = Expr::MLV_InvalidMessageExpression;
13572   if (IsLV == Expr::MLV_Valid)
13573     return false;
13574 
13575   unsigned DiagID = 0;
13576   bool NeedType = false;
13577   switch (IsLV) { // C99 6.5.16p2
13578   case Expr::MLV_ConstQualified:
13579     // Use a specialized diagnostic when we're assigning to an object
13580     // from an enclosing function or block.
13581     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
13582       if (NCCK == NCCK_Block)
13583         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13584       else
13585         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13586       break;
13587     }
13588 
13589     // In ARC, use some specialized diagnostics for occasions where we
13590     // infer 'const'.  These are always pseudo-strong variables.
13591     if (S.getLangOpts().ObjCAutoRefCount) {
13592       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13593       if (declRef && isa<VarDecl>(declRef->getDecl())) {
13594         VarDecl *var = cast<VarDecl>(declRef->getDecl());
13595 
13596         // Use the normal diagnostic if it's pseudo-__strong but the
13597         // user actually wrote 'const'.
13598         if (var->isARCPseudoStrong() &&
13599             (!var->getTypeSourceInfo() ||
13600              !var->getTypeSourceInfo()->getType().isConstQualified())) {
13601           // There are three pseudo-strong cases:
13602           //  - self
13603           ObjCMethodDecl *method = S.getCurMethodDecl();
13604           if (method && var == method->getSelfDecl()) {
13605             DiagID = method->isClassMethod()
13606               ? diag::err_typecheck_arc_assign_self_class_method
13607               : diag::err_typecheck_arc_assign_self;
13608 
13609           //  - Objective-C externally_retained attribute.
13610           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13611                      isa<ParmVarDecl>(var)) {
13612             DiagID = diag::err_typecheck_arc_assign_externally_retained;
13613 
13614           //  - fast enumeration variables
13615           } else {
13616             DiagID = diag::err_typecheck_arr_assign_enumeration;
13617           }
13618 
13619           SourceRange Assign;
13620           if (Loc != OrigLoc)
13621             Assign = SourceRange(OrigLoc, OrigLoc);
13622           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13623           // We need to preserve the AST regardless, so migration tool
13624           // can do its job.
13625           return false;
13626         }
13627       }
13628     }
13629 
13630     // If none of the special cases above are triggered, then this is a
13631     // simple const assignment.
13632     if (DiagID == 0) {
13633       DiagnoseConstAssignment(S, E, Loc);
13634       return true;
13635     }
13636 
13637     break;
13638   case Expr::MLV_ConstAddrSpace:
13639     DiagnoseConstAssignment(S, E, Loc);
13640     return true;
13641   case Expr::MLV_ConstQualifiedField:
13642     DiagnoseRecursiveConstFields(S, E, Loc);
13643     return true;
13644   case Expr::MLV_ArrayType:
13645   case Expr::MLV_ArrayTemporary:
13646     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13647     NeedType = true;
13648     break;
13649   case Expr::MLV_NotObjectType:
13650     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13651     NeedType = true;
13652     break;
13653   case Expr::MLV_LValueCast:
13654     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13655     break;
13656   case Expr::MLV_Valid:
13657     llvm_unreachable("did not take early return for MLV_Valid");
13658   case Expr::MLV_InvalidExpression:
13659   case Expr::MLV_MemberFunction:
13660   case Expr::MLV_ClassTemporary:
13661     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13662     break;
13663   case Expr::MLV_IncompleteType:
13664   case Expr::MLV_IncompleteVoidType:
13665     return S.RequireCompleteType(Loc, E->getType(),
13666              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13667   case Expr::MLV_DuplicateVectorComponents:
13668     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13669     break;
13670   case Expr::MLV_NoSetterProperty:
13671     llvm_unreachable("readonly properties should be processed differently");
13672   case Expr::MLV_InvalidMessageExpression:
13673     DiagID = diag::err_readonly_message_assignment;
13674     break;
13675   case Expr::MLV_SubObjCPropertySetting:
13676     DiagID = diag::err_no_subobject_property_setting;
13677     break;
13678   }
13679 
13680   SourceRange Assign;
13681   if (Loc != OrigLoc)
13682     Assign = SourceRange(OrigLoc, OrigLoc);
13683   if (NeedType)
13684     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13685   else
13686     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13687   return true;
13688 }
13689 
13690 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13691                                          SourceLocation Loc,
13692                                          Sema &Sema) {
13693   if (Sema.inTemplateInstantiation())
13694     return;
13695   if (Sema.isUnevaluatedContext())
13696     return;
13697   if (Loc.isInvalid() || Loc.isMacroID())
13698     return;
13699   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13700     return;
13701 
13702   // C / C++ fields
13703   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13704   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13705   if (ML && MR) {
13706     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13707       return;
13708     const ValueDecl *LHSDecl =
13709         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13710     const ValueDecl *RHSDecl =
13711         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13712     if (LHSDecl != RHSDecl)
13713       return;
13714     if (LHSDecl->getType().isVolatileQualified())
13715       return;
13716     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13717       if (RefTy->getPointeeType().isVolatileQualified())
13718         return;
13719 
13720     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13721   }
13722 
13723   // Objective-C instance variables
13724   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13725   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13726   if (OL && OR && OL->getDecl() == OR->getDecl()) {
13727     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13728     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13729     if (RL && RR && RL->getDecl() == RR->getDecl())
13730       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13731   }
13732 }
13733 
13734 // C99 6.5.16.1
13735 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13736                                        SourceLocation Loc,
13737                                        QualType CompoundType) {
13738   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13739 
13740   // Verify that LHS is a modifiable lvalue, and emit error if not.
13741   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13742     return QualType();
13743 
13744   QualType LHSType = LHSExpr->getType();
13745   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13746                                              CompoundType;
13747   // OpenCL v1.2 s6.1.1.1 p2:
13748   // The half data type can only be used to declare a pointer to a buffer that
13749   // contains half values
13750   if (getLangOpts().OpenCL &&
13751       !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13752       LHSType->isHalfType()) {
13753     Diag(Loc, diag::err_opencl_half_load_store) << 1
13754         << LHSType.getUnqualifiedType();
13755     return QualType();
13756   }
13757 
13758   AssignConvertType ConvTy;
13759   if (CompoundType.isNull()) {
13760     Expr *RHSCheck = RHS.get();
13761 
13762     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13763 
13764     QualType LHSTy(LHSType);
13765     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13766     if (RHS.isInvalid())
13767       return QualType();
13768     // Special case of NSObject attributes on c-style pointer types.
13769     if (ConvTy == IncompatiblePointer &&
13770         ((Context.isObjCNSObjectType(LHSType) &&
13771           RHSType->isObjCObjectPointerType()) ||
13772          (Context.isObjCNSObjectType(RHSType) &&
13773           LHSType->isObjCObjectPointerType())))
13774       ConvTy = Compatible;
13775 
13776     if (ConvTy == Compatible &&
13777         LHSType->isObjCObjectType())
13778         Diag(Loc, diag::err_objc_object_assignment)
13779           << LHSType;
13780 
13781     // If the RHS is a unary plus or minus, check to see if they = and + are
13782     // right next to each other.  If so, the user may have typo'd "x =+ 4"
13783     // instead of "x += 4".
13784     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13785       RHSCheck = ICE->getSubExpr();
13786     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13787       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13788           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13789           // Only if the two operators are exactly adjacent.
13790           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13791           // And there is a space or other character before the subexpr of the
13792           // unary +/-.  We don't want to warn on "x=-1".
13793           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13794           UO->getSubExpr()->getBeginLoc().isFileID()) {
13795         Diag(Loc, diag::warn_not_compound_assign)
13796           << (UO->getOpcode() == UO_Plus ? "+" : "-")
13797           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13798       }
13799     }
13800 
13801     if (ConvTy == Compatible) {
13802       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13803         // Warn about retain cycles where a block captures the LHS, but
13804         // not if the LHS is a simple variable into which the block is
13805         // being stored...unless that variable can be captured by reference!
13806         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13807         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13808         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13809           checkRetainCycles(LHSExpr, RHS.get());
13810       }
13811 
13812       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13813           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13814         // It is safe to assign a weak reference into a strong variable.
13815         // Although this code can still have problems:
13816         //   id x = self.weakProp;
13817         //   id y = self.weakProp;
13818         // we do not warn to warn spuriously when 'x' and 'y' are on separate
13819         // paths through the function. This should be revisited if
13820         // -Wrepeated-use-of-weak is made flow-sensitive.
13821         // For ObjCWeak only, we do not warn if the assign is to a non-weak
13822         // variable, which will be valid for the current autorelease scope.
13823         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13824                              RHS.get()->getBeginLoc()))
13825           getCurFunction()->markSafeWeakUse(RHS.get());
13826 
13827       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13828         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13829       }
13830     }
13831   } else {
13832     // Compound assignment "x += y"
13833     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13834   }
13835 
13836   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13837                                RHS.get(), AA_Assigning))
13838     return QualType();
13839 
13840   CheckForNullPointerDereference(*this, LHSExpr);
13841 
13842   if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13843     if (CompoundType.isNull()) {
13844       // C++2a [expr.ass]p5:
13845       //   A simple-assignment whose left operand is of a volatile-qualified
13846       //   type is deprecated unless the assignment is either a discarded-value
13847       //   expression or an unevaluated operand
13848       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13849     } else {
13850       // C++2a [expr.ass]p6:
13851       //   [Compound-assignment] expressions are deprecated if E1 has
13852       //   volatile-qualified type
13853       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13854     }
13855   }
13856 
13857   // C11 6.5.16p3: The type of an assignment expression is the type of the
13858   // left operand would have after lvalue conversion.
13859   // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13860   // qualified type, the value has the unqualified version of the type of the
13861   // lvalue; additionally, if the lvalue has atomic type, the value has the
13862   // non-atomic version of the type of the lvalue.
13863   // C++ 5.17p1: the type of the assignment expression is that of its left
13864   // operand.
13865   return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13866 }
13867 
13868 // Only ignore explicit casts to void.
13869 static bool IgnoreCommaOperand(const Expr *E) {
13870   E = E->IgnoreParens();
13871 
13872   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13873     if (CE->getCastKind() == CK_ToVoid) {
13874       return true;
13875     }
13876 
13877     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13878     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13879         CE->getSubExpr()->getType()->isDependentType()) {
13880       return true;
13881     }
13882   }
13883 
13884   return false;
13885 }
13886 
13887 // Look for instances where it is likely the comma operator is confused with
13888 // another operator.  There is an explicit list of acceptable expressions for
13889 // the left hand side of the comma operator, otherwise emit a warning.
13890 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13891   // No warnings in macros
13892   if (Loc.isMacroID())
13893     return;
13894 
13895   // Don't warn in template instantiations.
13896   if (inTemplateInstantiation())
13897     return;
13898 
13899   // Scope isn't fine-grained enough to explicitly list the specific cases, so
13900   // instead, skip more than needed, then call back into here with the
13901   // CommaVisitor in SemaStmt.cpp.
13902   // The listed locations are the initialization and increment portions
13903   // of a for loop.  The additional checks are on the condition of
13904   // if statements, do/while loops, and for loops.
13905   // Differences in scope flags for C89 mode requires the extra logic.
13906   const unsigned ForIncrementFlags =
13907       getLangOpts().C99 || getLangOpts().CPlusPlus
13908           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13909           : Scope::ContinueScope | Scope::BreakScope;
13910   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13911   const unsigned ScopeFlags = getCurScope()->getFlags();
13912   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13913       (ScopeFlags & ForInitFlags) == ForInitFlags)
13914     return;
13915 
13916   // If there are multiple comma operators used together, get the RHS of the
13917   // of the comma operator as the LHS.
13918   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13919     if (BO->getOpcode() != BO_Comma)
13920       break;
13921     LHS = BO->getRHS();
13922   }
13923 
13924   // Only allow some expressions on LHS to not warn.
13925   if (IgnoreCommaOperand(LHS))
13926     return;
13927 
13928   Diag(Loc, diag::warn_comma_operator);
13929   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13930       << LHS->getSourceRange()
13931       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13932                                     LangOpts.CPlusPlus ? "static_cast<void>("
13933                                                        : "(void)(")
13934       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13935                                     ")");
13936 }
13937 
13938 // C99 6.5.17
13939 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13940                                    SourceLocation Loc) {
13941   LHS = S.CheckPlaceholderExpr(LHS.get());
13942   RHS = S.CheckPlaceholderExpr(RHS.get());
13943   if (LHS.isInvalid() || RHS.isInvalid())
13944     return QualType();
13945 
13946   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13947   // operands, but not unary promotions.
13948   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13949 
13950   // So we treat the LHS as a ignored value, and in C++ we allow the
13951   // containing site to determine what should be done with the RHS.
13952   LHS = S.IgnoredValueConversions(LHS.get());
13953   if (LHS.isInvalid())
13954     return QualType();
13955 
13956   S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13957 
13958   if (!S.getLangOpts().CPlusPlus) {
13959     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13960     if (RHS.isInvalid())
13961       return QualType();
13962     if (!RHS.get()->getType()->isVoidType())
13963       S.RequireCompleteType(Loc, RHS.get()->getType(),
13964                             diag::err_incomplete_type);
13965   }
13966 
13967   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13968     S.DiagnoseCommaOperator(LHS.get(), Loc);
13969 
13970   return RHS.get()->getType();
13971 }
13972 
13973 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13974 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13975 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13976                                                ExprValueKind &VK,
13977                                                ExprObjectKind &OK,
13978                                                SourceLocation OpLoc,
13979                                                bool IsInc, bool IsPrefix) {
13980   if (Op->isTypeDependent())
13981     return S.Context.DependentTy;
13982 
13983   QualType ResType = Op->getType();
13984   // Atomic types can be used for increment / decrement where the non-atomic
13985   // versions can, so ignore the _Atomic() specifier for the purpose of
13986   // checking.
13987   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13988     ResType = ResAtomicType->getValueType();
13989 
13990   assert(!ResType.isNull() && "no type for increment/decrement expression");
13991 
13992   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13993     // Decrement of bool is not allowed.
13994     if (!IsInc) {
13995       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13996       return QualType();
13997     }
13998     // Increment of bool sets it to true, but is deprecated.
13999     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14000                                               : diag::warn_increment_bool)
14001       << Op->getSourceRange();
14002   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14003     // Error on enum increments and decrements in C++ mode
14004     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14005     return QualType();
14006   } else if (ResType->isRealType()) {
14007     // OK!
14008   } else if (ResType->isPointerType()) {
14009     // C99 6.5.2.4p2, 6.5.6p2
14010     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14011       return QualType();
14012   } else if (ResType->isObjCObjectPointerType()) {
14013     // On modern runtimes, ObjC pointer arithmetic is forbidden.
14014     // Otherwise, we just need a complete type.
14015     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14016         checkArithmeticOnObjCPointer(S, OpLoc, Op))
14017       return QualType();
14018   } else if (ResType->isAnyComplexType()) {
14019     // C99 does not support ++/-- on complex types, we allow as an extension.
14020     S.Diag(OpLoc, diag::ext_integer_increment_complex)
14021       << ResType << Op->getSourceRange();
14022   } else if (ResType->isPlaceholderType()) {
14023     ExprResult PR = S.CheckPlaceholderExpr(Op);
14024     if (PR.isInvalid()) return QualType();
14025     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14026                                           IsInc, IsPrefix);
14027   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14028     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14029   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14030              (ResType->castAs<VectorType>()->getVectorKind() !=
14031               VectorType::AltiVecBool)) {
14032     // The z vector extensions allow ++ and -- for non-bool vectors.
14033   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
14034             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14035     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14036   } else {
14037     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14038       << ResType << int(IsInc) << Op->getSourceRange();
14039     return QualType();
14040   }
14041   // At this point, we know we have a real, complex or pointer type.
14042   // Now make sure the operand is a modifiable lvalue.
14043   if (CheckForModifiableLvalue(Op, OpLoc, S))
14044     return QualType();
14045   if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14046     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14047     //   An operand with volatile-qualified type is deprecated
14048     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14049         << IsInc << ResType;
14050   }
14051   // In C++, a prefix increment is the same type as the operand. Otherwise
14052   // (in C or with postfix), the increment is the unqualified type of the
14053   // operand.
14054   if (IsPrefix && S.getLangOpts().CPlusPlus) {
14055     VK = VK_LValue;
14056     OK = Op->getObjectKind();
14057     return ResType;
14058   } else {
14059     VK = VK_PRValue;
14060     return ResType.getUnqualifiedType();
14061   }
14062 }
14063 
14064 
14065 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14066 /// This routine allows us to typecheck complex/recursive expressions
14067 /// where the declaration is needed for type checking. We only need to
14068 /// handle cases when the expression references a function designator
14069 /// or is an lvalue. Here are some examples:
14070 ///  - &(x) => x
14071 ///  - &*****f => f for f a function designator.
14072 ///  - &s.xx => s
14073 ///  - &s.zz[1].yy -> s, if zz is an array
14074 ///  - *(x + 1) -> x, if x is an array
14075 ///  - &"123"[2] -> 0
14076 ///  - & __real__ x -> x
14077 ///
14078 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14079 /// members.
14080 static ValueDecl *getPrimaryDecl(Expr *E) {
14081   switch (E->getStmtClass()) {
14082   case Stmt::DeclRefExprClass:
14083     return cast<DeclRefExpr>(E)->getDecl();
14084   case Stmt::MemberExprClass:
14085     // If this is an arrow operator, the address is an offset from
14086     // the base's value, so the object the base refers to is
14087     // irrelevant.
14088     if (cast<MemberExpr>(E)->isArrow())
14089       return nullptr;
14090     // Otherwise, the expression refers to a part of the base
14091     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14092   case Stmt::ArraySubscriptExprClass: {
14093     // FIXME: This code shouldn't be necessary!  We should catch the implicit
14094     // promotion of register arrays earlier.
14095     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14096     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14097       if (ICE->getSubExpr()->getType()->isArrayType())
14098         return getPrimaryDecl(ICE->getSubExpr());
14099     }
14100     return nullptr;
14101   }
14102   case Stmt::UnaryOperatorClass: {
14103     UnaryOperator *UO = cast<UnaryOperator>(E);
14104 
14105     switch(UO->getOpcode()) {
14106     case UO_Real:
14107     case UO_Imag:
14108     case UO_Extension:
14109       return getPrimaryDecl(UO->getSubExpr());
14110     default:
14111       return nullptr;
14112     }
14113   }
14114   case Stmt::ParenExprClass:
14115     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14116   case Stmt::ImplicitCastExprClass:
14117     // If the result of an implicit cast is an l-value, we care about
14118     // the sub-expression; otherwise, the result here doesn't matter.
14119     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14120   case Stmt::CXXUuidofExprClass:
14121     return cast<CXXUuidofExpr>(E)->getGuidDecl();
14122   default:
14123     return nullptr;
14124   }
14125 }
14126 
14127 namespace {
14128 enum {
14129   AO_Bit_Field = 0,
14130   AO_Vector_Element = 1,
14131   AO_Property_Expansion = 2,
14132   AO_Register_Variable = 3,
14133   AO_Matrix_Element = 4,
14134   AO_No_Error = 5
14135 };
14136 }
14137 /// Diagnose invalid operand for address of operations.
14138 ///
14139 /// \param Type The type of operand which cannot have its address taken.
14140 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14141                                          Expr *E, unsigned Type) {
14142   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14143 }
14144 
14145 /// CheckAddressOfOperand - The operand of & must be either a function
14146 /// designator or an lvalue designating an object. If it is an lvalue, the
14147 /// object cannot be declared with storage class register or be a bit field.
14148 /// Note: The usual conversions are *not* applied to the operand of the &
14149 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14150 /// In C++, the operand might be an overloaded function name, in which case
14151 /// we allow the '&' but retain the overloaded-function type.
14152 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
14153   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14154     if (PTy->getKind() == BuiltinType::Overload) {
14155       Expr *E = OrigOp.get()->IgnoreParens();
14156       if (!isa<OverloadExpr>(E)) {
14157         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14158         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14159           << OrigOp.get()->getSourceRange();
14160         return QualType();
14161       }
14162 
14163       OverloadExpr *Ovl = cast<OverloadExpr>(E);
14164       if (isa<UnresolvedMemberExpr>(Ovl))
14165         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
14166           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14167             << OrigOp.get()->getSourceRange();
14168           return QualType();
14169         }
14170 
14171       return Context.OverloadTy;
14172     }
14173 
14174     if (PTy->getKind() == BuiltinType::UnknownAny)
14175       return Context.UnknownAnyTy;
14176 
14177     if (PTy->getKind() == BuiltinType::BoundMember) {
14178       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14179         << OrigOp.get()->getSourceRange();
14180       return QualType();
14181     }
14182 
14183     OrigOp = CheckPlaceholderExpr(OrigOp.get());
14184     if (OrigOp.isInvalid()) return QualType();
14185   }
14186 
14187   if (OrigOp.get()->isTypeDependent())
14188     return Context.DependentTy;
14189 
14190   assert(!OrigOp.get()->hasPlaceholderType());
14191 
14192   // Make sure to ignore parentheses in subsequent checks
14193   Expr *op = OrigOp.get()->IgnoreParens();
14194 
14195   // In OpenCL captures for blocks called as lambda functions
14196   // are located in the private address space. Blocks used in
14197   // enqueue_kernel can be located in a different address space
14198   // depending on a vendor implementation. Thus preventing
14199   // taking an address of the capture to avoid invalid AS casts.
14200   if (LangOpts.OpenCL) {
14201     auto* VarRef = dyn_cast<DeclRefExpr>(op);
14202     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14203       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14204       return QualType();
14205     }
14206   }
14207 
14208   if (getLangOpts().C99) {
14209     // Implement C99-only parts of addressof rules.
14210     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14211       if (uOp->getOpcode() == UO_Deref)
14212         // Per C99 6.5.3.2, the address of a deref always returns a valid result
14213         // (assuming the deref expression is valid).
14214         return uOp->getSubExpr()->getType();
14215     }
14216     // Technically, there should be a check for array subscript
14217     // expressions here, but the result of one is always an lvalue anyway.
14218   }
14219   ValueDecl *dcl = getPrimaryDecl(op);
14220 
14221   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14222     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14223                                            op->getBeginLoc()))
14224       return QualType();
14225 
14226   Expr::LValueClassification lval = op->ClassifyLValue(Context);
14227   unsigned AddressOfError = AO_No_Error;
14228 
14229   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14230     bool sfinae = (bool)isSFINAEContext();
14231     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14232                                   : diag::ext_typecheck_addrof_temporary)
14233       << op->getType() << op->getSourceRange();
14234     if (sfinae)
14235       return QualType();
14236     // Materialize the temporary as an lvalue so that we can take its address.
14237     OrigOp = op =
14238         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14239   } else if (isa<ObjCSelectorExpr>(op)) {
14240     return Context.getPointerType(op->getType());
14241   } else if (lval == Expr::LV_MemberFunction) {
14242     // If it's an instance method, make a member pointer.
14243     // The expression must have exactly the form &A::foo.
14244 
14245     // If the underlying expression isn't a decl ref, give up.
14246     if (!isa<DeclRefExpr>(op)) {
14247       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14248         << OrigOp.get()->getSourceRange();
14249       return QualType();
14250     }
14251     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14252     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14253 
14254     // The id-expression was parenthesized.
14255     if (OrigOp.get() != DRE) {
14256       Diag(OpLoc, diag::err_parens_pointer_member_function)
14257         << OrigOp.get()->getSourceRange();
14258 
14259     // The method was named without a qualifier.
14260     } else if (!DRE->getQualifier()) {
14261       if (MD->getParent()->getName().empty())
14262         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14263           << op->getSourceRange();
14264       else {
14265         SmallString<32> Str;
14266         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14267         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14268           << op->getSourceRange()
14269           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
14270       }
14271     }
14272 
14273     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14274     if (isa<CXXDestructorDecl>(MD))
14275       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
14276 
14277     QualType MPTy = Context.getMemberPointerType(
14278         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
14279     // Under the MS ABI, lock down the inheritance model now.
14280     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14281       (void)isCompleteType(OpLoc, MPTy);
14282     return MPTy;
14283   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14284     // C99 6.5.3.2p1
14285     // The operand must be either an l-value or a function designator
14286     if (!op->getType()->isFunctionType()) {
14287       // Use a special diagnostic for loads from property references.
14288       if (isa<PseudoObjectExpr>(op)) {
14289         AddressOfError = AO_Property_Expansion;
14290       } else {
14291         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14292           << op->getType() << op->getSourceRange();
14293         return QualType();
14294       }
14295     }
14296   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14297     // The operand cannot be a bit-field
14298     AddressOfError = AO_Bit_Field;
14299   } else if (op->getObjectKind() == OK_VectorComponent) {
14300     // The operand cannot be an element of a vector
14301     AddressOfError = AO_Vector_Element;
14302   } else if (op->getObjectKind() == OK_MatrixComponent) {
14303     // The operand cannot be an element of a matrix.
14304     AddressOfError = AO_Matrix_Element;
14305   } else if (dcl) { // C99 6.5.3.2p1
14306     // We have an lvalue with a decl. Make sure the decl is not declared
14307     // with the register storage-class specifier.
14308     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14309       // in C++ it is not error to take address of a register
14310       // variable (c++03 7.1.1P3)
14311       if (vd->getStorageClass() == SC_Register &&
14312           !getLangOpts().CPlusPlus) {
14313         AddressOfError = AO_Register_Variable;
14314       }
14315     } else if (isa<MSPropertyDecl>(dcl)) {
14316       AddressOfError = AO_Property_Expansion;
14317     } else if (isa<FunctionTemplateDecl>(dcl)) {
14318       return Context.OverloadTy;
14319     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14320       // Okay: we can take the address of a field.
14321       // Could be a pointer to member, though, if there is an explicit
14322       // scope qualifier for the class.
14323       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14324         DeclContext *Ctx = dcl->getDeclContext();
14325         if (Ctx && Ctx->isRecord()) {
14326           if (dcl->getType()->isReferenceType()) {
14327             Diag(OpLoc,
14328                  diag::err_cannot_form_pointer_to_member_of_reference_type)
14329               << dcl->getDeclName() << dcl->getType();
14330             return QualType();
14331           }
14332 
14333           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14334             Ctx = Ctx->getParent();
14335 
14336           QualType MPTy = Context.getMemberPointerType(
14337               op->getType(),
14338               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14339           // Under the MS ABI, lock down the inheritance model now.
14340           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14341             (void)isCompleteType(OpLoc, MPTy);
14342           return MPTy;
14343         }
14344       }
14345     } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14346                     MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))
14347       llvm_unreachable("Unknown/unexpected decl type");
14348   }
14349 
14350   if (AddressOfError != AO_No_Error) {
14351     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14352     return QualType();
14353   }
14354 
14355   if (lval == Expr::LV_IncompleteVoidType) {
14356     // Taking the address of a void variable is technically illegal, but we
14357     // allow it in cases which are otherwise valid.
14358     // Example: "extern void x; void* y = &x;".
14359     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14360   }
14361 
14362   // If the operand has type "type", the result has type "pointer to type".
14363   if (op->getType()->isObjCObjectType())
14364     return Context.getObjCObjectPointerType(op->getType());
14365 
14366   CheckAddressOfPackedMember(op);
14367 
14368   return Context.getPointerType(op->getType());
14369 }
14370 
14371 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14372   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14373   if (!DRE)
14374     return;
14375   const Decl *D = DRE->getDecl();
14376   if (!D)
14377     return;
14378   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14379   if (!Param)
14380     return;
14381   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14382     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14383       return;
14384   if (FunctionScopeInfo *FD = S.getCurFunction())
14385     if (!FD->ModifiedNonNullParams.count(Param))
14386       FD->ModifiedNonNullParams.insert(Param);
14387 }
14388 
14389 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14390 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14391                                         SourceLocation OpLoc) {
14392   if (Op->isTypeDependent())
14393     return S.Context.DependentTy;
14394 
14395   ExprResult ConvResult = S.UsualUnaryConversions(Op);
14396   if (ConvResult.isInvalid())
14397     return QualType();
14398   Op = ConvResult.get();
14399   QualType OpTy = Op->getType();
14400   QualType Result;
14401 
14402   if (isa<CXXReinterpretCastExpr>(Op)) {
14403     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14404     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14405                                      Op->getSourceRange());
14406   }
14407 
14408   if (const PointerType *PT = OpTy->getAs<PointerType>())
14409   {
14410     Result = PT->getPointeeType();
14411   }
14412   else if (const ObjCObjectPointerType *OPT =
14413              OpTy->getAs<ObjCObjectPointerType>())
14414     Result = OPT->getPointeeType();
14415   else {
14416     ExprResult PR = S.CheckPlaceholderExpr(Op);
14417     if (PR.isInvalid()) return QualType();
14418     if (PR.get() != Op)
14419       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14420   }
14421 
14422   if (Result.isNull()) {
14423     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14424       << OpTy << Op->getSourceRange();
14425     return QualType();
14426   }
14427 
14428   // Note that per both C89 and C99, indirection is always legal, even if Result
14429   // is an incomplete type or void.  It would be possible to warn about
14430   // dereferencing a void pointer, but it's completely well-defined, and such a
14431   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
14432   // for pointers to 'void' but is fine for any other pointer type:
14433   //
14434   // C++ [expr.unary.op]p1:
14435   //   [...] the expression to which [the unary * operator] is applied shall
14436   //   be a pointer to an object type, or a pointer to a function type
14437   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
14438     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14439       << OpTy << Op->getSourceRange();
14440 
14441   // Dereferences are usually l-values...
14442   VK = VK_LValue;
14443 
14444   // ...except that certain expressions are never l-values in C.
14445   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14446     VK = VK_PRValue;
14447 
14448   return Result;
14449 }
14450 
14451 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14452   BinaryOperatorKind Opc;
14453   switch (Kind) {
14454   default: llvm_unreachable("Unknown binop!");
14455   case tok::periodstar:           Opc = BO_PtrMemD; break;
14456   case tok::arrowstar:            Opc = BO_PtrMemI; break;
14457   case tok::star:                 Opc = BO_Mul; break;
14458   case tok::slash:                Opc = BO_Div; break;
14459   case tok::percent:              Opc = BO_Rem; break;
14460   case tok::plus:                 Opc = BO_Add; break;
14461   case tok::minus:                Opc = BO_Sub; break;
14462   case tok::lessless:             Opc = BO_Shl; break;
14463   case tok::greatergreater:       Opc = BO_Shr; break;
14464   case tok::lessequal:            Opc = BO_LE; break;
14465   case tok::less:                 Opc = BO_LT; break;
14466   case tok::greaterequal:         Opc = BO_GE; break;
14467   case tok::greater:              Opc = BO_GT; break;
14468   case tok::exclaimequal:         Opc = BO_NE; break;
14469   case tok::equalequal:           Opc = BO_EQ; break;
14470   case tok::spaceship:            Opc = BO_Cmp; break;
14471   case tok::amp:                  Opc = BO_And; break;
14472   case tok::caret:                Opc = BO_Xor; break;
14473   case tok::pipe:                 Opc = BO_Or; break;
14474   case tok::ampamp:               Opc = BO_LAnd; break;
14475   case tok::pipepipe:             Opc = BO_LOr; break;
14476   case tok::equal:                Opc = BO_Assign; break;
14477   case tok::starequal:            Opc = BO_MulAssign; break;
14478   case tok::slashequal:           Opc = BO_DivAssign; break;
14479   case tok::percentequal:         Opc = BO_RemAssign; break;
14480   case tok::plusequal:            Opc = BO_AddAssign; break;
14481   case tok::minusequal:           Opc = BO_SubAssign; break;
14482   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
14483   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
14484   case tok::ampequal:             Opc = BO_AndAssign; break;
14485   case tok::caretequal:           Opc = BO_XorAssign; break;
14486   case tok::pipeequal:            Opc = BO_OrAssign; break;
14487   case tok::comma:                Opc = BO_Comma; break;
14488   }
14489   return Opc;
14490 }
14491 
14492 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14493   tok::TokenKind Kind) {
14494   UnaryOperatorKind Opc;
14495   switch (Kind) {
14496   default: llvm_unreachable("Unknown unary op!");
14497   case tok::plusplus:     Opc = UO_PreInc; break;
14498   case tok::minusminus:   Opc = UO_PreDec; break;
14499   case tok::amp:          Opc = UO_AddrOf; break;
14500   case tok::star:         Opc = UO_Deref; break;
14501   case tok::plus:         Opc = UO_Plus; break;
14502   case tok::minus:        Opc = UO_Minus; break;
14503   case tok::tilde:        Opc = UO_Not; break;
14504   case tok::exclaim:      Opc = UO_LNot; break;
14505   case tok::kw___real:    Opc = UO_Real; break;
14506   case tok::kw___imag:    Opc = UO_Imag; break;
14507   case tok::kw___extension__: Opc = UO_Extension; break;
14508   }
14509   return Opc;
14510 }
14511 
14512 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14513 /// This warning suppressed in the event of macro expansions.
14514 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14515                                    SourceLocation OpLoc, bool IsBuiltin) {
14516   if (S.inTemplateInstantiation())
14517     return;
14518   if (S.isUnevaluatedContext())
14519     return;
14520   if (OpLoc.isInvalid() || OpLoc.isMacroID())
14521     return;
14522   LHSExpr = LHSExpr->IgnoreParenImpCasts();
14523   RHSExpr = RHSExpr->IgnoreParenImpCasts();
14524   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14525   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14526   if (!LHSDeclRef || !RHSDeclRef ||
14527       LHSDeclRef->getLocation().isMacroID() ||
14528       RHSDeclRef->getLocation().isMacroID())
14529     return;
14530   const ValueDecl *LHSDecl =
14531     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14532   const ValueDecl *RHSDecl =
14533     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14534   if (LHSDecl != RHSDecl)
14535     return;
14536   if (LHSDecl->getType().isVolatileQualified())
14537     return;
14538   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14539     if (RefTy->getPointeeType().isVolatileQualified())
14540       return;
14541 
14542   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14543                           : diag::warn_self_assignment_overloaded)
14544       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14545       << RHSExpr->getSourceRange();
14546 }
14547 
14548 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
14549 /// is usually indicative of introspection within the Objective-C pointer.
14550 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
14551                                           SourceLocation OpLoc) {
14552   if (!S.getLangOpts().ObjC)
14553     return;
14554 
14555   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14556   const Expr *LHS = L.get();
14557   const Expr *RHS = R.get();
14558 
14559   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14560     ObjCPointerExpr = LHS;
14561     OtherExpr = RHS;
14562   }
14563   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14564     ObjCPointerExpr = RHS;
14565     OtherExpr = LHS;
14566   }
14567 
14568   // This warning is deliberately made very specific to reduce false
14569   // positives with logic that uses '&' for hashing.  This logic mainly
14570   // looks for code trying to introspect into tagged pointers, which
14571   // code should generally never do.
14572   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14573     unsigned Diag = diag::warn_objc_pointer_masking;
14574     // Determine if we are introspecting the result of performSelectorXXX.
14575     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14576     // Special case messages to -performSelector and friends, which
14577     // can return non-pointer values boxed in a pointer value.
14578     // Some clients may wish to silence warnings in this subcase.
14579     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14580       Selector S = ME->getSelector();
14581       StringRef SelArg0 = S.getNameForSlot(0);
14582       if (SelArg0.startswith("performSelector"))
14583         Diag = diag::warn_objc_pointer_masking_performSelector;
14584     }
14585 
14586     S.Diag(OpLoc, Diag)
14587       << ObjCPointerExpr->getSourceRange();
14588   }
14589 }
14590 
14591 static NamedDecl *getDeclFromExpr(Expr *E) {
14592   if (!E)
14593     return nullptr;
14594   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14595     return DRE->getDecl();
14596   if (auto *ME = dyn_cast<MemberExpr>(E))
14597     return ME->getMemberDecl();
14598   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14599     return IRE->getDecl();
14600   return nullptr;
14601 }
14602 
14603 // This helper function promotes a binary operator's operands (which are of a
14604 // half vector type) to a vector of floats and then truncates the result to
14605 // a vector of either half or short.
14606 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14607                                       BinaryOperatorKind Opc, QualType ResultTy,
14608                                       ExprValueKind VK, ExprObjectKind OK,
14609                                       bool IsCompAssign, SourceLocation OpLoc,
14610                                       FPOptionsOverride FPFeatures) {
14611   auto &Context = S.getASTContext();
14612   assert((isVector(ResultTy, Context.HalfTy) ||
14613           isVector(ResultTy, Context.ShortTy)) &&
14614          "Result must be a vector of half or short");
14615   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14616          isVector(RHS.get()->getType(), Context.HalfTy) &&
14617          "both operands expected to be a half vector");
14618 
14619   RHS = convertVector(RHS.get(), Context.FloatTy, S);
14620   QualType BinOpResTy = RHS.get()->getType();
14621 
14622   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14623   // change BinOpResTy to a vector of ints.
14624   if (isVector(ResultTy, Context.ShortTy))
14625     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14626 
14627   if (IsCompAssign)
14628     return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14629                                           ResultTy, VK, OK, OpLoc, FPFeatures,
14630                                           BinOpResTy, BinOpResTy);
14631 
14632   LHS = convertVector(LHS.get(), Context.FloatTy, S);
14633   auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14634                                     BinOpResTy, VK, OK, OpLoc, FPFeatures);
14635   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14636 }
14637 
14638 static std::pair<ExprResult, ExprResult>
14639 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
14640                            Expr *RHSExpr) {
14641   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14642   if (!S.Context.isDependenceAllowed()) {
14643     // C cannot handle TypoExpr nodes on either side of a binop because it
14644     // doesn't handle dependent types properly, so make sure any TypoExprs have
14645     // been dealt with before checking the operands.
14646     LHS = S.CorrectDelayedTyposInExpr(LHS);
14647     RHS = S.CorrectDelayedTyposInExpr(
14648         RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14649         [Opc, LHS](Expr *E) {
14650           if (Opc != BO_Assign)
14651             return ExprResult(E);
14652           // Avoid correcting the RHS to the same Expr as the LHS.
14653           Decl *D = getDeclFromExpr(E);
14654           return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14655         });
14656   }
14657   return std::make_pair(LHS, RHS);
14658 }
14659 
14660 /// Returns true if conversion between vectors of halfs and vectors of floats
14661 /// is needed.
14662 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14663                                      Expr *E0, Expr *E1 = nullptr) {
14664   if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14665       Ctx.getTargetInfo().useFP16ConversionIntrinsics())
14666     return false;
14667 
14668   auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14669     QualType Ty = E->IgnoreImplicit()->getType();
14670 
14671     // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14672     // to vectors of floats. Although the element type of the vectors is __fp16,
14673     // the vectors shouldn't be treated as storage-only types. See the
14674     // discussion here: https://reviews.llvm.org/rG825235c140e7
14675     if (const VectorType *VT = Ty->getAs<VectorType>()) {
14676       if (VT->getVectorKind() == VectorType::NeonVector)
14677         return false;
14678       return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14679     }
14680     return false;
14681   };
14682 
14683   return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14684 }
14685 
14686 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
14687 /// operator @p Opc at location @c TokLoc. This routine only supports
14688 /// built-in operations; ActOnBinOp handles overloaded operators.
14689 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
14690                                     BinaryOperatorKind Opc,
14691                                     Expr *LHSExpr, Expr *RHSExpr) {
14692   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14693     // The syntax only allows initializer lists on the RHS of assignment,
14694     // so we don't need to worry about accepting invalid code for
14695     // non-assignment operators.
14696     // C++11 5.17p9:
14697     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14698     //   of x = {} is x = T().
14699     InitializationKind Kind = InitializationKind::CreateDirectList(
14700         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14701     InitializedEntity Entity =
14702         InitializedEntity::InitializeTemporary(LHSExpr->getType());
14703     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14704     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14705     if (Init.isInvalid())
14706       return Init;
14707     RHSExpr = Init.get();
14708   }
14709 
14710   ExprResult LHS = LHSExpr, RHS = RHSExpr;
14711   QualType ResultTy;     // Result type of the binary operator.
14712   // The following two variables are used for compound assignment operators
14713   QualType CompLHSTy;    // Type of LHS after promotions for computation
14714   QualType CompResultTy; // Type of computation result
14715   ExprValueKind VK = VK_PRValue;
14716   ExprObjectKind OK = OK_Ordinary;
14717   bool ConvertHalfVec = false;
14718 
14719   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14720   if (!LHS.isUsable() || !RHS.isUsable())
14721     return ExprError();
14722 
14723   if (getLangOpts().OpenCL) {
14724     QualType LHSTy = LHSExpr->getType();
14725     QualType RHSTy = RHSExpr->getType();
14726     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14727     // the ATOMIC_VAR_INIT macro.
14728     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14729       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14730       if (BO_Assign == Opc)
14731         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14732       else
14733         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14734       return ExprError();
14735     }
14736 
14737     // OpenCL special types - image, sampler, pipe, and blocks are to be used
14738     // only with a builtin functions and therefore should be disallowed here.
14739     if (LHSTy->isImageType() || RHSTy->isImageType() ||
14740         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14741         LHSTy->isPipeType() || RHSTy->isPipeType() ||
14742         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14743       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14744       return ExprError();
14745     }
14746   }
14747 
14748   checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14749   checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14750 
14751   switch (Opc) {
14752   case BO_Assign:
14753     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14754     if (getLangOpts().CPlusPlus &&
14755         LHS.get()->getObjectKind() != OK_ObjCProperty) {
14756       VK = LHS.get()->getValueKind();
14757       OK = LHS.get()->getObjectKind();
14758     }
14759     if (!ResultTy.isNull()) {
14760       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14761       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14762 
14763       // Avoid copying a block to the heap if the block is assigned to a local
14764       // auto variable that is declared in the same scope as the block. This
14765       // optimization is unsafe if the local variable is declared in an outer
14766       // scope. For example:
14767       //
14768       // BlockTy b;
14769       // {
14770       //   b = ^{...};
14771       // }
14772       // // It is unsafe to invoke the block here if it wasn't copied to the
14773       // // heap.
14774       // b();
14775 
14776       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14777         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14778           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14779             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14780               BE->getBlockDecl()->setCanAvoidCopyToHeap();
14781 
14782       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14783         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14784                               NTCUC_Assignment, NTCUK_Copy);
14785     }
14786     RecordModifiableNonNullParam(*this, LHS.get());
14787     break;
14788   case BO_PtrMemD:
14789   case BO_PtrMemI:
14790     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14791                                             Opc == BO_PtrMemI);
14792     break;
14793   case BO_Mul:
14794   case BO_Div:
14795     ConvertHalfVec = true;
14796     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14797                                            Opc == BO_Div);
14798     break;
14799   case BO_Rem:
14800     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14801     break;
14802   case BO_Add:
14803     ConvertHalfVec = true;
14804     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14805     break;
14806   case BO_Sub:
14807     ConvertHalfVec = true;
14808     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14809     break;
14810   case BO_Shl:
14811   case BO_Shr:
14812     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14813     break;
14814   case BO_LE:
14815   case BO_LT:
14816   case BO_GE:
14817   case BO_GT:
14818     ConvertHalfVec = true;
14819     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14820     break;
14821   case BO_EQ:
14822   case BO_NE:
14823     ConvertHalfVec = true;
14824     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14825     break;
14826   case BO_Cmp:
14827     ConvertHalfVec = true;
14828     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14829     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14830     break;
14831   case BO_And:
14832     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14833     LLVM_FALLTHROUGH;
14834   case BO_Xor:
14835   case BO_Or:
14836     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14837     break;
14838   case BO_LAnd:
14839   case BO_LOr:
14840     ConvertHalfVec = true;
14841     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14842     break;
14843   case BO_MulAssign:
14844   case BO_DivAssign:
14845     ConvertHalfVec = true;
14846     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14847                                                Opc == BO_DivAssign);
14848     CompLHSTy = CompResultTy;
14849     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14850       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14851     break;
14852   case BO_RemAssign:
14853     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14854     CompLHSTy = CompResultTy;
14855     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14856       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14857     break;
14858   case BO_AddAssign:
14859     ConvertHalfVec = true;
14860     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14861     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14862       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14863     break;
14864   case BO_SubAssign:
14865     ConvertHalfVec = true;
14866     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14867     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14868       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14869     break;
14870   case BO_ShlAssign:
14871   case BO_ShrAssign:
14872     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14873     CompLHSTy = CompResultTy;
14874     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14875       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14876     break;
14877   case BO_AndAssign:
14878   case BO_OrAssign: // fallthrough
14879     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14880     LLVM_FALLTHROUGH;
14881   case BO_XorAssign:
14882     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14883     CompLHSTy = CompResultTy;
14884     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14885       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14886     break;
14887   case BO_Comma:
14888     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14889     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14890       VK = RHS.get()->getValueKind();
14891       OK = RHS.get()->getObjectKind();
14892     }
14893     break;
14894   }
14895   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14896     return ExprError();
14897 
14898   // Some of the binary operations require promoting operands of half vector to
14899   // float vectors and truncating the result back to half vector. For now, we do
14900   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14901   // arm64).
14902   assert(
14903       (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14904                               isVector(LHS.get()->getType(), Context.HalfTy)) &&
14905       "both sides are half vectors or neither sides are");
14906   ConvertHalfVec =
14907       needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14908 
14909   // Check for array bounds violations for both sides of the BinaryOperator
14910   CheckArrayAccess(LHS.get());
14911   CheckArrayAccess(RHS.get());
14912 
14913   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14914     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14915                                                  &Context.Idents.get("object_setClass"),
14916                                                  SourceLocation(), LookupOrdinaryName);
14917     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14918       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14919       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14920           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14921                                         "object_setClass(")
14922           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14923                                           ",")
14924           << FixItHint::CreateInsertion(RHSLocEnd, ")");
14925     }
14926     else
14927       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14928   }
14929   else if (const ObjCIvarRefExpr *OIRE =
14930            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14931     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14932 
14933   // Opc is not a compound assignment if CompResultTy is null.
14934   if (CompResultTy.isNull()) {
14935     if (ConvertHalfVec)
14936       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14937                                  OpLoc, CurFPFeatureOverrides());
14938     return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14939                                   VK, OK, OpLoc, CurFPFeatureOverrides());
14940   }
14941 
14942   // Handle compound assignments.
14943   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14944       OK_ObjCProperty) {
14945     VK = VK_LValue;
14946     OK = LHS.get()->getObjectKind();
14947   }
14948 
14949   // The LHS is not converted to the result type for fixed-point compound
14950   // assignment as the common type is computed on demand. Reset the CompLHSTy
14951   // to the LHS type we would have gotten after unary conversions.
14952   if (CompResultTy->isFixedPointType())
14953     CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14954 
14955   if (ConvertHalfVec)
14956     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14957                                OpLoc, CurFPFeatureOverrides());
14958 
14959   return CompoundAssignOperator::Create(
14960       Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14961       CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14962 }
14963 
14964 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14965 /// operators are mixed in a way that suggests that the programmer forgot that
14966 /// comparison operators have higher precedence. The most typical example of
14967 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14968 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14969                                       SourceLocation OpLoc, Expr *LHSExpr,
14970                                       Expr *RHSExpr) {
14971   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14972   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14973 
14974   // Check that one of the sides is a comparison operator and the other isn't.
14975   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14976   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14977   if (isLeftComp == isRightComp)
14978     return;
14979 
14980   // Bitwise operations are sometimes used as eager logical ops.
14981   // Don't diagnose this.
14982   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14983   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14984   if (isLeftBitwise || isRightBitwise)
14985     return;
14986 
14987   SourceRange DiagRange = isLeftComp
14988                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14989                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
14990   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14991   SourceRange ParensRange =
14992       isLeftComp
14993           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14994           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14995 
14996   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14997     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14998   SuggestParentheses(Self, OpLoc,
14999     Self.PDiag(diag::note_precedence_silence) << OpStr,
15000     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15001   SuggestParentheses(Self, OpLoc,
15002     Self.PDiag(diag::note_precedence_bitwise_first)
15003       << BinaryOperator::getOpcodeStr(Opc),
15004     ParensRange);
15005 }
15006 
15007 /// It accepts a '&&' expr that is inside a '||' one.
15008 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15009 /// in parentheses.
15010 static void
15011 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
15012                                        BinaryOperator *Bop) {
15013   assert(Bop->getOpcode() == BO_LAnd);
15014   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15015       << Bop->getSourceRange() << OpLoc;
15016   SuggestParentheses(Self, Bop->getOperatorLoc(),
15017     Self.PDiag(diag::note_precedence_silence)
15018       << Bop->getOpcodeStr(),
15019     Bop->getSourceRange());
15020 }
15021 
15022 /// Returns true if the given expression can be evaluated as a constant
15023 /// 'true'.
15024 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
15025   bool Res;
15026   return !E->isValueDependent() &&
15027          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
15028 }
15029 
15030 /// Returns true if the given expression can be evaluated as a constant
15031 /// 'false'.
15032 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
15033   bool Res;
15034   return !E->isValueDependent() &&
15035          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
15036 }
15037 
15038 /// Look for '&&' in the left hand of a '||' expr.
15039 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15040                                              Expr *LHSExpr, Expr *RHSExpr) {
15041   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15042     if (Bop->getOpcode() == BO_LAnd) {
15043       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
15044       if (EvaluatesAsFalse(S, RHSExpr))
15045         return;
15046       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
15047       if (!EvaluatesAsTrue(S, Bop->getLHS()))
15048         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15049     } else if (Bop->getOpcode() == BO_LOr) {
15050       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15051         // If it's "a || b && 1 || c" we didn't warn earlier for
15052         // "a || b && 1", but warn now.
15053         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
15054           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15055       }
15056     }
15057   }
15058 }
15059 
15060 /// Look for '&&' in the right hand of a '||' expr.
15061 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15062                                              Expr *LHSExpr, Expr *RHSExpr) {
15063   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15064     if (Bop->getOpcode() == BO_LAnd) {
15065       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
15066       if (EvaluatesAsFalse(S, LHSExpr))
15067         return;
15068       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
15069       if (!EvaluatesAsTrue(S, Bop->getRHS()))
15070         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15071     }
15072   }
15073 }
15074 
15075 /// Look for bitwise op in the left or right hand of a bitwise op with
15076 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15077 /// the '&' expression in parentheses.
15078 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15079                                          SourceLocation OpLoc, Expr *SubExpr) {
15080   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15081     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15082       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15083         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15084         << Bop->getSourceRange() << OpLoc;
15085       SuggestParentheses(S, Bop->getOperatorLoc(),
15086         S.PDiag(diag::note_precedence_silence)
15087           << Bop->getOpcodeStr(),
15088         Bop->getSourceRange());
15089     }
15090   }
15091 }
15092 
15093 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15094                                     Expr *SubExpr, StringRef Shift) {
15095   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15096     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15097       StringRef Op = Bop->getOpcodeStr();
15098       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15099           << Bop->getSourceRange() << OpLoc << Shift << Op;
15100       SuggestParentheses(S, Bop->getOperatorLoc(),
15101           S.PDiag(diag::note_precedence_silence) << Op,
15102           Bop->getSourceRange());
15103     }
15104   }
15105 }
15106 
15107 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15108                                  Expr *LHSExpr, Expr *RHSExpr) {
15109   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15110   if (!OCE)
15111     return;
15112 
15113   FunctionDecl *FD = OCE->getDirectCallee();
15114   if (!FD || !FD->isOverloadedOperator())
15115     return;
15116 
15117   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
15118   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15119     return;
15120 
15121   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15122       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15123       << (Kind == OO_LessLess);
15124   SuggestParentheses(S, OCE->getOperatorLoc(),
15125                      S.PDiag(diag::note_precedence_silence)
15126                          << (Kind == OO_LessLess ? "<<" : ">>"),
15127                      OCE->getSourceRange());
15128   SuggestParentheses(
15129       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15130       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15131 }
15132 
15133 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15134 /// precedence.
15135 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15136                                     SourceLocation OpLoc, Expr *LHSExpr,
15137                                     Expr *RHSExpr){
15138   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15139   if (BinaryOperator::isBitwiseOp(Opc))
15140     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15141 
15142   // Diagnose "arg1 & arg2 | arg3"
15143   if ((Opc == BO_Or || Opc == BO_Xor) &&
15144       !OpLoc.isMacroID()/* Don't warn in macros. */) {
15145     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15146     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15147   }
15148 
15149   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15150   // We don't warn for 'assert(a || b && "bad")' since this is safe.
15151   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15152     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15153     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15154   }
15155 
15156   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15157       || Opc == BO_Shr) {
15158     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15159     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15160     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15161   }
15162 
15163   // Warn on overloaded shift operators and comparisons, such as:
15164   // cout << 5 == 4;
15165   if (BinaryOperator::isComparisonOp(Opc))
15166     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15167 }
15168 
15169 // Binary Operators.  'Tok' is the token for the operator.
15170 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
15171                             tok::TokenKind Kind,
15172                             Expr *LHSExpr, Expr *RHSExpr) {
15173   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15174   assert(LHSExpr && "ActOnBinOp(): missing left expression");
15175   assert(RHSExpr && "ActOnBinOp(): missing right expression");
15176 
15177   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15178   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15179 
15180   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15181 }
15182 
15183 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15184                        UnresolvedSetImpl &Functions) {
15185   OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15186   if (OverOp != OO_None && OverOp != OO_Equal)
15187     LookupOverloadedOperatorName(OverOp, S, Functions);
15188 
15189   // In C++20 onwards, we may have a second operator to look up.
15190   if (getLangOpts().CPlusPlus20) {
15191     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
15192       LookupOverloadedOperatorName(ExtraOp, S, Functions);
15193   }
15194 }
15195 
15196 /// Build an overloaded binary operator expression in the given scope.
15197 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15198                                        BinaryOperatorKind Opc,
15199                                        Expr *LHS, Expr *RHS) {
15200   switch (Opc) {
15201   case BO_Assign:
15202   case BO_DivAssign:
15203   case BO_RemAssign:
15204   case BO_SubAssign:
15205   case BO_AndAssign:
15206   case BO_OrAssign:
15207   case BO_XorAssign:
15208     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15209     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15210     break;
15211   default:
15212     break;
15213   }
15214 
15215   // Find all of the overloaded operators visible from this point.
15216   UnresolvedSet<16> Functions;
15217   S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15218 
15219   // Build the (potentially-overloaded, potentially-dependent)
15220   // binary operation.
15221   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15222 }
15223 
15224 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15225                             BinaryOperatorKind Opc,
15226                             Expr *LHSExpr, Expr *RHSExpr) {
15227   ExprResult LHS, RHS;
15228   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15229   if (!LHS.isUsable() || !RHS.isUsable())
15230     return ExprError();
15231   LHSExpr = LHS.get();
15232   RHSExpr = RHS.get();
15233 
15234   // We want to end up calling one of checkPseudoObjectAssignment
15235   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15236   // both expressions are overloadable or either is type-dependent),
15237   // or CreateBuiltinBinOp (in any other case).  We also want to get
15238   // any placeholder types out of the way.
15239 
15240   // Handle pseudo-objects in the LHS.
15241   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15242     // Assignments with a pseudo-object l-value need special analysis.
15243     if (pty->getKind() == BuiltinType::PseudoObject &&
15244         BinaryOperator::isAssignmentOp(Opc))
15245       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15246 
15247     // Don't resolve overloads if the other type is overloadable.
15248     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15249       // We can't actually test that if we still have a placeholder,
15250       // though.  Fortunately, none of the exceptions we see in that
15251       // code below are valid when the LHS is an overload set.  Note
15252       // that an overload set can be dependently-typed, but it never
15253       // instantiates to having an overloadable type.
15254       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15255       if (resolvedRHS.isInvalid()) return ExprError();
15256       RHSExpr = resolvedRHS.get();
15257 
15258       if (RHSExpr->isTypeDependent() ||
15259           RHSExpr->getType()->isOverloadableType())
15260         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15261     }
15262 
15263     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15264     // template, diagnose the missing 'template' keyword instead of diagnosing
15265     // an invalid use of a bound member function.
15266     //
15267     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15268     // to C++1z [over.over]/1.4, but we already checked for that case above.
15269     if (Opc == BO_LT && inTemplateInstantiation() &&
15270         (pty->getKind() == BuiltinType::BoundMember ||
15271          pty->getKind() == BuiltinType::Overload)) {
15272       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15273       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15274           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
15275             return isa<FunctionTemplateDecl>(ND);
15276           })) {
15277         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15278                                 : OE->getNameLoc(),
15279              diag::err_template_kw_missing)
15280           << OE->getName().getAsString() << "";
15281         return ExprError();
15282       }
15283     }
15284 
15285     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15286     if (LHS.isInvalid()) return ExprError();
15287     LHSExpr = LHS.get();
15288   }
15289 
15290   // Handle pseudo-objects in the RHS.
15291   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15292     // An overload in the RHS can potentially be resolved by the type
15293     // being assigned to.
15294     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15295       if (getLangOpts().CPlusPlus &&
15296           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15297            LHSExpr->getType()->isOverloadableType()))
15298         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15299 
15300       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15301     }
15302 
15303     // Don't resolve overloads if the other type is overloadable.
15304     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15305         LHSExpr->getType()->isOverloadableType())
15306       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15307 
15308     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15309     if (!resolvedRHS.isUsable()) return ExprError();
15310     RHSExpr = resolvedRHS.get();
15311   }
15312 
15313   if (getLangOpts().CPlusPlus) {
15314     // If either expression is type-dependent, always build an
15315     // overloaded op.
15316     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15317       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15318 
15319     // Otherwise, build an overloaded op if either expression has an
15320     // overloadable type.
15321     if (LHSExpr->getType()->isOverloadableType() ||
15322         RHSExpr->getType()->isOverloadableType())
15323       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15324   }
15325 
15326   if (getLangOpts().RecoveryAST &&
15327       (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15328     assert(!getLangOpts().CPlusPlus);
15329     assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15330            "Should only occur in error-recovery path.");
15331     if (BinaryOperator::isCompoundAssignmentOp(Opc))
15332       // C [6.15.16] p3:
15333       // An assignment expression has the value of the left operand after the
15334       // assignment, but is not an lvalue.
15335       return CompoundAssignOperator::Create(
15336           Context, LHSExpr, RHSExpr, Opc,
15337           LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,
15338           OpLoc, CurFPFeatureOverrides());
15339     QualType ResultType;
15340     switch (Opc) {
15341     case BO_Assign:
15342       ResultType = LHSExpr->getType().getUnqualifiedType();
15343       break;
15344     case BO_LT:
15345     case BO_GT:
15346     case BO_LE:
15347     case BO_GE:
15348     case BO_EQ:
15349     case BO_NE:
15350     case BO_LAnd:
15351     case BO_LOr:
15352       // These operators have a fixed result type regardless of operands.
15353       ResultType = Context.IntTy;
15354       break;
15355     case BO_Comma:
15356       ResultType = RHSExpr->getType();
15357       break;
15358     default:
15359       ResultType = Context.DependentTy;
15360       break;
15361     }
15362     return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15363                                   VK_PRValue, OK_Ordinary, OpLoc,
15364                                   CurFPFeatureOverrides());
15365   }
15366 
15367   // Build a built-in binary operation.
15368   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15369 }
15370 
15371 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
15372   if (T.isNull() || T->isDependentType())
15373     return false;
15374 
15375   if (!T->isPromotableIntegerType())
15376     return true;
15377 
15378   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15379 }
15380 
15381 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15382                                       UnaryOperatorKind Opc,
15383                                       Expr *InputExpr) {
15384   ExprResult Input = InputExpr;
15385   ExprValueKind VK = VK_PRValue;
15386   ExprObjectKind OK = OK_Ordinary;
15387   QualType resultType;
15388   bool CanOverflow = false;
15389 
15390   bool ConvertHalfVec = false;
15391   if (getLangOpts().OpenCL) {
15392     QualType Ty = InputExpr->getType();
15393     // The only legal unary operation for atomics is '&'.
15394     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15395     // OpenCL special types - image, sampler, pipe, and blocks are to be used
15396     // only with a builtin functions and therefore should be disallowed here.
15397         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15398         || Ty->isBlockPointerType())) {
15399       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15400                        << InputExpr->getType()
15401                        << Input.get()->getSourceRange());
15402     }
15403   }
15404 
15405   if (getLangOpts().HLSL) {
15406     if (Opc == UO_AddrOf)
15407       return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15408     if (Opc == UO_Deref)
15409       return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15410   }
15411 
15412   switch (Opc) {
15413   case UO_PreInc:
15414   case UO_PreDec:
15415   case UO_PostInc:
15416   case UO_PostDec:
15417     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15418                                                 OpLoc,
15419                                                 Opc == UO_PreInc ||
15420                                                 Opc == UO_PostInc,
15421                                                 Opc == UO_PreInc ||
15422                                                 Opc == UO_PreDec);
15423     CanOverflow = isOverflowingIntegerType(Context, resultType);
15424     break;
15425   case UO_AddrOf:
15426     resultType = CheckAddressOfOperand(Input, OpLoc);
15427     CheckAddressOfNoDeref(InputExpr);
15428     RecordModifiableNonNullParam(*this, InputExpr);
15429     break;
15430   case UO_Deref: {
15431     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15432     if (Input.isInvalid()) return ExprError();
15433     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
15434     break;
15435   }
15436   case UO_Plus:
15437   case UO_Minus:
15438     CanOverflow = Opc == UO_Minus &&
15439                   isOverflowingIntegerType(Context, Input.get()->getType());
15440     Input = UsualUnaryConversions(Input.get());
15441     if (Input.isInvalid()) return ExprError();
15442     // Unary plus and minus require promoting an operand of half vector to a
15443     // float vector and truncating the result back to a half vector. For now, we
15444     // do this only when HalfArgsAndReturns is set (that is, when the target is
15445     // arm or arm64).
15446     ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15447 
15448     // If the operand is a half vector, promote it to a float vector.
15449     if (ConvertHalfVec)
15450       Input = convertVector(Input.get(), Context.FloatTy, *this);
15451     resultType = Input.get()->getType();
15452     if (resultType->isDependentType())
15453       break;
15454     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15455       break;
15456     else if (resultType->isVectorType() &&
15457              // The z vector extensions don't allow + or - with bool vectors.
15458              (!Context.getLangOpts().ZVector ||
15459               resultType->castAs<VectorType>()->getVectorKind() !=
15460               VectorType::AltiVecBool))
15461       break;
15462     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15463              Opc == UO_Plus &&
15464              resultType->isPointerType())
15465       break;
15466 
15467     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15468       << resultType << Input.get()->getSourceRange());
15469 
15470   case UO_Not: // bitwise complement
15471     Input = UsualUnaryConversions(Input.get());
15472     if (Input.isInvalid())
15473       return ExprError();
15474     resultType = Input.get()->getType();
15475     if (resultType->isDependentType())
15476       break;
15477     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15478     if (resultType->isComplexType() || resultType->isComplexIntegerType())
15479       // C99 does not support '~' for complex conjugation.
15480       Diag(OpLoc, diag::ext_integer_complement_complex)
15481           << resultType << Input.get()->getSourceRange();
15482     else if (resultType->hasIntegerRepresentation())
15483       break;
15484     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15485       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15486       // on vector float types.
15487       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15488       if (!T->isIntegerType())
15489         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15490                           << resultType << Input.get()->getSourceRange());
15491     } else {
15492       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15493                        << resultType << Input.get()->getSourceRange());
15494     }
15495     break;
15496 
15497   case UO_LNot: // logical negation
15498     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15499     Input = DefaultFunctionArrayLvalueConversion(Input.get());
15500     if (Input.isInvalid()) return ExprError();
15501     resultType = Input.get()->getType();
15502 
15503     // Though we still have to promote half FP to float...
15504     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15505       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15506       resultType = Context.FloatTy;
15507     }
15508 
15509     if (resultType->isDependentType())
15510       break;
15511     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15512       // C99 6.5.3.3p1: ok, fallthrough;
15513       if (Context.getLangOpts().CPlusPlus) {
15514         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15515         // operand contextually converted to bool.
15516         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15517                                   ScalarTypeToBooleanCastKind(resultType));
15518       } else if (Context.getLangOpts().OpenCL &&
15519                  Context.getLangOpts().OpenCLVersion < 120) {
15520         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15521         // operate on scalar float types.
15522         if (!resultType->isIntegerType() && !resultType->isPointerType())
15523           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15524                            << resultType << Input.get()->getSourceRange());
15525       }
15526     } else if (resultType->isExtVectorType()) {
15527       if (Context.getLangOpts().OpenCL &&
15528           Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15529         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15530         // operate on vector float types.
15531         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15532         if (!T->isIntegerType())
15533           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15534                            << resultType << Input.get()->getSourceRange());
15535       }
15536       // Vector logical not returns the signed variant of the operand type.
15537       resultType = GetSignedVectorType(resultType);
15538       break;
15539     } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15540       const VectorType *VTy = resultType->castAs<VectorType>();
15541       if (VTy->getVectorKind() != VectorType::GenericVector)
15542         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15543                          << resultType << Input.get()->getSourceRange());
15544 
15545       // Vector logical not returns the signed variant of the operand type.
15546       resultType = GetSignedVectorType(resultType);
15547       break;
15548     } else {
15549       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15550         << resultType << Input.get()->getSourceRange());
15551     }
15552 
15553     // LNot always has type int. C99 6.5.3.3p5.
15554     // In C++, it's bool. C++ 5.3.1p8
15555     resultType = Context.getLogicalOperationType();
15556     break;
15557   case UO_Real:
15558   case UO_Imag:
15559     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15560     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15561     // complex l-values to ordinary l-values and all other values to r-values.
15562     if (Input.isInvalid()) return ExprError();
15563     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15564       if (Input.get()->isGLValue() &&
15565           Input.get()->getObjectKind() == OK_Ordinary)
15566         VK = Input.get()->getValueKind();
15567     } else if (!getLangOpts().CPlusPlus) {
15568       // In C, a volatile scalar is read by __imag. In C++, it is not.
15569       Input = DefaultLvalueConversion(Input.get());
15570     }
15571     break;
15572   case UO_Extension:
15573     resultType = Input.get()->getType();
15574     VK = Input.get()->getValueKind();
15575     OK = Input.get()->getObjectKind();
15576     break;
15577   case UO_Coawait:
15578     // It's unnecessary to represent the pass-through operator co_await in the
15579     // AST; just return the input expression instead.
15580     assert(!Input.get()->getType()->isDependentType() &&
15581                    "the co_await expression must be non-dependant before "
15582                    "building operator co_await");
15583     return Input;
15584   }
15585   if (resultType.isNull() || Input.isInvalid())
15586     return ExprError();
15587 
15588   // Check for array bounds violations in the operand of the UnaryOperator,
15589   // except for the '*' and '&' operators that have to be handled specially
15590   // by CheckArrayAccess (as there are special cases like &array[arraysize]
15591   // that are explicitly defined as valid by the standard).
15592   if (Opc != UO_AddrOf && Opc != UO_Deref)
15593     CheckArrayAccess(Input.get());
15594 
15595   auto *UO =
15596       UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15597                             OpLoc, CanOverflow, CurFPFeatureOverrides());
15598 
15599   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15600       !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15601       !isUnevaluatedContext())
15602     ExprEvalContexts.back().PossibleDerefs.insert(UO);
15603 
15604   // Convert the result back to a half vector.
15605   if (ConvertHalfVec)
15606     return convertVector(UO, Context.HalfTy, *this);
15607   return UO;
15608 }
15609 
15610 /// Determine whether the given expression is a qualified member
15611 /// access expression, of a form that could be turned into a pointer to member
15612 /// with the address-of operator.
15613 bool Sema::isQualifiedMemberAccess(Expr *E) {
15614   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15615     if (!DRE->getQualifier())
15616       return false;
15617 
15618     ValueDecl *VD = DRE->getDecl();
15619     if (!VD->isCXXClassMember())
15620       return false;
15621 
15622     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15623       return true;
15624     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15625       return Method->isInstance();
15626 
15627     return false;
15628   }
15629 
15630   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15631     if (!ULE->getQualifier())
15632       return false;
15633 
15634     for (NamedDecl *D : ULE->decls()) {
15635       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15636         if (Method->isInstance())
15637           return true;
15638       } else {
15639         // Overload set does not contain methods.
15640         break;
15641       }
15642     }
15643 
15644     return false;
15645   }
15646 
15647   return false;
15648 }
15649 
15650 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
15651                               UnaryOperatorKind Opc, Expr *Input) {
15652   // First things first: handle placeholders so that the
15653   // overloaded-operator check considers the right type.
15654   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15655     // Increment and decrement of pseudo-object references.
15656     if (pty->getKind() == BuiltinType::PseudoObject &&
15657         UnaryOperator::isIncrementDecrementOp(Opc))
15658       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
15659 
15660     // extension is always a builtin operator.
15661     if (Opc == UO_Extension)
15662       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15663 
15664     // & gets special logic for several kinds of placeholder.
15665     // The builtin code knows what to do.
15666     if (Opc == UO_AddrOf &&
15667         (pty->getKind() == BuiltinType::Overload ||
15668          pty->getKind() == BuiltinType::UnknownAny ||
15669          pty->getKind() == BuiltinType::BoundMember))
15670       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15671 
15672     // Anything else needs to be handled now.
15673     ExprResult Result = CheckPlaceholderExpr(Input);
15674     if (Result.isInvalid()) return ExprError();
15675     Input = Result.get();
15676   }
15677 
15678   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15679       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
15680       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15681     // Find all of the overloaded operators visible from this point.
15682     UnresolvedSet<16> Functions;
15683     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
15684     if (S && OverOp != OO_None)
15685       LookupOverloadedOperatorName(OverOp, S, Functions);
15686 
15687     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15688   }
15689 
15690   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15691 }
15692 
15693 // Unary Operators.  'Tok' is the token for the operator.
15694 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
15695                               tok::TokenKind Op, Expr *Input) {
15696   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
15697 }
15698 
15699 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
15700 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
15701                                 LabelDecl *TheDecl) {
15702   TheDecl->markUsed(Context);
15703   // Create the AST node.  The address of a label always has type 'void*'.
15704   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
15705                                      Context.getPointerType(Context.VoidTy));
15706 }
15707 
15708 void Sema::ActOnStartStmtExpr() {
15709   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
15710 }
15711 
15712 void Sema::ActOnStmtExprError() {
15713   // Note that function is also called by TreeTransform when leaving a
15714   // StmtExpr scope without rebuilding anything.
15715 
15716   DiscardCleanupsInEvaluationContext();
15717   PopExpressionEvaluationContext();
15718 }
15719 
15720 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
15721                                SourceLocation RPLoc) {
15722   return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15723 }
15724 
15725 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
15726                                SourceLocation RPLoc, unsigned TemplateDepth) {
15727   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15728   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15729 
15730   if (hasAnyUnrecoverableErrorsInThisFunction())
15731     DiscardCleanupsInEvaluationContext();
15732   assert(!Cleanup.exprNeedsCleanups() &&
15733          "cleanups within StmtExpr not correctly bound!");
15734   PopExpressionEvaluationContext();
15735 
15736   // FIXME: there are a variety of strange constraints to enforce here, for
15737   // example, it is not possible to goto into a stmt expression apparently.
15738   // More semantic analysis is needed.
15739 
15740   // If there are sub-stmts in the compound stmt, take the type of the last one
15741   // as the type of the stmtexpr.
15742   QualType Ty = Context.VoidTy;
15743   bool StmtExprMayBindToTemp = false;
15744   if (!Compound->body_empty()) {
15745     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15746     if (const auto *LastStmt =
15747             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15748       if (const Expr *Value = LastStmt->getExprStmt()) {
15749         StmtExprMayBindToTemp = true;
15750         Ty = Value->getType();
15751       }
15752     }
15753   }
15754 
15755   // FIXME: Check that expression type is complete/non-abstract; statement
15756   // expressions are not lvalues.
15757   Expr *ResStmtExpr =
15758       new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15759   if (StmtExprMayBindToTemp)
15760     return MaybeBindToTemporary(ResStmtExpr);
15761   return ResStmtExpr;
15762 }
15763 
15764 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15765   if (ER.isInvalid())
15766     return ExprError();
15767 
15768   // Do function/array conversion on the last expression, but not
15769   // lvalue-to-rvalue.  However, initialize an unqualified type.
15770   ER = DefaultFunctionArrayConversion(ER.get());
15771   if (ER.isInvalid())
15772     return ExprError();
15773   Expr *E = ER.get();
15774 
15775   if (E->isTypeDependent())
15776     return E;
15777 
15778   // In ARC, if the final expression ends in a consume, splice
15779   // the consume out and bind it later.  In the alternate case
15780   // (when dealing with a retainable type), the result
15781   // initialization will create a produce.  In both cases the
15782   // result will be +1, and we'll need to balance that out with
15783   // a bind.
15784   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15785   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15786     return Cast->getSubExpr();
15787 
15788   // FIXME: Provide a better location for the initialization.
15789   return PerformCopyInitialization(
15790       InitializedEntity::InitializeStmtExprResult(
15791           E->getBeginLoc(), E->getType().getUnqualifiedType()),
15792       SourceLocation(), E);
15793 }
15794 
15795 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15796                                       TypeSourceInfo *TInfo,
15797                                       ArrayRef<OffsetOfComponent> Components,
15798                                       SourceLocation RParenLoc) {
15799   QualType ArgTy = TInfo->getType();
15800   bool Dependent = ArgTy->isDependentType();
15801   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15802 
15803   // We must have at least one component that refers to the type, and the first
15804   // one is known to be a field designator.  Verify that the ArgTy represents
15805   // a struct/union/class.
15806   if (!Dependent && !ArgTy->isRecordType())
15807     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15808                        << ArgTy << TypeRange);
15809 
15810   // Type must be complete per C99 7.17p3 because a declaring a variable
15811   // with an incomplete type would be ill-formed.
15812   if (!Dependent
15813       && RequireCompleteType(BuiltinLoc, ArgTy,
15814                              diag::err_offsetof_incomplete_type, TypeRange))
15815     return ExprError();
15816 
15817   bool DidWarnAboutNonPOD = false;
15818   QualType CurrentType = ArgTy;
15819   SmallVector<OffsetOfNode, 4> Comps;
15820   SmallVector<Expr*, 4> Exprs;
15821   for (const OffsetOfComponent &OC : Components) {
15822     if (OC.isBrackets) {
15823       // Offset of an array sub-field.  TODO: Should we allow vector elements?
15824       if (!CurrentType->isDependentType()) {
15825         const ArrayType *AT = Context.getAsArrayType(CurrentType);
15826         if(!AT)
15827           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15828                            << CurrentType);
15829         CurrentType = AT->getElementType();
15830       } else
15831         CurrentType = Context.DependentTy;
15832 
15833       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15834       if (IdxRval.isInvalid())
15835         return ExprError();
15836       Expr *Idx = IdxRval.get();
15837 
15838       // The expression must be an integral expression.
15839       // FIXME: An integral constant expression?
15840       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15841           !Idx->getType()->isIntegerType())
15842         return ExprError(
15843             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15844             << Idx->getSourceRange());
15845 
15846       // Record this array index.
15847       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15848       Exprs.push_back(Idx);
15849       continue;
15850     }
15851 
15852     // Offset of a field.
15853     if (CurrentType->isDependentType()) {
15854       // We have the offset of a field, but we can't look into the dependent
15855       // type. Just record the identifier of the field.
15856       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15857       CurrentType = Context.DependentTy;
15858       continue;
15859     }
15860 
15861     // We need to have a complete type to look into.
15862     if (RequireCompleteType(OC.LocStart, CurrentType,
15863                             diag::err_offsetof_incomplete_type))
15864       return ExprError();
15865 
15866     // Look for the designated field.
15867     const RecordType *RC = CurrentType->getAs<RecordType>();
15868     if (!RC)
15869       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15870                        << CurrentType);
15871     RecordDecl *RD = RC->getDecl();
15872 
15873     // C++ [lib.support.types]p5:
15874     //   The macro offsetof accepts a restricted set of type arguments in this
15875     //   International Standard. type shall be a POD structure or a POD union
15876     //   (clause 9).
15877     // C++11 [support.types]p4:
15878     //   If type is not a standard-layout class (Clause 9), the results are
15879     //   undefined.
15880     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15881       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15882       unsigned DiagID =
15883         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15884                             : diag::ext_offsetof_non_pod_type;
15885 
15886       if (!IsSafe && !DidWarnAboutNonPOD &&
15887           DiagRuntimeBehavior(BuiltinLoc, nullptr,
15888                               PDiag(DiagID)
15889                               << SourceRange(Components[0].LocStart, OC.LocEnd)
15890                               << CurrentType))
15891         DidWarnAboutNonPOD = true;
15892     }
15893 
15894     // Look for the field.
15895     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15896     LookupQualifiedName(R, RD);
15897     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15898     IndirectFieldDecl *IndirectMemberDecl = nullptr;
15899     if (!MemberDecl) {
15900       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15901         MemberDecl = IndirectMemberDecl->getAnonField();
15902     }
15903 
15904     if (!MemberDecl)
15905       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15906                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15907                                                               OC.LocEnd));
15908 
15909     // C99 7.17p3:
15910     //   (If the specified member is a bit-field, the behavior is undefined.)
15911     //
15912     // We diagnose this as an error.
15913     if (MemberDecl->isBitField()) {
15914       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15915         << MemberDecl->getDeclName()
15916         << SourceRange(BuiltinLoc, RParenLoc);
15917       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15918       return ExprError();
15919     }
15920 
15921     RecordDecl *Parent = MemberDecl->getParent();
15922     if (IndirectMemberDecl)
15923       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15924 
15925     // If the member was found in a base class, introduce OffsetOfNodes for
15926     // the base class indirections.
15927     CXXBasePaths Paths;
15928     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15929                       Paths)) {
15930       if (Paths.getDetectedVirtual()) {
15931         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15932           << MemberDecl->getDeclName()
15933           << SourceRange(BuiltinLoc, RParenLoc);
15934         return ExprError();
15935       }
15936 
15937       CXXBasePath &Path = Paths.front();
15938       for (const CXXBasePathElement &B : Path)
15939         Comps.push_back(OffsetOfNode(B.Base));
15940     }
15941 
15942     if (IndirectMemberDecl) {
15943       for (auto *FI : IndirectMemberDecl->chain()) {
15944         assert(isa<FieldDecl>(FI));
15945         Comps.push_back(OffsetOfNode(OC.LocStart,
15946                                      cast<FieldDecl>(FI), OC.LocEnd));
15947       }
15948     } else
15949       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15950 
15951     CurrentType = MemberDecl->getType().getNonReferenceType();
15952   }
15953 
15954   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15955                               Comps, Exprs, RParenLoc);
15956 }
15957 
15958 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15959                                       SourceLocation BuiltinLoc,
15960                                       SourceLocation TypeLoc,
15961                                       ParsedType ParsedArgTy,
15962                                       ArrayRef<OffsetOfComponent> Components,
15963                                       SourceLocation RParenLoc) {
15964 
15965   TypeSourceInfo *ArgTInfo;
15966   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15967   if (ArgTy.isNull())
15968     return ExprError();
15969 
15970   if (!ArgTInfo)
15971     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15972 
15973   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15974 }
15975 
15976 
15977 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15978                                  Expr *CondExpr,
15979                                  Expr *LHSExpr, Expr *RHSExpr,
15980                                  SourceLocation RPLoc) {
15981   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15982 
15983   ExprValueKind VK = VK_PRValue;
15984   ExprObjectKind OK = OK_Ordinary;
15985   QualType resType;
15986   bool CondIsTrue = false;
15987   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15988     resType = Context.DependentTy;
15989   } else {
15990     // The conditional expression is required to be a constant expression.
15991     llvm::APSInt condEval(32);
15992     ExprResult CondICE = VerifyIntegerConstantExpression(
15993         CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15994     if (CondICE.isInvalid())
15995       return ExprError();
15996     CondExpr = CondICE.get();
15997     CondIsTrue = condEval.getZExtValue();
15998 
15999     // If the condition is > zero, then the AST type is the same as the LHSExpr.
16000     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16001 
16002     resType = ActiveExpr->getType();
16003     VK = ActiveExpr->getValueKind();
16004     OK = ActiveExpr->getObjectKind();
16005   }
16006 
16007   return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16008                                   resType, VK, OK, RPLoc, CondIsTrue);
16009 }
16010 
16011 //===----------------------------------------------------------------------===//
16012 // Clang Extensions.
16013 //===----------------------------------------------------------------------===//
16014 
16015 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16016 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16017   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
16018 
16019   if (LangOpts.CPlusPlus) {
16020     MangleNumberingContext *MCtx;
16021     Decl *ManglingContextDecl;
16022     std::tie(MCtx, ManglingContextDecl) =
16023         getCurrentMangleNumberContext(Block->getDeclContext());
16024     if (MCtx) {
16025       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16026       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16027     }
16028   }
16029 
16030   PushBlockScope(CurScope, Block);
16031   CurContext->addDecl(Block);
16032   if (CurScope)
16033     PushDeclContext(CurScope, Block);
16034   else
16035     CurContext = Block;
16036 
16037   getCurBlock()->HasImplicitReturnType = true;
16038 
16039   // Enter a new evaluation context to insulate the block from any
16040   // cleanups from the enclosing full-expression.
16041   PushExpressionEvaluationContext(
16042       ExpressionEvaluationContext::PotentiallyEvaluated);
16043 }
16044 
16045 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
16046                                Scope *CurScope) {
16047   assert(ParamInfo.getIdentifier() == nullptr &&
16048          "block-id should have no identifier!");
16049   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16050   BlockScopeInfo *CurBlock = getCurBlock();
16051 
16052   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
16053   QualType T = Sig->getType();
16054 
16055   // FIXME: We should allow unexpanded parameter packs here, but that would,
16056   // in turn, make the block expression contain unexpanded parameter packs.
16057   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16058     // Drop the parameters.
16059     FunctionProtoType::ExtProtoInfo EPI;
16060     EPI.HasTrailingReturn = false;
16061     EPI.TypeQuals.addConst();
16062     T = Context.getFunctionType(Context.DependentTy, None, EPI);
16063     Sig = Context.getTrivialTypeSourceInfo(T);
16064   }
16065 
16066   // GetTypeForDeclarator always produces a function type for a block
16067   // literal signature.  Furthermore, it is always a FunctionProtoType
16068   // unless the function was written with a typedef.
16069   assert(T->isFunctionType() &&
16070          "GetTypeForDeclarator made a non-function block signature");
16071 
16072   // Look for an explicit signature in that function type.
16073   FunctionProtoTypeLoc ExplicitSignature;
16074 
16075   if ((ExplicitSignature = Sig->getTypeLoc()
16076                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
16077 
16078     // Check whether that explicit signature was synthesized by
16079     // GetTypeForDeclarator.  If so, don't save that as part of the
16080     // written signature.
16081     if (ExplicitSignature.getLocalRangeBegin() ==
16082         ExplicitSignature.getLocalRangeEnd()) {
16083       // This would be much cheaper if we stored TypeLocs instead of
16084       // TypeSourceInfos.
16085       TypeLoc Result = ExplicitSignature.getReturnLoc();
16086       unsigned Size = Result.getFullDataSize();
16087       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16088       Sig->getTypeLoc().initializeFullCopy(Result, Size);
16089 
16090       ExplicitSignature = FunctionProtoTypeLoc();
16091     }
16092   }
16093 
16094   CurBlock->TheDecl->setSignatureAsWritten(Sig);
16095   CurBlock->FunctionType = T;
16096 
16097   const auto *Fn = T->castAs<FunctionType>();
16098   QualType RetTy = Fn->getReturnType();
16099   bool isVariadic =
16100       (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16101 
16102   CurBlock->TheDecl->setIsVariadic(isVariadic);
16103 
16104   // Context.DependentTy is used as a placeholder for a missing block
16105   // return type.  TODO:  what should we do with declarators like:
16106   //   ^ * { ... }
16107   // If the answer is "apply template argument deduction"....
16108   if (RetTy != Context.DependentTy) {
16109     CurBlock->ReturnType = RetTy;
16110     CurBlock->TheDecl->setBlockMissingReturnType(false);
16111     CurBlock->HasImplicitReturnType = false;
16112   }
16113 
16114   // Push block parameters from the declarator if we had them.
16115   SmallVector<ParmVarDecl*, 8> Params;
16116   if (ExplicitSignature) {
16117     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16118       ParmVarDecl *Param = ExplicitSignature.getParam(I);
16119       if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16120           !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16121         // Diagnose this as an extension in C17 and earlier.
16122         if (!getLangOpts().C2x)
16123           Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
16124       }
16125       Params.push_back(Param);
16126     }
16127 
16128   // Fake up parameter variables if we have a typedef, like
16129   //   ^ fntype { ... }
16130   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16131     for (const auto &I : Fn->param_types()) {
16132       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16133           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16134       Params.push_back(Param);
16135     }
16136   }
16137 
16138   // Set the parameters on the block decl.
16139   if (!Params.empty()) {
16140     CurBlock->TheDecl->setParams(Params);
16141     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
16142                              /*CheckParameterNames=*/false);
16143   }
16144 
16145   // Finally we can process decl attributes.
16146   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16147 
16148   // Put the parameter variables in scope.
16149   for (auto AI : CurBlock->TheDecl->parameters()) {
16150     AI->setOwningFunction(CurBlock->TheDecl);
16151 
16152     // If this has an identifier, add it to the scope stack.
16153     if (AI->getIdentifier()) {
16154       CheckShadow(CurBlock->TheScope, AI);
16155 
16156       PushOnScopeChains(AI, CurBlock->TheScope);
16157     }
16158   }
16159 }
16160 
16161 /// ActOnBlockError - If there is an error parsing a block, this callback
16162 /// is invoked to pop the information about the block from the action impl.
16163 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16164   // Leave the expression-evaluation context.
16165   DiscardCleanupsInEvaluationContext();
16166   PopExpressionEvaluationContext();
16167 
16168   // Pop off CurBlock, handle nested blocks.
16169   PopDeclContext();
16170   PopFunctionScopeInfo();
16171 }
16172 
16173 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16174 /// literal was successfully completed.  ^(int x){...}
16175 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
16176                                     Stmt *Body, Scope *CurScope) {
16177   // If blocks are disabled, emit an error.
16178   if (!LangOpts.Blocks)
16179     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16180 
16181   // Leave the expression-evaluation context.
16182   if (hasAnyUnrecoverableErrorsInThisFunction())
16183     DiscardCleanupsInEvaluationContext();
16184   assert(!Cleanup.exprNeedsCleanups() &&
16185          "cleanups within block not correctly bound!");
16186   PopExpressionEvaluationContext();
16187 
16188   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16189   BlockDecl *BD = BSI->TheDecl;
16190 
16191   if (BSI->HasImplicitReturnType)
16192     deduceClosureReturnType(*BSI);
16193 
16194   QualType RetTy = Context.VoidTy;
16195   if (!BSI->ReturnType.isNull())
16196     RetTy = BSI->ReturnType;
16197 
16198   bool NoReturn = BD->hasAttr<NoReturnAttr>();
16199   QualType BlockTy;
16200 
16201   // If the user wrote a function type in some form, try to use that.
16202   if (!BSI->FunctionType.isNull()) {
16203     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16204 
16205     FunctionType::ExtInfo Ext = FTy->getExtInfo();
16206     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16207 
16208     // Turn protoless block types into nullary block types.
16209     if (isa<FunctionNoProtoType>(FTy)) {
16210       FunctionProtoType::ExtProtoInfo EPI;
16211       EPI.ExtInfo = Ext;
16212       BlockTy = Context.getFunctionType(RetTy, None, EPI);
16213 
16214     // Otherwise, if we don't need to change anything about the function type,
16215     // preserve its sugar structure.
16216     } else if (FTy->getReturnType() == RetTy &&
16217                (!NoReturn || FTy->getNoReturnAttr())) {
16218       BlockTy = BSI->FunctionType;
16219 
16220     // Otherwise, make the minimal modifications to the function type.
16221     } else {
16222       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16223       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16224       EPI.TypeQuals = Qualifiers();
16225       EPI.ExtInfo = Ext;
16226       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16227     }
16228 
16229   // If we don't have a function type, just build one from nothing.
16230   } else {
16231     FunctionProtoType::ExtProtoInfo EPI;
16232     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16233     BlockTy = Context.getFunctionType(RetTy, None, EPI);
16234   }
16235 
16236   DiagnoseUnusedParameters(BD->parameters());
16237   BlockTy = Context.getBlockPointerType(BlockTy);
16238 
16239   // If needed, diagnose invalid gotos and switches in the block.
16240   if (getCurFunction()->NeedsScopeChecking() &&
16241       !PP.isCodeCompletionEnabled())
16242     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16243 
16244   BD->setBody(cast<CompoundStmt>(Body));
16245 
16246   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16247     DiagnoseUnguardedAvailabilityViolations(BD);
16248 
16249   // Try to apply the named return value optimization. We have to check again
16250   // if we can do this, though, because blocks keep return statements around
16251   // to deduce an implicit return type.
16252   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16253       !BD->isDependentContext())
16254     computeNRVO(Body, BSI);
16255 
16256   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16257       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16258     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
16259                           NTCUK_Destruct|NTCUK_Copy);
16260 
16261   PopDeclContext();
16262 
16263   // Set the captured variables on the block.
16264   SmallVector<BlockDecl::Capture, 4> Captures;
16265   for (Capture &Cap : BSI->Captures) {
16266     if (Cap.isInvalid() || Cap.isThisCapture())
16267       continue;
16268 
16269     VarDecl *Var = Cap.getVariable();
16270     Expr *CopyExpr = nullptr;
16271     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16272       if (const RecordType *Record =
16273               Cap.getCaptureType()->getAs<RecordType>()) {
16274         // The capture logic needs the destructor, so make sure we mark it.
16275         // Usually this is unnecessary because most local variables have
16276         // their destructors marked at declaration time, but parameters are
16277         // an exception because it's technically only the call site that
16278         // actually requires the destructor.
16279         if (isa<ParmVarDecl>(Var))
16280           FinalizeVarWithDestructor(Var, Record);
16281 
16282         // Enter a separate potentially-evaluated context while building block
16283         // initializers to isolate their cleanups from those of the block
16284         // itself.
16285         // FIXME: Is this appropriate even when the block itself occurs in an
16286         // unevaluated operand?
16287         EnterExpressionEvaluationContext EvalContext(
16288             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16289 
16290         SourceLocation Loc = Cap.getLocation();
16291 
16292         ExprResult Result = BuildDeclarationNameExpr(
16293             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16294 
16295         // According to the blocks spec, the capture of a variable from
16296         // the stack requires a const copy constructor.  This is not true
16297         // of the copy/move done to move a __block variable to the heap.
16298         if (!Result.isInvalid() &&
16299             !Result.get()->getType().isConstQualified()) {
16300           Result = ImpCastExprToType(Result.get(),
16301                                      Result.get()->getType().withConst(),
16302                                      CK_NoOp, VK_LValue);
16303         }
16304 
16305         if (!Result.isInvalid()) {
16306           Result = PerformCopyInitialization(
16307               InitializedEntity::InitializeBlock(Var->getLocation(),
16308                                                  Cap.getCaptureType()),
16309               Loc, Result.get());
16310         }
16311 
16312         // Build a full-expression copy expression if initialization
16313         // succeeded and used a non-trivial constructor.  Recover from
16314         // errors by pretending that the copy isn't necessary.
16315         if (!Result.isInvalid() &&
16316             !cast<CXXConstructExpr>(Result.get())->getConstructor()
16317                 ->isTrivial()) {
16318           Result = MaybeCreateExprWithCleanups(Result);
16319           CopyExpr = Result.get();
16320         }
16321       }
16322     }
16323 
16324     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16325                               CopyExpr);
16326     Captures.push_back(NewCap);
16327   }
16328   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16329 
16330   // Pop the block scope now but keep it alive to the end of this function.
16331   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
16332   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16333 
16334   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16335 
16336   // If the block isn't obviously global, i.e. it captures anything at
16337   // all, then we need to do a few things in the surrounding context:
16338   if (Result->getBlockDecl()->hasCaptures()) {
16339     // First, this expression has a new cleanup object.
16340     ExprCleanupObjects.push_back(Result->getBlockDecl());
16341     Cleanup.setExprNeedsCleanups(true);
16342 
16343     // It also gets a branch-protected scope if any of the captured
16344     // variables needs destruction.
16345     for (const auto &CI : Result->getBlockDecl()->captures()) {
16346       const VarDecl *var = CI.getVariable();
16347       if (var->getType().isDestructedType() != QualType::DK_none) {
16348         setFunctionHasBranchProtectedScope();
16349         break;
16350       }
16351     }
16352   }
16353 
16354   if (getCurFunction())
16355     getCurFunction()->addBlock(BD);
16356 
16357   return Result;
16358 }
16359 
16360 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16361                             SourceLocation RPLoc) {
16362   TypeSourceInfo *TInfo;
16363   GetTypeFromParser(Ty, &TInfo);
16364   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16365 }
16366 
16367 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
16368                                 Expr *E, TypeSourceInfo *TInfo,
16369                                 SourceLocation RPLoc) {
16370   Expr *OrigExpr = E;
16371   bool IsMS = false;
16372 
16373   // CUDA device code does not support varargs.
16374   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16375     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16376       CUDAFunctionTarget T = IdentifyCUDATarget(F);
16377       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
16378         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16379     }
16380   }
16381 
16382   // NVPTX does not support va_arg expression.
16383   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
16384       Context.getTargetInfo().getTriple().isNVPTX())
16385     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16386 
16387   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16388   // as Microsoft ABI on an actual Microsoft platform, where
16389   // __builtin_ms_va_list and __builtin_va_list are the same.)
16390   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16391       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16392     QualType MSVaListType = Context.getBuiltinMSVaListType();
16393     if (Context.hasSameType(MSVaListType, E->getType())) {
16394       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16395         return ExprError();
16396       IsMS = true;
16397     }
16398   }
16399 
16400   // Get the va_list type
16401   QualType VaListType = Context.getBuiltinVaListType();
16402   if (!IsMS) {
16403     if (VaListType->isArrayType()) {
16404       // Deal with implicit array decay; for example, on x86-64,
16405       // va_list is an array, but it's supposed to decay to
16406       // a pointer for va_arg.
16407       VaListType = Context.getArrayDecayedType(VaListType);
16408       // Make sure the input expression also decays appropriately.
16409       ExprResult Result = UsualUnaryConversions(E);
16410       if (Result.isInvalid())
16411         return ExprError();
16412       E = Result.get();
16413     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16414       // If va_list is a record type and we are compiling in C++ mode,
16415       // check the argument using reference binding.
16416       InitializedEntity Entity = InitializedEntity::InitializeParameter(
16417           Context, Context.getLValueReferenceType(VaListType), false);
16418       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
16419       if (Init.isInvalid())
16420         return ExprError();
16421       E = Init.getAs<Expr>();
16422     } else {
16423       // Otherwise, the va_list argument must be an l-value because
16424       // it is modified by va_arg.
16425       if (!E->isTypeDependent() &&
16426           CheckForModifiableLvalue(E, BuiltinLoc, *this))
16427         return ExprError();
16428     }
16429   }
16430 
16431   if (!IsMS && !E->isTypeDependent() &&
16432       !Context.hasSameType(VaListType, E->getType()))
16433     return ExprError(
16434         Diag(E->getBeginLoc(),
16435              diag::err_first_argument_to_va_arg_not_of_type_va_list)
16436         << OrigExpr->getType() << E->getSourceRange());
16437 
16438   if (!TInfo->getType()->isDependentType()) {
16439     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16440                             diag::err_second_parameter_to_va_arg_incomplete,
16441                             TInfo->getTypeLoc()))
16442       return ExprError();
16443 
16444     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
16445                                TInfo->getType(),
16446                                diag::err_second_parameter_to_va_arg_abstract,
16447                                TInfo->getTypeLoc()))
16448       return ExprError();
16449 
16450     if (!TInfo->getType().isPODType(Context)) {
16451       Diag(TInfo->getTypeLoc().getBeginLoc(),
16452            TInfo->getType()->isObjCLifetimeType()
16453              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16454              : diag::warn_second_parameter_to_va_arg_not_pod)
16455         << TInfo->getType()
16456         << TInfo->getTypeLoc().getSourceRange();
16457     }
16458 
16459     // Check for va_arg where arguments of the given type will be promoted
16460     // (i.e. this va_arg is guaranteed to have undefined behavior).
16461     QualType PromoteType;
16462     if (TInfo->getType()->isPromotableIntegerType()) {
16463       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16464       // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16465       // and C2x 7.16.1.1p2 says, in part:
16466       //   If type is not compatible with the type of the actual next argument
16467       //   (as promoted according to the default argument promotions), the
16468       //   behavior is undefined, except for the following cases:
16469       //     - both types are pointers to qualified or unqualified versions of
16470       //       compatible types;
16471       //     - one type is a signed integer type, the other type is the
16472       //       corresponding unsigned integer type, and the value is
16473       //       representable in both types;
16474       //     - one type is pointer to qualified or unqualified void and the
16475       //       other is a pointer to a qualified or unqualified character type.
16476       // Given that type compatibility is the primary requirement (ignoring
16477       // qualifications), you would think we could call typesAreCompatible()
16478       // directly to test this. However, in C++, that checks for *same type*,
16479       // which causes false positives when passing an enumeration type to
16480       // va_arg. Instead, get the underlying type of the enumeration and pass
16481       // that.
16482       QualType UnderlyingType = TInfo->getType();
16483       if (const auto *ET = UnderlyingType->getAs<EnumType>())
16484         UnderlyingType = ET->getDecl()->getIntegerType();
16485       if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16486                                      /*CompareUnqualified*/ true))
16487         PromoteType = QualType();
16488 
16489       // If the types are still not compatible, we need to test whether the
16490       // promoted type and the underlying type are the same except for
16491       // signedness. Ask the AST for the correctly corresponding type and see
16492       // if that's compatible.
16493       if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16494           PromoteType->isUnsignedIntegerType() !=
16495               UnderlyingType->isUnsignedIntegerType()) {
16496         UnderlyingType =
16497             UnderlyingType->isUnsignedIntegerType()
16498                 ? Context.getCorrespondingSignedType(UnderlyingType)
16499                 : Context.getCorrespondingUnsignedType(UnderlyingType);
16500         if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16501                                        /*CompareUnqualified*/ true))
16502           PromoteType = QualType();
16503       }
16504     }
16505     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16506       PromoteType = Context.DoubleTy;
16507     if (!PromoteType.isNull())
16508       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16509                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16510                           << TInfo->getType()
16511                           << PromoteType
16512                           << TInfo->getTypeLoc().getSourceRange());
16513   }
16514 
16515   QualType T = TInfo->getType().getNonLValueExprType(Context);
16516   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16517 }
16518 
16519 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16520   // The type of __null will be int or long, depending on the size of
16521   // pointers on the target.
16522   QualType Ty;
16523   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
16524   if (pw == Context.getTargetInfo().getIntWidth())
16525     Ty = Context.IntTy;
16526   else if (pw == Context.getTargetInfo().getLongWidth())
16527     Ty = Context.LongTy;
16528   else if (pw == Context.getTargetInfo().getLongLongWidth())
16529     Ty = Context.LongLongTy;
16530   else {
16531     llvm_unreachable("I don't know size of pointer!");
16532   }
16533 
16534   return new (Context) GNUNullExpr(Ty, TokenLoc);
16535 }
16536 
16537 static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
16538   CXXRecordDecl *ImplDecl = nullptr;
16539 
16540   // Fetch the std::source_location::__impl decl.
16541   if (NamespaceDecl *Std = S.getStdNamespace()) {
16542     LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16543                           Loc, Sema::LookupOrdinaryName);
16544     if (S.LookupQualifiedName(ResultSL, Std)) {
16545       if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16546         LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16547                                 Loc, Sema::LookupOrdinaryName);
16548         if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16549             S.LookupQualifiedName(ResultImpl, SLDecl)) {
16550           ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16551         }
16552       }
16553     }
16554   }
16555 
16556   if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16557     S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16558     return nullptr;
16559   }
16560 
16561   // Verify that __impl is a trivial struct type, with no base classes, and with
16562   // only the four expected fields.
16563   if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16564       ImplDecl->getNumBases() != 0) {
16565     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16566     return nullptr;
16567   }
16568 
16569   unsigned Count = 0;
16570   for (FieldDecl *F : ImplDecl->fields()) {
16571     StringRef Name = F->getName();
16572 
16573     if (Name == "_M_file_name") {
16574       if (F->getType() !=
16575           S.Context.getPointerType(S.Context.CharTy.withConst()))
16576         break;
16577       Count++;
16578     } else if (Name == "_M_function_name") {
16579       if (F->getType() !=
16580           S.Context.getPointerType(S.Context.CharTy.withConst()))
16581         break;
16582       Count++;
16583     } else if (Name == "_M_line") {
16584       if (!F->getType()->isIntegerType())
16585         break;
16586       Count++;
16587     } else if (Name == "_M_column") {
16588       if (!F->getType()->isIntegerType())
16589         break;
16590       Count++;
16591     } else {
16592       Count = 100; // invalid
16593       break;
16594     }
16595   }
16596   if (Count != 4) {
16597     S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16598     return nullptr;
16599   }
16600 
16601   return ImplDecl;
16602 }
16603 
16604 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
16605                                     SourceLocation BuiltinLoc,
16606                                     SourceLocation RPLoc) {
16607   QualType ResultTy;
16608   switch (Kind) {
16609   case SourceLocExpr::File:
16610   case SourceLocExpr::Function: {
16611     QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
16612     ResultTy =
16613         Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
16614     break;
16615   }
16616   case SourceLocExpr::Line:
16617   case SourceLocExpr::Column:
16618     ResultTy = Context.UnsignedIntTy;
16619     break;
16620   case SourceLocExpr::SourceLocStruct:
16621     if (!StdSourceLocationImplDecl) {
16622       StdSourceLocationImplDecl =
16623           LookupStdSourceLocationImpl(*this, BuiltinLoc);
16624       if (!StdSourceLocationImplDecl)
16625         return ExprError();
16626     }
16627     ResultTy = Context.getPointerType(
16628         Context.getRecordType(StdSourceLocationImplDecl).withConst());
16629     break;
16630   }
16631 
16632   return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16633 }
16634 
16635 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
16636                                     QualType ResultTy,
16637                                     SourceLocation BuiltinLoc,
16638                                     SourceLocation RPLoc,
16639                                     DeclContext *ParentContext) {
16640   return new (Context)
16641       SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16642 }
16643 
16644 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
16645                                         bool Diagnose) {
16646   if (!getLangOpts().ObjC)
16647     return false;
16648 
16649   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
16650   if (!PT)
16651     return false;
16652   const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
16653 
16654   // Ignore any parens, implicit casts (should only be
16655   // array-to-pointer decays), and not-so-opaque values.  The last is
16656   // important for making this trigger for property assignments.
16657   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
16658   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
16659     if (OV->getSourceExpr())
16660       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
16661 
16662   if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
16663     if (!PT->isObjCIdType() &&
16664         !(ID && ID->getIdentifier()->isStr("NSString")))
16665       return false;
16666     if (!SL->isAscii())
16667       return false;
16668 
16669     if (Diagnose) {
16670       Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
16671           << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
16672       Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
16673     }
16674     return true;
16675   }
16676 
16677   if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
16678       isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
16679       isa<CXXBoolLiteralExpr>(SrcExpr)) &&
16680       !SrcExpr->isNullPointerConstant(
16681           getASTContext(), Expr::NPC_NeverValueDependent)) {
16682     if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
16683       return false;
16684     if (Diagnose) {
16685       Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
16686           << /*number*/1
16687           << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
16688       Expr *NumLit =
16689           BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
16690       if (NumLit)
16691         Exp = NumLit;
16692     }
16693     return true;
16694   }
16695 
16696   return false;
16697 }
16698 
16699 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
16700                                               const Expr *SrcExpr) {
16701   if (!DstType->isFunctionPointerType() ||
16702       !SrcExpr->getType()->isFunctionType())
16703     return false;
16704 
16705   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16706   if (!DRE)
16707     return false;
16708 
16709   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16710   if (!FD)
16711     return false;
16712 
16713   return !S.checkAddressOfFunctionIsAvailable(FD,
16714                                               /*Complain=*/true,
16715                                               SrcExpr->getBeginLoc());
16716 }
16717 
16718 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
16719                                     SourceLocation Loc,
16720                                     QualType DstType, QualType SrcType,
16721                                     Expr *SrcExpr, AssignmentAction Action,
16722                                     bool *Complained) {
16723   if (Complained)
16724     *Complained = false;
16725 
16726   // Decode the result (notice that AST's are still created for extensions).
16727   bool CheckInferredResultType = false;
16728   bool isInvalid = false;
16729   unsigned DiagKind = 0;
16730   ConversionFixItGenerator ConvHints;
16731   bool MayHaveConvFixit = false;
16732   bool MayHaveFunctionDiff = false;
16733   const ObjCInterfaceDecl *IFace = nullptr;
16734   const ObjCProtocolDecl *PDecl = nullptr;
16735 
16736   switch (ConvTy) {
16737   case Compatible:
16738       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16739       return false;
16740 
16741   case PointerToInt:
16742     if (getLangOpts().CPlusPlus) {
16743       DiagKind = diag::err_typecheck_convert_pointer_int;
16744       isInvalid = true;
16745     } else {
16746       DiagKind = diag::ext_typecheck_convert_pointer_int;
16747     }
16748     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16749     MayHaveConvFixit = true;
16750     break;
16751   case IntToPointer:
16752     if (getLangOpts().CPlusPlus) {
16753       DiagKind = diag::err_typecheck_convert_int_pointer;
16754       isInvalid = true;
16755     } else {
16756       DiagKind = diag::ext_typecheck_convert_int_pointer;
16757     }
16758     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16759     MayHaveConvFixit = true;
16760     break;
16761   case IncompatibleFunctionPointer:
16762     if (getLangOpts().CPlusPlus) {
16763       DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16764       isInvalid = true;
16765     } else {
16766       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16767     }
16768     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16769     MayHaveConvFixit = true;
16770     break;
16771   case IncompatiblePointer:
16772     if (Action == AA_Passing_CFAudited) {
16773       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16774     } else if (getLangOpts().CPlusPlus) {
16775       DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16776       isInvalid = true;
16777     } else {
16778       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16779     }
16780     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16781       SrcType->isObjCObjectPointerType();
16782     if (!CheckInferredResultType) {
16783       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16784     } else if (CheckInferredResultType) {
16785       SrcType = SrcType.getUnqualifiedType();
16786       DstType = DstType.getUnqualifiedType();
16787     }
16788     MayHaveConvFixit = true;
16789     break;
16790   case IncompatiblePointerSign:
16791     if (getLangOpts().CPlusPlus) {
16792       DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16793       isInvalid = true;
16794     } else {
16795       DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16796     }
16797     break;
16798   case FunctionVoidPointer:
16799     if (getLangOpts().CPlusPlus) {
16800       DiagKind = diag::err_typecheck_convert_pointer_void_func;
16801       isInvalid = true;
16802     } else {
16803       DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16804     }
16805     break;
16806   case IncompatiblePointerDiscardsQualifiers: {
16807     // Perform array-to-pointer decay if necessary.
16808     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16809 
16810     isInvalid = true;
16811 
16812     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16813     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16814     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16815       DiagKind = diag::err_typecheck_incompatible_address_space;
16816       break;
16817 
16818     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16819       DiagKind = diag::err_typecheck_incompatible_ownership;
16820       break;
16821     }
16822 
16823     llvm_unreachable("unknown error case for discarding qualifiers!");
16824     // fallthrough
16825   }
16826   case CompatiblePointerDiscardsQualifiers:
16827     // If the qualifiers lost were because we were applying the
16828     // (deprecated) C++ conversion from a string literal to a char*
16829     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
16830     // Ideally, this check would be performed in
16831     // checkPointerTypesForAssignment. However, that would require a
16832     // bit of refactoring (so that the second argument is an
16833     // expression, rather than a type), which should be done as part
16834     // of a larger effort to fix checkPointerTypesForAssignment for
16835     // C++ semantics.
16836     if (getLangOpts().CPlusPlus &&
16837         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
16838       return false;
16839     if (getLangOpts().CPlusPlus) {
16840       DiagKind =  diag::err_typecheck_convert_discards_qualifiers;
16841       isInvalid = true;
16842     } else {
16843       DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;
16844     }
16845 
16846     break;
16847   case IncompatibleNestedPointerQualifiers:
16848     if (getLangOpts().CPlusPlus) {
16849       isInvalid = true;
16850       DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16851     } else {
16852       DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16853     }
16854     break;
16855   case IncompatibleNestedPointerAddressSpaceMismatch:
16856     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16857     isInvalid = true;
16858     break;
16859   case IntToBlockPointer:
16860     DiagKind = diag::err_int_to_block_pointer;
16861     isInvalid = true;
16862     break;
16863   case IncompatibleBlockPointer:
16864     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16865     isInvalid = true;
16866     break;
16867   case IncompatibleObjCQualifiedId: {
16868     if (SrcType->isObjCQualifiedIdType()) {
16869       const ObjCObjectPointerType *srcOPT =
16870                 SrcType->castAs<ObjCObjectPointerType>();
16871       for (auto *srcProto : srcOPT->quals()) {
16872         PDecl = srcProto;
16873         break;
16874       }
16875       if (const ObjCInterfaceType *IFaceT =
16876             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16877         IFace = IFaceT->getDecl();
16878     }
16879     else if (DstType->isObjCQualifiedIdType()) {
16880       const ObjCObjectPointerType *dstOPT =
16881         DstType->castAs<ObjCObjectPointerType>();
16882       for (auto *dstProto : dstOPT->quals()) {
16883         PDecl = dstProto;
16884         break;
16885       }
16886       if (const ObjCInterfaceType *IFaceT =
16887             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16888         IFace = IFaceT->getDecl();
16889     }
16890     if (getLangOpts().CPlusPlus) {
16891       DiagKind = diag::err_incompatible_qualified_id;
16892       isInvalid = true;
16893     } else {
16894       DiagKind = diag::warn_incompatible_qualified_id;
16895     }
16896     break;
16897   }
16898   case IncompatibleVectors:
16899     if (getLangOpts().CPlusPlus) {
16900       DiagKind = diag::err_incompatible_vectors;
16901       isInvalid = true;
16902     } else {
16903       DiagKind = diag::warn_incompatible_vectors;
16904     }
16905     break;
16906   case IncompatibleObjCWeakRef:
16907     DiagKind = diag::err_arc_weak_unavailable_assign;
16908     isInvalid = true;
16909     break;
16910   case Incompatible:
16911     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16912       if (Complained)
16913         *Complained = true;
16914       return true;
16915     }
16916 
16917     DiagKind = diag::err_typecheck_convert_incompatible;
16918     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16919     MayHaveConvFixit = true;
16920     isInvalid = true;
16921     MayHaveFunctionDiff = true;
16922     break;
16923   }
16924 
16925   QualType FirstType, SecondType;
16926   switch (Action) {
16927   case AA_Assigning:
16928   case AA_Initializing:
16929     // The destination type comes first.
16930     FirstType = DstType;
16931     SecondType = SrcType;
16932     break;
16933 
16934   case AA_Returning:
16935   case AA_Passing:
16936   case AA_Passing_CFAudited:
16937   case AA_Converting:
16938   case AA_Sending:
16939   case AA_Casting:
16940     // The source type comes first.
16941     FirstType = SrcType;
16942     SecondType = DstType;
16943     break;
16944   }
16945 
16946   PartialDiagnostic FDiag = PDiag(DiagKind);
16947   if (Action == AA_Passing_CFAudited)
16948     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16949   else
16950     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16951 
16952   if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16953       DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16954     auto isPlainChar = [](const clang::Type *Type) {
16955       return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16956              Type->isSpecificBuiltinType(BuiltinType::Char_U);
16957     };
16958     FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16959               isPlainChar(SecondType->getPointeeOrArrayElementType()));
16960   }
16961 
16962   // If we can fix the conversion, suggest the FixIts.
16963   if (!ConvHints.isNull()) {
16964     for (FixItHint &H : ConvHints.Hints)
16965       FDiag << H;
16966   }
16967 
16968   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16969 
16970   if (MayHaveFunctionDiff)
16971     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16972 
16973   Diag(Loc, FDiag);
16974   if ((DiagKind == diag::warn_incompatible_qualified_id ||
16975        DiagKind == diag::err_incompatible_qualified_id) &&
16976       PDecl && IFace && !IFace->hasDefinition())
16977     Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16978         << IFace << PDecl;
16979 
16980   if (SecondType == Context.OverloadTy)
16981     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16982                               FirstType, /*TakingAddress=*/true);
16983 
16984   if (CheckInferredResultType)
16985     EmitRelatedResultTypeNote(SrcExpr);
16986 
16987   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16988     EmitRelatedResultTypeNoteForReturn(DstType);
16989 
16990   if (Complained)
16991     *Complained = true;
16992   return isInvalid;
16993 }
16994 
16995 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16996                                                  llvm::APSInt *Result,
16997                                                  AllowFoldKind CanFold) {
16998   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16999   public:
17000     SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17001                                              QualType T) override {
17002       return S.Diag(Loc, diag::err_ice_not_integral)
17003              << T << S.LangOpts.CPlusPlus;
17004     }
17005     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17006       return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17007     }
17008   } Diagnoser;
17009 
17010   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17011 }
17012 
17013 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
17014                                                  llvm::APSInt *Result,
17015                                                  unsigned DiagID,
17016                                                  AllowFoldKind CanFold) {
17017   class IDDiagnoser : public VerifyICEDiagnoser {
17018     unsigned DiagID;
17019 
17020   public:
17021     IDDiagnoser(unsigned DiagID)
17022       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17023 
17024     SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17025       return S.Diag(Loc, DiagID);
17026     }
17027   } Diagnoser(DiagID);
17028 
17029   return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17030 }
17031 
17032 Sema::SemaDiagnosticBuilder
17033 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17034                                              QualType T) {
17035   return diagnoseNotICE(S, Loc);
17036 }
17037 
17038 Sema::SemaDiagnosticBuilder
17039 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17040   return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17041 }
17042 
17043 ExprResult
17044 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
17045                                       VerifyICEDiagnoser &Diagnoser,
17046                                       AllowFoldKind CanFold) {
17047   SourceLocation DiagLoc = E->getBeginLoc();
17048 
17049   if (getLangOpts().CPlusPlus11) {
17050     // C++11 [expr.const]p5:
17051     //   If an expression of literal class type is used in a context where an
17052     //   integral constant expression is required, then that class type shall
17053     //   have a single non-explicit conversion function to an integral or
17054     //   unscoped enumeration type
17055     ExprResult Converted;
17056     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17057       VerifyICEDiagnoser &BaseDiagnoser;
17058     public:
17059       CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17060           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17061                                 BaseDiagnoser.Suppress, true),
17062             BaseDiagnoser(BaseDiagnoser) {}
17063 
17064       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17065                                            QualType T) override {
17066         return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17067       }
17068 
17069       SemaDiagnosticBuilder diagnoseIncomplete(
17070           Sema &S, SourceLocation Loc, QualType T) override {
17071         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17072       }
17073 
17074       SemaDiagnosticBuilder diagnoseExplicitConv(
17075           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17076         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17077       }
17078 
17079       SemaDiagnosticBuilder noteExplicitConv(
17080           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17081         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17082                  << ConvTy->isEnumeralType() << ConvTy;
17083       }
17084 
17085       SemaDiagnosticBuilder diagnoseAmbiguous(
17086           Sema &S, SourceLocation Loc, QualType T) override {
17087         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17088       }
17089 
17090       SemaDiagnosticBuilder noteAmbiguous(
17091           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17092         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17093                  << ConvTy->isEnumeralType() << ConvTy;
17094       }
17095 
17096       SemaDiagnosticBuilder diagnoseConversion(
17097           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17098         llvm_unreachable("conversion functions are permitted");
17099       }
17100     } ConvertDiagnoser(Diagnoser);
17101 
17102     Converted = PerformContextualImplicitConversion(DiagLoc, E,
17103                                                     ConvertDiagnoser);
17104     if (Converted.isInvalid())
17105       return Converted;
17106     E = Converted.get();
17107     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
17108       return ExprError();
17109   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17110     // An ICE must be of integral or unscoped enumeration type.
17111     if (!Diagnoser.Suppress)
17112       Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17113           << E->getSourceRange();
17114     return ExprError();
17115   }
17116 
17117   ExprResult RValueExpr = DefaultLvalueConversion(E);
17118   if (RValueExpr.isInvalid())
17119     return ExprError();
17120 
17121   E = RValueExpr.get();
17122 
17123   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17124   // in the non-ICE case.
17125   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
17126     if (Result)
17127       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
17128     if (!isa<ConstantExpr>(E))
17129       E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
17130                  : ConstantExpr::Create(Context, E);
17131     return E;
17132   }
17133 
17134   Expr::EvalResult EvalResult;
17135   SmallVector<PartialDiagnosticAt, 8> Notes;
17136   EvalResult.Diag = &Notes;
17137 
17138   // Try to evaluate the expression, and produce diagnostics explaining why it's
17139   // not a constant expression as a side-effect.
17140   bool Folded =
17141       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17142       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17143 
17144   if (!isa<ConstantExpr>(E))
17145     E = ConstantExpr::Create(Context, E, EvalResult.Val);
17146 
17147   // In C++11, we can rely on diagnostics being produced for any expression
17148   // which is not a constant expression. If no diagnostics were produced, then
17149   // this is a constant expression.
17150   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17151     if (Result)
17152       *Result = EvalResult.Val.getInt();
17153     return E;
17154   }
17155 
17156   // If our only note is the usual "invalid subexpression" note, just point
17157   // the caret at its location rather than producing an essentially
17158   // redundant note.
17159   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17160         diag::note_invalid_subexpr_in_const_expr) {
17161     DiagLoc = Notes[0].first;
17162     Notes.clear();
17163   }
17164 
17165   if (!Folded || !CanFold) {
17166     if (!Diagnoser.Suppress) {
17167       Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17168       for (const PartialDiagnosticAt &Note : Notes)
17169         Diag(Note.first, Note.second);
17170     }
17171 
17172     return ExprError();
17173   }
17174 
17175   Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17176   for (const PartialDiagnosticAt &Note : Notes)
17177     Diag(Note.first, Note.second);
17178 
17179   if (Result)
17180     *Result = EvalResult.Val.getInt();
17181   return E;
17182 }
17183 
17184 namespace {
17185   // Handle the case where we conclude a expression which we speculatively
17186   // considered to be unevaluated is actually evaluated.
17187   class TransformToPE : public TreeTransform<TransformToPE> {
17188     typedef TreeTransform<TransformToPE> BaseTransform;
17189 
17190   public:
17191     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17192 
17193     // Make sure we redo semantic analysis
17194     bool AlwaysRebuild() { return true; }
17195     bool ReplacingOriginal() { return true; }
17196 
17197     // We need to special-case DeclRefExprs referring to FieldDecls which
17198     // are not part of a member pointer formation; normal TreeTransforming
17199     // doesn't catch this case because of the way we represent them in the AST.
17200     // FIXME: This is a bit ugly; is it really the best way to handle this
17201     // case?
17202     //
17203     // Error on DeclRefExprs referring to FieldDecls.
17204     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17205       if (isa<FieldDecl>(E->getDecl()) &&
17206           !SemaRef.isUnevaluatedContext())
17207         return SemaRef.Diag(E->getLocation(),
17208                             diag::err_invalid_non_static_member_use)
17209             << E->getDecl() << E->getSourceRange();
17210 
17211       return BaseTransform::TransformDeclRefExpr(E);
17212     }
17213 
17214     // Exception: filter out member pointer formation
17215     ExprResult TransformUnaryOperator(UnaryOperator *E) {
17216       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17217         return E;
17218 
17219       return BaseTransform::TransformUnaryOperator(E);
17220     }
17221 
17222     // The body of a lambda-expression is in a separate expression evaluation
17223     // context so never needs to be transformed.
17224     // FIXME: Ideally we wouldn't transform the closure type either, and would
17225     // just recreate the capture expressions and lambda expression.
17226     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17227       return SkipLambdaBody(E, Body);
17228     }
17229   };
17230 }
17231 
17232 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17233   assert(isUnevaluatedContext() &&
17234          "Should only transform unevaluated expressions");
17235   ExprEvalContexts.back().Context =
17236       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17237   if (isUnevaluatedContext())
17238     return E;
17239   return TransformToPE(*this).TransformExpr(E);
17240 }
17241 
17242 TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17243   assert(isUnevaluatedContext() &&
17244          "Should only transform unevaluated expressions");
17245   ExprEvalContexts.back().Context =
17246       ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17247   if (isUnevaluatedContext())
17248     return TInfo;
17249   return TransformToPE(*this).TransformType(TInfo);
17250 }
17251 
17252 void
17253 Sema::PushExpressionEvaluationContext(
17254     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17255     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17256   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17257                                 LambdaContextDecl, ExprContext);
17258 
17259   // Discarded statements and immediate contexts nested in other
17260   // discarded statements or immediate context are themselves
17261   // a discarded statement or an immediate context, respectively.
17262   ExprEvalContexts.back().InDiscardedStatement =
17263       ExprEvalContexts[ExprEvalContexts.size() - 2]
17264           .isDiscardedStatementContext();
17265   ExprEvalContexts.back().InImmediateFunctionContext =
17266       ExprEvalContexts[ExprEvalContexts.size() - 2]
17267           .isImmediateFunctionContext();
17268 
17269   Cleanup.reset();
17270   if (!MaybeODRUseExprs.empty())
17271     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17272 }
17273 
17274 void
17275 Sema::PushExpressionEvaluationContext(
17276     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17277     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17278   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17279   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17280 }
17281 
17282 namespace {
17283 
17284 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17285   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17286   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17287     if (E->getOpcode() == UO_Deref)
17288       return CheckPossibleDeref(S, E->getSubExpr());
17289   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17290     return CheckPossibleDeref(S, E->getBase());
17291   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17292     return CheckPossibleDeref(S, E->getBase());
17293   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17294     QualType Inner;
17295     QualType Ty = E->getType();
17296     if (const auto *Ptr = Ty->getAs<PointerType>())
17297       Inner = Ptr->getPointeeType();
17298     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17299       Inner = Arr->getElementType();
17300     else
17301       return nullptr;
17302 
17303     if (Inner->hasAttr(attr::NoDeref))
17304       return E;
17305   }
17306   return nullptr;
17307 }
17308 
17309 } // namespace
17310 
17311 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17312   for (const Expr *E : Rec.PossibleDerefs) {
17313     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17314     if (DeclRef) {
17315       const ValueDecl *Decl = DeclRef->getDecl();
17316       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17317           << Decl->getName() << E->getSourceRange();
17318       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17319     } else {
17320       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17321           << E->getSourceRange();
17322     }
17323   }
17324   Rec.PossibleDerefs.clear();
17325 }
17326 
17327 /// Check whether E, which is either a discarded-value expression or an
17328 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17329 /// and if so, remove it from the list of volatile-qualified assignments that
17330 /// we are going to warn are deprecated.
17331 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17332   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
17333     return;
17334 
17335   // Note: ignoring parens here is not justified by the standard rules, but
17336   // ignoring parentheses seems like a more reasonable approach, and this only
17337   // drives a deprecation warning so doesn't affect conformance.
17338   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17339     if (BO->getOpcode() == BO_Assign) {
17340       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17341       llvm::erase_value(LHSs, BO->getLHS());
17342     }
17343   }
17344 }
17345 
17346 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17347   if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17348       !Decl->isConsteval() || isConstantEvaluated() ||
17349       RebuildingImmediateInvocation || isImmediateFunctionContext())
17350     return E;
17351 
17352   /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17353   /// It's OK if this fails; we'll also remove this in
17354   /// HandleImmediateInvocations, but catching it here allows us to avoid
17355   /// walking the AST looking for it in simple cases.
17356   if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17357     if (auto *DeclRef =
17358             dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17359       ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17360 
17361   E = MaybeCreateExprWithCleanups(E);
17362 
17363   ConstantExpr *Res = ConstantExpr::Create(
17364       getASTContext(), E.get(),
17365       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17366                                    getASTContext()),
17367       /*IsImmediateInvocation*/ true);
17368   /// Value-dependent constant expressions should not be immediately
17369   /// evaluated until they are instantiated.
17370   if (!Res->isValueDependent())
17371     ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17372   return Res;
17373 }
17374 
17375 static void EvaluateAndDiagnoseImmediateInvocation(
17376     Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17377   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17378   Expr::EvalResult Eval;
17379   Eval.Diag = &Notes;
17380   ConstantExpr *CE = Candidate.getPointer();
17381   bool Result = CE->EvaluateAsConstantExpr(
17382       Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17383   if (!Result || !Notes.empty()) {
17384     Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17385     if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17386       InnerExpr = FunctionalCast->getSubExpr();
17387     FunctionDecl *FD = nullptr;
17388     if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17389       FD = cast<FunctionDecl>(Call->getCalleeDecl());
17390     else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17391       FD = Call->getConstructor();
17392     else
17393       llvm_unreachable("unhandled decl kind");
17394     assert(FD->isConsteval());
17395     SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
17396     for (auto &Note : Notes)
17397       SemaRef.Diag(Note.first, Note.second);
17398     return;
17399   }
17400   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
17401 }
17402 
17403 static void RemoveNestedImmediateInvocation(
17404     Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17405     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17406   struct ComplexRemove : TreeTransform<ComplexRemove> {
17407     using Base = TreeTransform<ComplexRemove>;
17408     llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17409     SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17410     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17411         CurrentII;
17412     ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17413                   SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17414                   SmallVector<Sema::ImmediateInvocationCandidate,
17415                               4>::reverse_iterator Current)
17416         : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17417     void RemoveImmediateInvocation(ConstantExpr* E) {
17418       auto It = std::find_if(CurrentII, IISet.rend(),
17419                              [E](Sema::ImmediateInvocationCandidate Elem) {
17420                                return Elem.getPointer() == E;
17421                              });
17422       assert(It != IISet.rend() &&
17423              "ConstantExpr marked IsImmediateInvocation should "
17424              "be present");
17425       It->setInt(1); // Mark as deleted
17426     }
17427     ExprResult TransformConstantExpr(ConstantExpr *E) {
17428       if (!E->isImmediateInvocation())
17429         return Base::TransformConstantExpr(E);
17430       RemoveImmediateInvocation(E);
17431       return Base::TransformExpr(E->getSubExpr());
17432     }
17433     /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17434     /// we need to remove its DeclRefExpr from the DRSet.
17435     ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17436       DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17437       return Base::TransformCXXOperatorCallExpr(E);
17438     }
17439     /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17440     /// here.
17441     ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17442       if (!Init)
17443         return Init;
17444       /// ConstantExpr are the first layer of implicit node to be removed so if
17445       /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17446       if (auto *CE = dyn_cast<ConstantExpr>(Init))
17447         if (CE->isImmediateInvocation())
17448           RemoveImmediateInvocation(CE);
17449       return Base::TransformInitializer(Init, NotCopyInit);
17450     }
17451     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17452       DRSet.erase(E);
17453       return E;
17454     }
17455     bool AlwaysRebuild() { return false; }
17456     bool ReplacingOriginal() { return true; }
17457     bool AllowSkippingCXXConstructExpr() {
17458       bool Res = AllowSkippingFirstCXXConstructExpr;
17459       AllowSkippingFirstCXXConstructExpr = true;
17460       return Res;
17461     }
17462     bool AllowSkippingFirstCXXConstructExpr = true;
17463   } Transformer(SemaRef, Rec.ReferenceToConsteval,
17464                 Rec.ImmediateInvocationCandidates, It);
17465 
17466   /// CXXConstructExpr with a single argument are getting skipped by
17467   /// TreeTransform in some situtation because they could be implicit. This
17468   /// can only occur for the top-level CXXConstructExpr because it is used
17469   /// nowhere in the expression being transformed therefore will not be rebuilt.
17470   /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17471   /// skipping the first CXXConstructExpr.
17472   if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17473     Transformer.AllowSkippingFirstCXXConstructExpr = false;
17474 
17475   ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17476   assert(Res.isUsable());
17477   Res = SemaRef.MaybeCreateExprWithCleanups(Res);
17478   It->getPointer()->setSubExpr(Res.get());
17479 }
17480 
17481 static void
17482 HandleImmediateInvocations(Sema &SemaRef,
17483                            Sema::ExpressionEvaluationContextRecord &Rec) {
17484   if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17485        Rec.ReferenceToConsteval.size() == 0) ||
17486       SemaRef.RebuildingImmediateInvocation)
17487     return;
17488 
17489   /// When we have more then 1 ImmediateInvocationCandidates we need to check
17490   /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17491   /// need to remove ReferenceToConsteval in the immediate invocation.
17492   if (Rec.ImmediateInvocationCandidates.size() > 1) {
17493 
17494     /// Prevent sema calls during the tree transform from adding pointers that
17495     /// are already in the sets.
17496     llvm::SaveAndRestore<bool> DisableIITracking(
17497         SemaRef.RebuildingImmediateInvocation, true);
17498 
17499     /// Prevent diagnostic during tree transfrom as they are duplicates
17500     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
17501 
17502     for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17503          It != Rec.ImmediateInvocationCandidates.rend(); It++)
17504       if (!It->getInt())
17505         RemoveNestedImmediateInvocation(SemaRef, Rec, It);
17506   } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17507              Rec.ReferenceToConsteval.size()) {
17508     struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17509       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17510       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17511       bool VisitDeclRefExpr(DeclRefExpr *E) {
17512         DRSet.erase(E);
17513         return DRSet.size();
17514       }
17515     } Visitor(Rec.ReferenceToConsteval);
17516     Visitor.TraverseStmt(
17517         Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17518   }
17519   for (auto CE : Rec.ImmediateInvocationCandidates)
17520     if (!CE.getInt())
17521       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
17522   for (auto DR : Rec.ReferenceToConsteval) {
17523     auto *FD = cast<FunctionDecl>(DR->getDecl());
17524     SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17525         << FD;
17526     SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
17527   }
17528 }
17529 
17530 void Sema::PopExpressionEvaluationContext() {
17531   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
17532   unsigned NumTypos = Rec.NumTypos;
17533 
17534   if (!Rec.Lambdas.empty()) {
17535     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
17536     if (!getLangOpts().CPlusPlus20 &&
17537         (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17538          Rec.isUnevaluated() ||
17539          (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
17540       unsigned D;
17541       if (Rec.isUnevaluated()) {
17542         // C++11 [expr.prim.lambda]p2:
17543         //   A lambda-expression shall not appear in an unevaluated operand
17544         //   (Clause 5).
17545         D = diag::err_lambda_unevaluated_operand;
17546       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17547         // C++1y [expr.const]p2:
17548         //   A conditional-expression e is a core constant expression unless the
17549         //   evaluation of e, following the rules of the abstract machine, would
17550         //   evaluate [...] a lambda-expression.
17551         D = diag::err_lambda_in_constant_expression;
17552       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17553         // C++17 [expr.prim.lamda]p2:
17554         // A lambda-expression shall not appear [...] in a template-argument.
17555         D = diag::err_lambda_in_invalid_context;
17556       } else
17557         llvm_unreachable("Couldn't infer lambda error message.");
17558 
17559       for (const auto *L : Rec.Lambdas)
17560         Diag(L->getBeginLoc(), D);
17561     }
17562   }
17563 
17564   WarnOnPendingNoDerefs(Rec);
17565   HandleImmediateInvocations(*this, Rec);
17566 
17567   // Warn on any volatile-qualified simple-assignments that are not discarded-
17568   // value expressions nor unevaluated operands (those cases get removed from
17569   // this list by CheckUnusedVolatileAssignment).
17570   for (auto *BO : Rec.VolatileAssignmentLHSs)
17571     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17572         << BO->getType();
17573 
17574   // When are coming out of an unevaluated context, clear out any
17575   // temporaries that we may have created as part of the evaluation of
17576   // the expression in that context: they aren't relevant because they
17577   // will never be constructed.
17578   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17579     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
17580                              ExprCleanupObjects.end());
17581     Cleanup = Rec.ParentCleanup;
17582     CleanupVarDeclMarking();
17583     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
17584   // Otherwise, merge the contexts together.
17585   } else {
17586     Cleanup.mergeFrom(Rec.ParentCleanup);
17587     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17588                             Rec.SavedMaybeODRUseExprs.end());
17589   }
17590 
17591   // Pop the current expression evaluation context off the stack.
17592   ExprEvalContexts.pop_back();
17593 
17594   // The global expression evaluation context record is never popped.
17595   ExprEvalContexts.back().NumTypos += NumTypos;
17596 }
17597 
17598 void Sema::DiscardCleanupsInEvaluationContext() {
17599   ExprCleanupObjects.erase(
17600          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17601          ExprCleanupObjects.end());
17602   Cleanup.reset();
17603   MaybeODRUseExprs.clear();
17604 }
17605 
17606 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
17607   ExprResult Result = CheckPlaceholderExpr(E);
17608   if (Result.isInvalid())
17609     return ExprError();
17610   E = Result.get();
17611   if (!E->getType()->isVariablyModifiedType())
17612     return E;
17613   return TransformToPotentiallyEvaluated(E);
17614 }
17615 
17616 /// Are we in a context that is potentially constant evaluated per C++20
17617 /// [expr.const]p12?
17618 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
17619   /// C++2a [expr.const]p12:
17620   //   An expression or conversion is potentially constant evaluated if it is
17621   switch (SemaRef.ExprEvalContexts.back().Context) {
17622     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17623     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17624 
17625       // -- a manifestly constant-evaluated expression,
17626     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17627     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17628     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17629       // -- a potentially-evaluated expression,
17630     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17631       // -- an immediate subexpression of a braced-init-list,
17632 
17633       // -- [FIXME] an expression of the form & cast-expression that occurs
17634       //    within a templated entity
17635       // -- a subexpression of one of the above that is not a subexpression of
17636       // a nested unevaluated operand.
17637       return true;
17638 
17639     case Sema::ExpressionEvaluationContext::Unevaluated:
17640     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17641       // Expressions in this context are never evaluated.
17642       return false;
17643   }
17644   llvm_unreachable("Invalid context");
17645 }
17646 
17647 /// Return true if this function has a calling convention that requires mangling
17648 /// in the size of the parameter pack.
17649 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
17650   // These manglings don't do anything on non-Windows or non-x86 platforms, so
17651   // we don't need parameter type sizes.
17652   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17653   if (!TT.isOSWindows() || !TT.isX86())
17654     return false;
17655 
17656   // If this is C++ and this isn't an extern "C" function, parameters do not
17657   // need to be complete. In this case, C++ mangling will apply, which doesn't
17658   // use the size of the parameters.
17659   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17660     return false;
17661 
17662   // Stdcall, fastcall, and vectorcall need this special treatment.
17663   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17664   switch (CC) {
17665   case CC_X86StdCall:
17666   case CC_X86FastCall:
17667   case CC_X86VectorCall:
17668     return true;
17669   default:
17670     break;
17671   }
17672   return false;
17673 }
17674 
17675 /// Require that all of the parameter types of function be complete. Normally,
17676 /// parameter types are only required to be complete when a function is called
17677 /// or defined, but to mangle functions with certain calling conventions, the
17678 /// mangler needs to know the size of the parameter list. In this situation,
17679 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17680 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17681 /// result in a linker error. Clang doesn't implement this behavior, and instead
17682 /// attempts to error at compile time.
17683 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
17684                                                   SourceLocation Loc) {
17685   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17686     FunctionDecl *FD;
17687     ParmVarDecl *Param;
17688 
17689   public:
17690     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17691         : FD(FD), Param(Param) {}
17692 
17693     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17694       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17695       StringRef CCName;
17696       switch (CC) {
17697       case CC_X86StdCall:
17698         CCName = "stdcall";
17699         break;
17700       case CC_X86FastCall:
17701         CCName = "fastcall";
17702         break;
17703       case CC_X86VectorCall:
17704         CCName = "vectorcall";
17705         break;
17706       default:
17707         llvm_unreachable("CC does not need mangling");
17708       }
17709 
17710       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17711           << Param->getDeclName() << FD->getDeclName() << CCName;
17712     }
17713   };
17714 
17715   for (ParmVarDecl *Param : FD->parameters()) {
17716     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17717     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17718   }
17719 }
17720 
17721 namespace {
17722 enum class OdrUseContext {
17723   /// Declarations in this context are not odr-used.
17724   None,
17725   /// Declarations in this context are formally odr-used, but this is a
17726   /// dependent context.
17727   Dependent,
17728   /// Declarations in this context are odr-used but not actually used (yet).
17729   FormallyOdrUsed,
17730   /// Declarations in this context are used.
17731   Used
17732 };
17733 }
17734 
17735 /// Are we within a context in which references to resolved functions or to
17736 /// variables result in odr-use?
17737 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17738   OdrUseContext Result;
17739 
17740   switch (SemaRef.ExprEvalContexts.back().Context) {
17741     case Sema::ExpressionEvaluationContext::Unevaluated:
17742     case Sema::ExpressionEvaluationContext::UnevaluatedList:
17743     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
17744       return OdrUseContext::None;
17745 
17746     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
17747     case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
17748     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
17749       Result = OdrUseContext::Used;
17750       break;
17751 
17752     case Sema::ExpressionEvaluationContext::DiscardedStatement:
17753       Result = OdrUseContext::FormallyOdrUsed;
17754       break;
17755 
17756     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17757       // A default argument formally results in odr-use, but doesn't actually
17758       // result in a use in any real sense until it itself is used.
17759       Result = OdrUseContext::FormallyOdrUsed;
17760       break;
17761   }
17762 
17763   if (SemaRef.CurContext->isDependentContext())
17764     return OdrUseContext::Dependent;
17765 
17766   return Result;
17767 }
17768 
17769 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
17770   if (!Func->isConstexpr())
17771     return false;
17772 
17773   if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17774     return true;
17775   auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17776   return CCD && CCD->getInheritedConstructor();
17777 }
17778 
17779 /// Mark a function referenced, and check whether it is odr-used
17780 /// (C++ [basic.def.odr]p2, C99 6.9p3)
17781 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
17782                                   bool MightBeOdrUse) {
17783   assert(Func && "No function?");
17784 
17785   Func->setReferenced();
17786 
17787   // Recursive functions aren't really used until they're used from some other
17788   // context.
17789   bool IsRecursiveCall = CurContext == Func;
17790 
17791   // C++11 [basic.def.odr]p3:
17792   //   A function whose name appears as a potentially-evaluated expression is
17793   //   odr-used if it is the unique lookup result or the selected member of a
17794   //   set of overloaded functions [...].
17795   //
17796   // We (incorrectly) mark overload resolution as an unevaluated context, so we
17797   // can just check that here.
17798   OdrUseContext OdrUse =
17799       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17800   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17801     OdrUse = OdrUseContext::FormallyOdrUsed;
17802 
17803   // Trivial default constructors and destructors are never actually used.
17804   // FIXME: What about other special members?
17805   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17806       OdrUse == OdrUseContext::Used) {
17807     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17808       if (Constructor->isDefaultConstructor())
17809         OdrUse = OdrUseContext::FormallyOdrUsed;
17810     if (isa<CXXDestructorDecl>(Func))
17811       OdrUse = OdrUseContext::FormallyOdrUsed;
17812   }
17813 
17814   // C++20 [expr.const]p12:
17815   //   A function [...] is needed for constant evaluation if it is [...] a
17816   //   constexpr function that is named by an expression that is potentially
17817   //   constant evaluated
17818   bool NeededForConstantEvaluation =
17819       isPotentiallyConstantEvaluatedContext(*this) &&
17820       isImplicitlyDefinableConstexprFunction(Func);
17821 
17822   // Determine whether we require a function definition to exist, per
17823   // C++11 [temp.inst]p3:
17824   //   Unless a function template specialization has been explicitly
17825   //   instantiated or explicitly specialized, the function template
17826   //   specialization is implicitly instantiated when the specialization is
17827   //   referenced in a context that requires a function definition to exist.
17828   // C++20 [temp.inst]p7:
17829   //   The existence of a definition of a [...] function is considered to
17830   //   affect the semantics of the program if the [...] function is needed for
17831   //   constant evaluation by an expression
17832   // C++20 [basic.def.odr]p10:
17833   //   Every program shall contain exactly one definition of every non-inline
17834   //   function or variable that is odr-used in that program outside of a
17835   //   discarded statement
17836   // C++20 [special]p1:
17837   //   The implementation will implicitly define [defaulted special members]
17838   //   if they are odr-used or needed for constant evaluation.
17839   //
17840   // Note that we skip the implicit instantiation of templates that are only
17841   // used in unused default arguments or by recursive calls to themselves.
17842   // This is formally non-conforming, but seems reasonable in practice.
17843   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
17844                                              NeededForConstantEvaluation);
17845 
17846   // C++14 [temp.expl.spec]p6:
17847   //   If a template [...] is explicitly specialized then that specialization
17848   //   shall be declared before the first use of that specialization that would
17849   //   cause an implicit instantiation to take place, in every translation unit
17850   //   in which such a use occurs
17851   if (NeedDefinition &&
17852       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17853        Func->getMemberSpecializationInfo()))
17854     checkSpecializationVisibility(Loc, Func);
17855 
17856   if (getLangOpts().CUDA)
17857     CheckCUDACall(Loc, Func);
17858 
17859   if (getLangOpts().SYCLIsDevice)
17860     checkSYCLDeviceFunction(Loc, Func);
17861 
17862   // If we need a definition, try to create one.
17863   if (NeedDefinition && !Func->getBody()) {
17864     runWithSufficientStackSpace(Loc, [&] {
17865       if (CXXConstructorDecl *Constructor =
17866               dyn_cast<CXXConstructorDecl>(Func)) {
17867         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17868         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17869           if (Constructor->isDefaultConstructor()) {
17870             if (Constructor->isTrivial() &&
17871                 !Constructor->hasAttr<DLLExportAttr>())
17872               return;
17873             DefineImplicitDefaultConstructor(Loc, Constructor);
17874           } else if (Constructor->isCopyConstructor()) {
17875             DefineImplicitCopyConstructor(Loc, Constructor);
17876           } else if (Constructor->isMoveConstructor()) {
17877             DefineImplicitMoveConstructor(Loc, Constructor);
17878           }
17879         } else if (Constructor->getInheritedConstructor()) {
17880           DefineInheritingConstructor(Loc, Constructor);
17881         }
17882       } else if (CXXDestructorDecl *Destructor =
17883                      dyn_cast<CXXDestructorDecl>(Func)) {
17884         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17885         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17886           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17887             return;
17888           DefineImplicitDestructor(Loc, Destructor);
17889         }
17890         if (Destructor->isVirtual() && getLangOpts().AppleKext)
17891           MarkVTableUsed(Loc, Destructor->getParent());
17892       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17893         if (MethodDecl->isOverloadedOperator() &&
17894             MethodDecl->getOverloadedOperator() == OO_Equal) {
17895           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17896           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17897             if (MethodDecl->isCopyAssignmentOperator())
17898               DefineImplicitCopyAssignment(Loc, MethodDecl);
17899             else if (MethodDecl->isMoveAssignmentOperator())
17900               DefineImplicitMoveAssignment(Loc, MethodDecl);
17901           }
17902         } else if (isa<CXXConversionDecl>(MethodDecl) &&
17903                    MethodDecl->getParent()->isLambda()) {
17904           CXXConversionDecl *Conversion =
17905               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17906           if (Conversion->isLambdaToBlockPointerConversion())
17907             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17908           else
17909             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17910         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17911           MarkVTableUsed(Loc, MethodDecl->getParent());
17912       }
17913 
17914       if (Func->isDefaulted() && !Func->isDeleted()) {
17915         DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17916         if (DCK != DefaultedComparisonKind::None)
17917           DefineDefaultedComparison(Loc, Func, DCK);
17918       }
17919 
17920       // Implicit instantiation of function templates and member functions of
17921       // class templates.
17922       if (Func->isImplicitlyInstantiable()) {
17923         TemplateSpecializationKind TSK =
17924             Func->getTemplateSpecializationKindForInstantiation();
17925         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17926         bool FirstInstantiation = PointOfInstantiation.isInvalid();
17927         if (FirstInstantiation) {
17928           PointOfInstantiation = Loc;
17929           if (auto *MSI = Func->getMemberSpecializationInfo())
17930             MSI->setPointOfInstantiation(Loc);
17931             // FIXME: Notify listener.
17932           else
17933             Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17934         } else if (TSK != TSK_ImplicitInstantiation) {
17935           // Use the point of use as the point of instantiation, instead of the
17936           // point of explicit instantiation (which we track as the actual point
17937           // of instantiation). This gives better backtraces in diagnostics.
17938           PointOfInstantiation = Loc;
17939         }
17940 
17941         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17942             Func->isConstexpr()) {
17943           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17944               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17945               CodeSynthesisContexts.size())
17946             PendingLocalImplicitInstantiations.push_back(
17947                 std::make_pair(Func, PointOfInstantiation));
17948           else if (Func->isConstexpr())
17949             // Do not defer instantiations of constexpr functions, to avoid the
17950             // expression evaluator needing to call back into Sema if it sees a
17951             // call to such a function.
17952             InstantiateFunctionDefinition(PointOfInstantiation, Func);
17953           else {
17954             Func->setInstantiationIsPending(true);
17955             PendingInstantiations.push_back(
17956                 std::make_pair(Func, PointOfInstantiation));
17957             // Notify the consumer that a function was implicitly instantiated.
17958             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17959           }
17960         }
17961       } else {
17962         // Walk redefinitions, as some of them may be instantiable.
17963         for (auto i : Func->redecls()) {
17964           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17965             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17966         }
17967       }
17968     });
17969   }
17970 
17971   // C++14 [except.spec]p17:
17972   //   An exception-specification is considered to be needed when:
17973   //   - the function is odr-used or, if it appears in an unevaluated operand,
17974   //     would be odr-used if the expression were potentially-evaluated;
17975   //
17976   // Note, we do this even if MightBeOdrUse is false. That indicates that the
17977   // function is a pure virtual function we're calling, and in that case the
17978   // function was selected by overload resolution and we need to resolve its
17979   // exception specification for a different reason.
17980   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17981   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17982     ResolveExceptionSpec(Loc, FPT);
17983 
17984   // If this is the first "real" use, act on that.
17985   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17986     // Keep track of used but undefined functions.
17987     if (!Func->isDefined()) {
17988       if (mightHaveNonExternalLinkage(Func))
17989         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17990       else if (Func->getMostRecentDecl()->isInlined() &&
17991                !LangOpts.GNUInline &&
17992                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17993         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17994       else if (isExternalWithNoLinkageType(Func))
17995         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17996     }
17997 
17998     // Some x86 Windows calling conventions mangle the size of the parameter
17999     // pack into the name. Computing the size of the parameters requires the
18000     // parameter types to be complete. Check that now.
18001     if (funcHasParameterSizeMangling(*this, Func))
18002       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
18003 
18004     // In the MS C++ ABI, the compiler emits destructor variants where they are
18005     // used. If the destructor is used here but defined elsewhere, mark the
18006     // virtual base destructors referenced. If those virtual base destructors
18007     // are inline, this will ensure they are defined when emitting the complete
18008     // destructor variant. This checking may be redundant if the destructor is
18009     // provided later in this TU.
18010     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18011       if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18012         CXXRecordDecl *Parent = Dtor->getParent();
18013         if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18014           CheckCompleteDestructorVariant(Loc, Dtor);
18015       }
18016     }
18017 
18018     Func->markUsed(Context);
18019   }
18020 }
18021 
18022 /// Directly mark a variable odr-used. Given a choice, prefer to use
18023 /// MarkVariableReferenced since it does additional checks and then
18024 /// calls MarkVarDeclODRUsed.
18025 /// If the variable must be captured:
18026 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18027 ///  - else capture it in the DeclContext that maps to the
18028 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18029 static void
18030 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
18031                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18032   // Keep track of used but undefined variables.
18033   // FIXME: We shouldn't suppress this warning for static data members.
18034   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18035       (!Var->isExternallyVisible() || Var->isInline() ||
18036        SemaRef.isExternalWithNoLinkageType(Var)) &&
18037       !(Var->isStaticDataMember() && Var->hasInit())) {
18038     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18039     if (old.isInvalid())
18040       old = Loc;
18041   }
18042   QualType CaptureType, DeclRefType;
18043   if (SemaRef.LangOpts.OpenMP)
18044     SemaRef.tryCaptureOpenMPLambdas(Var);
18045   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
18046     /*EllipsisLoc*/ SourceLocation(),
18047     /*BuildAndDiagnose*/ true,
18048     CaptureType, DeclRefType,
18049     FunctionScopeIndexToStopAt);
18050 
18051   if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18052     auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18053     auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
18054     auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
18055     if (VarTarget == Sema::CVT_Host &&
18056         (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
18057          UserTarget == Sema::CFT_Global)) {
18058       // Diagnose ODR-use of host global variables in device functions.
18059       // Reference of device global variables in host functions is allowed
18060       // through shadow variables therefore it is not diagnosed.
18061       if (SemaRef.LangOpts.CUDAIsDevice) {
18062         SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18063             << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18064         SemaRef.targetDiag(Var->getLocation(),
18065                            Var->getType().isConstQualified()
18066                                ? diag::note_cuda_const_var_unpromoted
18067                                : diag::note_cuda_host_var);
18068       }
18069     } else if (VarTarget == Sema::CVT_Device &&
18070                (UserTarget == Sema::CFT_Host ||
18071                 UserTarget == Sema::CFT_HostDevice)) {
18072       // Record a CUDA/HIP device side variable if it is ODR-used
18073       // by host code. This is done conservatively, when the variable is
18074       // referenced in any of the following contexts:
18075       //   - a non-function context
18076       //   - a host function
18077       //   - a host device function
18078       // This makes the ODR-use of the device side variable by host code to
18079       // be visible in the device compilation for the compiler to be able to
18080       // emit template variables instantiated by host code only and to
18081       // externalize the static device side variable ODR-used by host code.
18082       if (!Var->hasExternalStorage())
18083         SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
18084       else if (SemaRef.LangOpts.GPURelocatableDeviceCode)
18085         SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18086     }
18087   }
18088 
18089   Var->markUsed(SemaRef.Context);
18090 }
18091 
18092 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
18093                                              SourceLocation Loc,
18094                                              unsigned CapturingScopeIndex) {
18095   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18096 }
18097 
18098 static void diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
18099                                                ValueDecl *var) {
18100   DeclContext *VarDC = var->getDeclContext();
18101 
18102   //  If the parameter still belongs to the translation unit, then
18103   //  we're actually just using one parameter in the declaration of
18104   //  the next.
18105   if (isa<ParmVarDecl>(var) &&
18106       isa<TranslationUnitDecl>(VarDC))
18107     return;
18108 
18109   // For C code, don't diagnose about capture if we're not actually in code
18110   // right now; it's impossible to write a non-constant expression outside of
18111   // function context, so we'll get other (more useful) diagnostics later.
18112   //
18113   // For C++, things get a bit more nasty... it would be nice to suppress this
18114   // diagnostic for certain cases like using a local variable in an array bound
18115   // for a member of a local class, but the correct predicate is not obvious.
18116   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18117     return;
18118 
18119   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18120   unsigned ContextKind = 3; // unknown
18121   if (isa<CXXMethodDecl>(VarDC) &&
18122       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18123     ContextKind = 2;
18124   } else if (isa<FunctionDecl>(VarDC)) {
18125     ContextKind = 0;
18126   } else if (isa<BlockDecl>(VarDC)) {
18127     ContextKind = 1;
18128   }
18129 
18130   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18131     << var << ValueKind << ContextKind << VarDC;
18132   S.Diag(var->getLocation(), diag::note_entity_declared_at)
18133       << var;
18134 
18135   // FIXME: Add additional diagnostic info about class etc. which prevents
18136   // capture.
18137 }
18138 
18139 
18140 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
18141                                       bool &SubCapturesAreNested,
18142                                       QualType &CaptureType,
18143                                       QualType &DeclRefType) {
18144    // Check whether we've already captured it.
18145   if (CSI->CaptureMap.count(Var)) {
18146     // If we found a capture, any subcaptures are nested.
18147     SubCapturesAreNested = true;
18148 
18149     // Retrieve the capture type for this variable.
18150     CaptureType = CSI->getCapture(Var).getCaptureType();
18151 
18152     // Compute the type of an expression that refers to this variable.
18153     DeclRefType = CaptureType.getNonReferenceType();
18154 
18155     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18156     // are mutable in the sense that user can change their value - they are
18157     // private instances of the captured declarations.
18158     const Capture &Cap = CSI->getCapture(Var);
18159     if (Cap.isCopyCapture() &&
18160         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
18161         !(isa<CapturedRegionScopeInfo>(CSI) &&
18162           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18163       DeclRefType.addConst();
18164     return true;
18165   }
18166   return false;
18167 }
18168 
18169 // Only block literals, captured statements, and lambda expressions can
18170 // capture; other scopes don't work.
18171 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
18172                                  SourceLocation Loc,
18173                                  const bool Diagnose, Sema &S) {
18174   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18175     return getLambdaAwareParentOfDeclContext(DC);
18176   else if (Var->hasLocalStorage()) {
18177     if (Diagnose)
18178        diagnoseUncapturableValueReference(S, Loc, Var);
18179   }
18180   return nullptr;
18181 }
18182 
18183 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18184 // certain types of variables (unnamed, variably modified types etc.)
18185 // so check for eligibility.
18186 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
18187                                  SourceLocation Loc,
18188                                  const bool Diagnose, Sema &S) {
18189 
18190   bool IsBlock = isa<BlockScopeInfo>(CSI);
18191   bool IsLambda = isa<LambdaScopeInfo>(CSI);
18192 
18193   // Lambdas are not allowed to capture unnamed variables
18194   // (e.g. anonymous unions).
18195   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18196   // assuming that's the intent.
18197   if (IsLambda && !Var->getDeclName()) {
18198     if (Diagnose) {
18199       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18200       S.Diag(Var->getLocation(), diag::note_declared_at);
18201     }
18202     return false;
18203   }
18204 
18205   // Prohibit variably-modified types in blocks; they're difficult to deal with.
18206   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18207     if (Diagnose) {
18208       S.Diag(Loc, diag::err_ref_vm_type);
18209       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18210     }
18211     return false;
18212   }
18213   // Prohibit structs with flexible array members too.
18214   // We cannot capture what is in the tail end of the struct.
18215   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18216     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18217       if (Diagnose) {
18218         if (IsBlock)
18219           S.Diag(Loc, diag::err_ref_flexarray_type);
18220         else
18221           S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18222         S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18223       }
18224       return false;
18225     }
18226   }
18227   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18228   // Lambdas and captured statements are not allowed to capture __block
18229   // variables; they don't support the expected semantics.
18230   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18231     if (Diagnose) {
18232       S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18233       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18234     }
18235     return false;
18236   }
18237   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18238   if (S.getLangOpts().OpenCL && IsBlock &&
18239       Var->getType()->isBlockPointerType()) {
18240     if (Diagnose)
18241       S.Diag(Loc, diag::err_opencl_block_ref_block);
18242     return false;
18243   }
18244 
18245   return true;
18246 }
18247 
18248 // Returns true if the capture by block was successful.
18249 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
18250                                  SourceLocation Loc,
18251                                  const bool BuildAndDiagnose,
18252                                  QualType &CaptureType,
18253                                  QualType &DeclRefType,
18254                                  const bool Nested,
18255                                  Sema &S, bool Invalid) {
18256   bool ByRef = false;
18257 
18258   // Blocks are not allowed to capture arrays, excepting OpenCL.
18259   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18260   // (decayed to pointers).
18261   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18262     if (BuildAndDiagnose) {
18263       S.Diag(Loc, diag::err_ref_array_type);
18264       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18265       Invalid = true;
18266     } else {
18267       return false;
18268     }
18269   }
18270 
18271   // Forbid the block-capture of autoreleasing variables.
18272   if (!Invalid &&
18273       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18274     if (BuildAndDiagnose) {
18275       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18276         << /*block*/ 0;
18277       S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18278       Invalid = true;
18279     } else {
18280       return false;
18281     }
18282   }
18283 
18284   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18285   if (const auto *PT = CaptureType->getAs<PointerType>()) {
18286     QualType PointeeTy = PT->getPointeeType();
18287 
18288     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18289         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18290         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18291       if (BuildAndDiagnose) {
18292         SourceLocation VarLoc = Var->getLocation();
18293         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18294         S.Diag(VarLoc, diag::note_declare_parameter_strong);
18295       }
18296     }
18297   }
18298 
18299   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18300   if (HasBlocksAttr || CaptureType->isReferenceType() ||
18301       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
18302     // Block capture by reference does not change the capture or
18303     // declaration reference types.
18304     ByRef = true;
18305   } else {
18306     // Block capture by copy introduces 'const'.
18307     CaptureType = CaptureType.getNonReferenceType().withConst();
18308     DeclRefType = CaptureType;
18309   }
18310 
18311   // Actually capture the variable.
18312   if (BuildAndDiagnose)
18313     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18314                     CaptureType, Invalid);
18315 
18316   return !Invalid;
18317 }
18318 
18319 
18320 /// Capture the given variable in the captured region.
18321 static bool captureInCapturedRegion(
18322     CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
18323     const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18324     const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18325     bool IsTopScope, Sema &S, bool Invalid) {
18326   // By default, capture variables by reference.
18327   bool ByRef = true;
18328   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18329     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18330   } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18331     // Using an LValue reference type is consistent with Lambdas (see below).
18332     if (S.isOpenMPCapturedDecl(Var)) {
18333       bool HasConst = DeclRefType.isConstQualified();
18334       DeclRefType = DeclRefType.getUnqualifiedType();
18335       // Don't lose diagnostics about assignments to const.
18336       if (HasConst)
18337         DeclRefType.addConst();
18338     }
18339     // Do not capture firstprivates in tasks.
18340     if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
18341         OMPC_unknown)
18342       return true;
18343     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18344                                     RSI->OpenMPCaptureLevel);
18345   }
18346 
18347   if (ByRef)
18348     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18349   else
18350     CaptureType = DeclRefType;
18351 
18352   // Actually capture the variable.
18353   if (BuildAndDiagnose)
18354     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18355                     Loc, SourceLocation(), CaptureType, Invalid);
18356 
18357   return !Invalid;
18358 }
18359 
18360 /// Capture the given variable in the lambda.
18361 static bool captureInLambda(LambdaScopeInfo *LSI,
18362                             VarDecl *Var,
18363                             SourceLocation Loc,
18364                             const bool BuildAndDiagnose,
18365                             QualType &CaptureType,
18366                             QualType &DeclRefType,
18367                             const bool RefersToCapturedVariable,
18368                             const Sema::TryCaptureKind Kind,
18369                             SourceLocation EllipsisLoc,
18370                             const bool IsTopScope,
18371                             Sema &S, bool Invalid) {
18372   // Determine whether we are capturing by reference or by value.
18373   bool ByRef = false;
18374   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18375     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18376   } else {
18377     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18378   }
18379 
18380   // Compute the type of the field that will capture this variable.
18381   if (ByRef) {
18382     // C++11 [expr.prim.lambda]p15:
18383     //   An entity is captured by reference if it is implicitly or
18384     //   explicitly captured but not captured by copy. It is
18385     //   unspecified whether additional unnamed non-static data
18386     //   members are declared in the closure type for entities
18387     //   captured by reference.
18388     //
18389     // FIXME: It is not clear whether we want to build an lvalue reference
18390     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18391     // to do the former, while EDG does the latter. Core issue 1249 will
18392     // clarify, but for now we follow GCC because it's a more permissive and
18393     // easily defensible position.
18394     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18395   } else {
18396     // C++11 [expr.prim.lambda]p14:
18397     //   For each entity captured by copy, an unnamed non-static
18398     //   data member is declared in the closure type. The
18399     //   declaration order of these members is unspecified. The type
18400     //   of such a data member is the type of the corresponding
18401     //   captured entity if the entity is not a reference to an
18402     //   object, or the referenced type otherwise. [Note: If the
18403     //   captured entity is a reference to a function, the
18404     //   corresponding data member is also a reference to a
18405     //   function. - end note ]
18406     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18407       if (!RefType->getPointeeType()->isFunctionType())
18408         CaptureType = RefType->getPointeeType();
18409     }
18410 
18411     // Forbid the lambda copy-capture of autoreleasing variables.
18412     if (!Invalid &&
18413         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
18414       if (BuildAndDiagnose) {
18415         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18416         S.Diag(Var->getLocation(), diag::note_previous_decl)
18417           << Var->getDeclName();
18418         Invalid = true;
18419       } else {
18420         return false;
18421       }
18422     }
18423 
18424     // Make sure that by-copy captures are of a complete and non-abstract type.
18425     if (!Invalid && BuildAndDiagnose) {
18426       if (!CaptureType->isDependentType() &&
18427           S.RequireCompleteSizedType(
18428               Loc, CaptureType,
18429               diag::err_capture_of_incomplete_or_sizeless_type,
18430               Var->getDeclName()))
18431         Invalid = true;
18432       else if (S.RequireNonAbstractType(Loc, CaptureType,
18433                                         diag::err_capture_of_abstract_type))
18434         Invalid = true;
18435     }
18436   }
18437 
18438   // Compute the type of a reference to this captured variable.
18439   if (ByRef)
18440     DeclRefType = CaptureType.getNonReferenceType();
18441   else {
18442     // C++ [expr.prim.lambda]p5:
18443     //   The closure type for a lambda-expression has a public inline
18444     //   function call operator [...]. This function call operator is
18445     //   declared const (9.3.1) if and only if the lambda-expression's
18446     //   parameter-declaration-clause is not followed by mutable.
18447     DeclRefType = CaptureType.getNonReferenceType();
18448     if (!LSI->Mutable && !CaptureType->isReferenceType())
18449       DeclRefType.addConst();
18450   }
18451 
18452   // Add the capture.
18453   if (BuildAndDiagnose)
18454     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18455                     Loc, EllipsisLoc, CaptureType, Invalid);
18456 
18457   return !Invalid;
18458 }
18459 
18460 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
18461   // Offer a Copy fix even if the type is dependent.
18462   if (Var->getType()->isDependentType())
18463     return true;
18464   QualType T = Var->getType().getNonReferenceType();
18465   if (T.isTriviallyCopyableType(Context))
18466     return true;
18467   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18468 
18469     if (!(RD = RD->getDefinition()))
18470       return false;
18471     if (RD->hasSimpleCopyConstructor())
18472       return true;
18473     if (RD->hasUserDeclaredCopyConstructor())
18474       for (CXXConstructorDecl *Ctor : RD->ctors())
18475         if (Ctor->isCopyConstructor())
18476           return !Ctor->isDeleted();
18477   }
18478   return false;
18479 }
18480 
18481 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18482 /// default capture. Fixes may be omitted if they aren't allowed by the
18483 /// standard, for example we can't emit a default copy capture fix-it if we
18484 /// already explicitly copy capture capture another variable.
18485 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
18486                                     VarDecl *Var) {
18487   assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
18488   // Don't offer Capture by copy of default capture by copy fixes if Var is
18489   // known not to be copy constructible.
18490   bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18491 
18492   SmallString<32> FixBuffer;
18493   StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18494   if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18495     SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18496     if (ShouldOfferCopyFix) {
18497       // Offer fixes to insert an explicit capture for the variable.
18498       // [] -> [VarName]
18499       // [OtherCapture] -> [OtherCapture, VarName]
18500       FixBuffer.assign({Separator, Var->getName()});
18501       Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18502           << Var << /*value*/ 0
18503           << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18504     }
18505     // As above but capture by reference.
18506     FixBuffer.assign({Separator, "&", Var->getName()});
18507     Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18508         << Var << /*reference*/ 1
18509         << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18510   }
18511 
18512   // Only try to offer default capture if there are no captures excluding this
18513   // and init captures.
18514   // [this]: OK.
18515   // [X = Y]: OK.
18516   // [&A, &B]: Don't offer.
18517   // [A, B]: Don't offer.
18518   if (llvm::any_of(LSI->Captures, [](Capture &C) {
18519         return !C.isThisCapture() && !C.isInitCapture();
18520       }))
18521     return;
18522 
18523   // The default capture specifiers, '=' or '&', must appear first in the
18524   // capture body.
18525   SourceLocation DefaultInsertLoc =
18526       LSI->IntroducerRange.getBegin().getLocWithOffset(1);
18527 
18528   if (ShouldOfferCopyFix) {
18529     bool CanDefaultCopyCapture = true;
18530     // [=, *this] OK since c++17
18531     // [=, this] OK since c++20
18532     if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18533       CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18534                                   ? LSI->getCXXThisCapture().isCopyCapture()
18535                                   : false;
18536     // We can't use default capture by copy if any captures already specified
18537     // capture by copy.
18538     if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18539           return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18540         })) {
18541       FixBuffer.assign({"=", Separator});
18542       Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18543           << /*value*/ 0
18544           << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18545     }
18546   }
18547 
18548   // We can't use default capture by reference if any captures already specified
18549   // capture by reference.
18550   if (llvm::none_of(LSI->Captures, [](Capture &C) {
18551         return !C.isInitCapture() && C.isReferenceCapture() &&
18552                !C.isThisCapture();
18553       })) {
18554     FixBuffer.assign({"&", Separator});
18555     Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18556         << /*reference*/ 1
18557         << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18558   }
18559 }
18560 
18561 static bool CheckCaptureUseBeforeLambdaQualifiers(Sema &S, VarDecl *Var,
18562                                                   SourceLocation ExprLoc,
18563                                                   LambdaScopeInfo *LSI) {
18564 
18565   // Allow `[a = 1](decltype(a)) {}` as per CWG2569.
18566   if (S.InMutableAgnosticContext)
18567     return true;
18568 
18569   if (Var->isInvalidDecl())
18570     return false;
18571 
18572   bool ByCopy = LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval;
18573   SourceLocation Loc = LSI->IntroducerRange.getBegin();
18574   bool Explicitly = false;
18575   for (auto &&C : LSI->DelayedCaptures) {
18576     VarDecl *CV = C.second.Var;
18577     if (Var != CV)
18578       continue;
18579     ByCopy = C.second.Kind == LambdaCaptureKind::LCK_ByCopy;
18580     Loc = C.second.Loc;
18581     Explicitly = true;
18582     break;
18583   }
18584   if (ByCopy && LSI->BeforeLambdaQualifiersScope) {
18585     // This can only occur in a non-ODR context, so we need to diagnose eagerly,
18586     // even when BuildAndDiagnose is false
18587     S.Diag(ExprLoc, diag::err_lambda_used_before_capture) << Var;
18588     S.Diag(Loc, diag::note_var_explicitly_captured_here) << Var << Explicitly;
18589     if (!Var->isInitCapture())
18590       S.Diag(Var->getBeginLoc(), diag::note_entity_declared_at) << Var;
18591     Var->setInvalidDecl();
18592     return false;
18593   }
18594   return true;
18595 }
18596 
18597 bool Sema::tryCaptureVariable(
18598     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18599     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18600     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18601   // An init-capture is notionally from the context surrounding its
18602   // declaration, but its parent DC is the lambda class.
18603   DeclContext *VarDC = Var->getDeclContext();
18604   if (Var->isInitCapture())
18605     VarDC = VarDC->getParent();
18606 
18607   DeclContext *DC = CurContext;
18608   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18609       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18610   // We need to sync up the Declaration Context with the
18611   // FunctionScopeIndexToStopAt
18612   if (FunctionScopeIndexToStopAt) {
18613     unsigned FSIndex = FunctionScopes.size() - 1;
18614     while (FSIndex != MaxFunctionScopesIndex) {
18615       DC = getLambdaAwareParentOfDeclContext(DC);
18616       --FSIndex;
18617     }
18618   }
18619 
18620   // Capture global variables if it is required to use private copy of this
18621   // variable.
18622   bool IsGlobal = !Var->hasLocalStorage();
18623   if (IsGlobal &&
18624       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18625                                                 MaxFunctionScopesIndex)))
18626     return true;
18627   Var = Var->getCanonicalDecl();
18628 
18629   // Walk up the stack to determine whether we can capture the variable,
18630   // performing the "simple" checks that don't depend on type. We stop when
18631   // we've either hit the declared scope of the variable or find an existing
18632   // capture of that variable.  We start from the innermost capturing-entity
18633   // (the DC) and ensure that all intervening capturing-entities
18634   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18635   // declcontext can either capture the variable or have already captured
18636   // the variable.
18637   CaptureType = Var->getType();
18638   DeclRefType = CaptureType.getNonReferenceType();
18639   bool Nested = false;
18640   bool Explicit = (Kind != TryCapture_Implicit);
18641   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18642   bool IsInLambdaBeforeQualifiers;
18643   do {
18644     IsInLambdaBeforeQualifiers = false;
18645 
18646     LambdaScopeInfo *LSI = nullptr;
18647     if (!FunctionScopes.empty())
18648       LSI = dyn_cast_or_null<LambdaScopeInfo>(
18649           FunctionScopes[FunctionScopesIndex]);
18650     if (LSI && LSI->BeforeLambdaQualifiersScope) {
18651       if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18652         return true;
18653       IsInLambdaBeforeQualifiers = true;
18654       if (!CheckCaptureUseBeforeLambdaQualifiers(*this, Var, ExprLoc, LSI)) {
18655         break;
18656       }
18657     }
18658 
18659     // If the variable is declared in the current context, there is no need to
18660     // capture it.
18661     if (!IsInLambdaBeforeQualifiers &&
18662         FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18663       return true;
18664 
18665     // Only block literals, captured statements, and lambda expressions can
18666     // capture; other scopes don't work.
18667     DeclContext *ParentDC =
18668         IsInLambdaBeforeQualifiers
18669             ? DC->getParent()
18670             : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18671                                                 BuildAndDiagnose, *this);
18672     // We need to check for the parent *first* because, if we *have*
18673     // private-captured a global variable, we need to recursively capture it in
18674     // intermediate blocks, lambdas, etc.
18675     if (!ParentDC) {
18676       if (IsGlobal) {
18677         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18678         break;
18679       }
18680       return true;
18681     }
18682 
18683     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
18684     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18685 
18686     // Check whether we've already captured it.
18687     if (!IsInLambdaBeforeQualifiers &&
18688         isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18689                                              DeclRefType)) {
18690       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18691       break;
18692     }
18693     // If we are instantiating a generic lambda call operator body,
18694     // we do not want to capture new variables.  What was captured
18695     // during either a lambdas transformation or initial parsing
18696     // should be used.
18697     if (!IsInLambdaBeforeQualifiers &&
18698         isGenericLambdaCallOperatorSpecialization(DC)) {
18699       if (BuildAndDiagnose) {
18700         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18701         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
18702           Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18703           Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18704           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18705           buildLambdaCaptureFixit(*this, LSI, Var);
18706         } else
18707           diagnoseUncapturableValueReference(*this, ExprLoc, Var);
18708       }
18709       return true;
18710     }
18711 
18712     // Try to capture variable-length arrays types.
18713     if (!IsInLambdaBeforeQualifiers &&
18714         Var->getType()->isVariablyModifiedType()) {
18715       // We're going to walk down into the type and look for VLA
18716       // expressions.
18717       QualType QTy = Var->getType();
18718       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18719         QTy = PVD->getOriginalType();
18720       captureVariablyModifiedType(Context, QTy, CSI);
18721     }
18722 
18723     if (!IsInLambdaBeforeQualifiers && getLangOpts().OpenMP) {
18724       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18725         // OpenMP private variables should not be captured in outer scope, so
18726         // just break here. Similarly, global variables that are captured in a
18727         // target region should not be captured outside the scope of the region.
18728         if (RSI->CapRegionKind == CR_OpenMP) {
18729           OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
18730               Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18731           // If the variable is private (i.e. not captured) and has variably
18732           // modified type, we still need to capture the type for correct
18733           // codegen in all regions, associated with the construct. Currently,
18734           // it is captured in the innermost captured region only.
18735           if (IsOpenMPPrivateDecl != OMPC_unknown &&
18736               Var->getType()->isVariablyModifiedType()) {
18737             QualType QTy = Var->getType();
18738             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18739               QTy = PVD->getOriginalType();
18740             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
18741                  I < E; ++I) {
18742               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18743                   FunctionScopes[FunctionScopesIndex - I]);
18744               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18745                      "Wrong number of captured regions associated with the "
18746                      "OpenMP construct.");
18747               captureVariablyModifiedType(Context, QTy, OuterRSI);
18748             }
18749           }
18750           bool IsTargetCap =
18751               IsOpenMPPrivateDecl != OMPC_private &&
18752               isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18753                                          RSI->OpenMPCaptureLevel);
18754           // Do not capture global if it is not privatized in outer regions.
18755           bool IsGlobalCap =
18756               IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
18757                                                      RSI->OpenMPCaptureLevel);
18758 
18759           // When we detect target captures we are looking from inside the
18760           // target region, therefore we need to propagate the capture from the
18761           // enclosing region. Therefore, the capture is not initially nested.
18762           if (IsTargetCap)
18763             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
18764 
18765           if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18766               (IsGlobal && !IsGlobalCap)) {
18767             Nested = !IsTargetCap;
18768             bool HasConst = DeclRefType.isConstQualified();
18769             DeclRefType = DeclRefType.getUnqualifiedType();
18770             // Don't lose diagnostics about assignments to const.
18771             if (HasConst)
18772               DeclRefType.addConst();
18773             CaptureType = Context.getLValueReferenceType(DeclRefType);
18774             break;
18775           }
18776         }
18777       }
18778     }
18779     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18780       // No capture-default, and this is not an explicit capture
18781       // so cannot capture this variable.
18782       if (BuildAndDiagnose) {
18783         Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18784         Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18785         auto *LSI = cast<LambdaScopeInfo>(CSI);
18786         if (LSI->Lambda) {
18787           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18788           buildLambdaCaptureFixit(*this, LSI, Var);
18789         }
18790         // FIXME: If we error out because an outer lambda can not implicitly
18791         // capture a variable that an inner lambda explicitly captures, we
18792         // should have the inner lambda do the explicit capture - because
18793         // it makes for cleaner diagnostics later.  This would purely be done
18794         // so that the diagnostic does not misleadingly claim that a variable
18795         // can not be captured by a lambda implicitly even though it is captured
18796         // explicitly.  Suggestion:
18797         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18798         //    at the function head
18799         //  - cache the StartingDeclContext - this must be a lambda
18800         //  - captureInLambda in the innermost lambda the variable.
18801       }
18802       return true;
18803     }
18804     Explicit = false;
18805     FunctionScopesIndex--;
18806     if (!IsInLambdaBeforeQualifiers)
18807       DC = ParentDC;
18808   } while (IsInLambdaBeforeQualifiers || !VarDC->Equals(DC));
18809 
18810   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18811   // computing the type of the capture at each step, checking type-specific
18812   // requirements, and adding captures if requested.
18813   // If the variable had already been captured previously, we start capturing
18814   // at the lambda nested within that one.
18815   bool Invalid = false;
18816   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18817        ++I) {
18818     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18819 
18820     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18821     // certain types of variables (unnamed, variably modified types etc.)
18822     // so check for eligibility.
18823     if (!Invalid)
18824       Invalid =
18825           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18826 
18827     // After encountering an error, if we're actually supposed to capture, keep
18828     // capturing in nested contexts to suppress any follow-on diagnostics.
18829     if (Invalid && !BuildAndDiagnose)
18830       return true;
18831 
18832     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18833       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18834                                DeclRefType, Nested, *this, Invalid);
18835       Nested = true;
18836     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18837       Invalid = !captureInCapturedRegion(
18838           RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18839           Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18840       Nested = true;
18841     } else {
18842       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18843       if (!CheckCaptureUseBeforeLambdaQualifiers(*this, Var, ExprLoc, LSI)) {
18844         return true;
18845       }
18846       Invalid =
18847           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18848                            DeclRefType, Nested, Kind, EllipsisLoc,
18849                            /*IsTopScope*/ I == N - 1, *this, Invalid);
18850       Nested = true;
18851     }
18852 
18853     if (Invalid && !BuildAndDiagnose)
18854       return true;
18855   }
18856   return Invalid;
18857 }
18858 
18859 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
18860                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18861   QualType CaptureType;
18862   QualType DeclRefType;
18863   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18864                             /*BuildAndDiagnose=*/true, CaptureType,
18865                             DeclRefType, nullptr);
18866 }
18867 
18868 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
18869   QualType CaptureType;
18870   QualType DeclRefType;
18871   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18872                              /*BuildAndDiagnose=*/false, CaptureType,
18873                              DeclRefType, nullptr);
18874 }
18875 
18876 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
18877   QualType CaptureType;
18878   QualType DeclRefType;
18879 
18880   // Determine whether we can capture this variable.
18881   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
18882                          /*BuildAndDiagnose=*/false, CaptureType,
18883                          DeclRefType, nullptr))
18884     return QualType();
18885 
18886   return DeclRefType;
18887 }
18888 
18889 namespace {
18890 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
18891 // The produced TemplateArgumentListInfo* points to data stored within this
18892 // object, so should only be used in contexts where the pointer will not be
18893 // used after the CopiedTemplateArgs object is destroyed.
18894 class CopiedTemplateArgs {
18895   bool HasArgs;
18896   TemplateArgumentListInfo TemplateArgStorage;
18897 public:
18898   template<typename RefExpr>
18899   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
18900     if (HasArgs)
18901       E->copyTemplateArgumentsInto(TemplateArgStorage);
18902   }
18903   operator TemplateArgumentListInfo*()
18904 #ifdef __has_cpp_attribute
18905 #if __has_cpp_attribute(clang::lifetimebound)
18906   [[clang::lifetimebound]]
18907 #endif
18908 #endif
18909   {
18910     return HasArgs ? &TemplateArgStorage : nullptr;
18911   }
18912 };
18913 }
18914 
18915 /// Walk the set of potential results of an expression and mark them all as
18916 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
18917 ///
18918 /// \return A new expression if we found any potential results, ExprEmpty() if
18919 ///         not, and ExprError() if we diagnosed an error.
18920 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
18921                                                       NonOdrUseReason NOUR) {
18922   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
18923   // an object that satisfies the requirements for appearing in a
18924   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
18925   // is immediately applied."  This function handles the lvalue-to-rvalue
18926   // conversion part.
18927   //
18928   // If we encounter a node that claims to be an odr-use but shouldn't be, we
18929   // transform it into the relevant kind of non-odr-use node and rebuild the
18930   // tree of nodes leading to it.
18931   //
18932   // This is a mini-TreeTransform that only transforms a restricted subset of
18933   // nodes (and only certain operands of them).
18934 
18935   // Rebuild a subexpression.
18936   auto Rebuild = [&](Expr *Sub) {
18937     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
18938   };
18939 
18940   // Check whether a potential result satisfies the requirements of NOUR.
18941   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
18942     // Any entity other than a VarDecl is always odr-used whenever it's named
18943     // in a potentially-evaluated expression.
18944     auto *VD = dyn_cast<VarDecl>(D);
18945     if (!VD)
18946       return true;
18947 
18948     // C++2a [basic.def.odr]p4:
18949     //   A variable x whose name appears as a potentially-evalauted expression
18950     //   e is odr-used by e unless
18951     //   -- x is a reference that is usable in constant expressions, or
18952     //   -- x is a variable of non-reference type that is usable in constant
18953     //      expressions and has no mutable subobjects, and e is an element of
18954     //      the set of potential results of an expression of
18955     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
18956     //      conversion is applied, or
18957     //   -- x is a variable of non-reference type, and e is an element of the
18958     //      set of potential results of a discarded-value expression to which
18959     //      the lvalue-to-rvalue conversion is not applied
18960     //
18961     // We check the first bullet and the "potentially-evaluated" condition in
18962     // BuildDeclRefExpr. We check the type requirements in the second bullet
18963     // in CheckLValueToRValueConversionOperand below.
18964     switch (NOUR) {
18965     case NOUR_None:
18966     case NOUR_Unevaluated:
18967       llvm_unreachable("unexpected non-odr-use-reason");
18968 
18969     case NOUR_Constant:
18970       // Constant references were handled when they were built.
18971       if (VD->getType()->isReferenceType())
18972         return true;
18973       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18974         if (RD->hasMutableFields())
18975           return true;
18976       if (!VD->isUsableInConstantExpressions(S.Context))
18977         return true;
18978       break;
18979 
18980     case NOUR_Discarded:
18981       if (VD->getType()->isReferenceType())
18982         return true;
18983       break;
18984     }
18985     return false;
18986   };
18987 
18988   // Mark that this expression does not constitute an odr-use.
18989   auto MarkNotOdrUsed = [&] {
18990     S.MaybeODRUseExprs.remove(E);
18991     if (LambdaScopeInfo *LSI = S.getCurLambda())
18992       LSI->markVariableExprAsNonODRUsed(E);
18993   };
18994 
18995   // C++2a [basic.def.odr]p2:
18996   //   The set of potential results of an expression e is defined as follows:
18997   switch (E->getStmtClass()) {
18998   //   -- If e is an id-expression, ...
18999   case Expr::DeclRefExprClass: {
19000     auto *DRE = cast<DeclRefExpr>(E);
19001     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19002       break;
19003 
19004     // Rebuild as a non-odr-use DeclRefExpr.
19005     MarkNotOdrUsed();
19006     return DeclRefExpr::Create(
19007         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19008         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19009         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19010         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19011   }
19012 
19013   case Expr::FunctionParmPackExprClass: {
19014     auto *FPPE = cast<FunctionParmPackExpr>(E);
19015     // If any of the declarations in the pack is odr-used, then the expression
19016     // as a whole constitutes an odr-use.
19017     for (VarDecl *D : *FPPE)
19018       if (IsPotentialResultOdrUsed(D))
19019         return ExprEmpty();
19020 
19021     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19022     // nothing cares about whether we marked this as an odr-use, but it might
19023     // be useful for non-compiler tools.
19024     MarkNotOdrUsed();
19025     break;
19026   }
19027 
19028   //   -- If e is a subscripting operation with an array operand...
19029   case Expr::ArraySubscriptExprClass: {
19030     auto *ASE = cast<ArraySubscriptExpr>(E);
19031     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19032     if (!OldBase->getType()->isArrayType())
19033       break;
19034     ExprResult Base = Rebuild(OldBase);
19035     if (!Base.isUsable())
19036       return Base;
19037     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19038     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19039     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19040     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19041                                      ASE->getRBracketLoc());
19042   }
19043 
19044   case Expr::MemberExprClass: {
19045     auto *ME = cast<MemberExpr>(E);
19046     // -- If e is a class member access expression [...] naming a non-static
19047     //    data member...
19048     if (isa<FieldDecl>(ME->getMemberDecl())) {
19049       ExprResult Base = Rebuild(ME->getBase());
19050       if (!Base.isUsable())
19051         return Base;
19052       return MemberExpr::Create(
19053           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19054           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19055           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19056           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19057           ME->getObjectKind(), ME->isNonOdrUse());
19058     }
19059 
19060     if (ME->getMemberDecl()->isCXXInstanceMember())
19061       break;
19062 
19063     // -- If e is a class member access expression naming a static data member,
19064     //    ...
19065     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19066       break;
19067 
19068     // Rebuild as a non-odr-use MemberExpr.
19069     MarkNotOdrUsed();
19070     return MemberExpr::Create(
19071         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19072         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19073         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19074         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19075   }
19076 
19077   case Expr::BinaryOperatorClass: {
19078     auto *BO = cast<BinaryOperator>(E);
19079     Expr *LHS = BO->getLHS();
19080     Expr *RHS = BO->getRHS();
19081     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19082     if (BO->getOpcode() == BO_PtrMemD) {
19083       ExprResult Sub = Rebuild(LHS);
19084       if (!Sub.isUsable())
19085         return Sub;
19086       LHS = Sub.get();
19087     //   -- If e is a comma expression, ...
19088     } else if (BO->getOpcode() == BO_Comma) {
19089       ExprResult Sub = Rebuild(RHS);
19090       if (!Sub.isUsable())
19091         return Sub;
19092       RHS = Sub.get();
19093     } else {
19094       break;
19095     }
19096     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19097                         LHS, RHS);
19098   }
19099 
19100   //   -- If e has the form (e1)...
19101   case Expr::ParenExprClass: {
19102     auto *PE = cast<ParenExpr>(E);
19103     ExprResult Sub = Rebuild(PE->getSubExpr());
19104     if (!Sub.isUsable())
19105       return Sub;
19106     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19107   }
19108 
19109   //   -- If e is a glvalue conditional expression, ...
19110   // We don't apply this to a binary conditional operator. FIXME: Should we?
19111   case Expr::ConditionalOperatorClass: {
19112     auto *CO = cast<ConditionalOperator>(E);
19113     ExprResult LHS = Rebuild(CO->getLHS());
19114     if (LHS.isInvalid())
19115       return ExprError();
19116     ExprResult RHS = Rebuild(CO->getRHS());
19117     if (RHS.isInvalid())
19118       return ExprError();
19119     if (!LHS.isUsable() && !RHS.isUsable())
19120       return ExprEmpty();
19121     if (!LHS.isUsable())
19122       LHS = CO->getLHS();
19123     if (!RHS.isUsable())
19124       RHS = CO->getRHS();
19125     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19126                                 CO->getCond(), LHS.get(), RHS.get());
19127   }
19128 
19129   // [Clang extension]
19130   //   -- If e has the form __extension__ e1...
19131   case Expr::UnaryOperatorClass: {
19132     auto *UO = cast<UnaryOperator>(E);
19133     if (UO->getOpcode() != UO_Extension)
19134       break;
19135     ExprResult Sub = Rebuild(UO->getSubExpr());
19136     if (!Sub.isUsable())
19137       return Sub;
19138     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19139                           Sub.get());
19140   }
19141 
19142   // [Clang extension]
19143   //   -- If e has the form _Generic(...), the set of potential results is the
19144   //      union of the sets of potential results of the associated expressions.
19145   case Expr::GenericSelectionExprClass: {
19146     auto *GSE = cast<GenericSelectionExpr>(E);
19147 
19148     SmallVector<Expr *, 4> AssocExprs;
19149     bool AnyChanged = false;
19150     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19151       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19152       if (AssocExpr.isInvalid())
19153         return ExprError();
19154       if (AssocExpr.isUsable()) {
19155         AssocExprs.push_back(AssocExpr.get());
19156         AnyChanged = true;
19157       } else {
19158         AssocExprs.push_back(OrigAssocExpr);
19159       }
19160     }
19161 
19162     return AnyChanged ? S.CreateGenericSelectionExpr(
19163                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
19164                             GSE->getRParenLoc(), GSE->getControllingExpr(),
19165                             GSE->getAssocTypeSourceInfos(), AssocExprs)
19166                       : ExprEmpty();
19167   }
19168 
19169   // [Clang extension]
19170   //   -- If e has the form __builtin_choose_expr(...), the set of potential
19171   //      results is the union of the sets of potential results of the
19172   //      second and third subexpressions.
19173   case Expr::ChooseExprClass: {
19174     auto *CE = cast<ChooseExpr>(E);
19175 
19176     ExprResult LHS = Rebuild(CE->getLHS());
19177     if (LHS.isInvalid())
19178       return ExprError();
19179 
19180     ExprResult RHS = Rebuild(CE->getLHS());
19181     if (RHS.isInvalid())
19182       return ExprError();
19183 
19184     if (!LHS.get() && !RHS.get())
19185       return ExprEmpty();
19186     if (!LHS.isUsable())
19187       LHS = CE->getLHS();
19188     if (!RHS.isUsable())
19189       RHS = CE->getRHS();
19190 
19191     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19192                              RHS.get(), CE->getRParenLoc());
19193   }
19194 
19195   // Step through non-syntactic nodes.
19196   case Expr::ConstantExprClass: {
19197     auto *CE = cast<ConstantExpr>(E);
19198     ExprResult Sub = Rebuild(CE->getSubExpr());
19199     if (!Sub.isUsable())
19200       return Sub;
19201     return ConstantExpr::Create(S.Context, Sub.get());
19202   }
19203 
19204   // We could mostly rely on the recursive rebuilding to rebuild implicit
19205   // casts, but not at the top level, so rebuild them here.
19206   case Expr::ImplicitCastExprClass: {
19207     auto *ICE = cast<ImplicitCastExpr>(E);
19208     // Only step through the narrow set of cast kinds we expect to encounter.
19209     // Anything else suggests we've left the region in which potential results
19210     // can be found.
19211     switch (ICE->getCastKind()) {
19212     case CK_NoOp:
19213     case CK_DerivedToBase:
19214     case CK_UncheckedDerivedToBase: {
19215       ExprResult Sub = Rebuild(ICE->getSubExpr());
19216       if (!Sub.isUsable())
19217         return Sub;
19218       CXXCastPath Path(ICE->path());
19219       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19220                                  ICE->getValueKind(), &Path);
19221     }
19222 
19223     default:
19224       break;
19225     }
19226     break;
19227   }
19228 
19229   default:
19230     break;
19231   }
19232 
19233   // Can't traverse through this node. Nothing to do.
19234   return ExprEmpty();
19235 }
19236 
19237 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19238   // Check whether the operand is or contains an object of non-trivial C union
19239   // type.
19240   if (E->getType().isVolatileQualified() &&
19241       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19242        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19243     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
19244                           Sema::NTCUC_LValueToRValueVolatile,
19245                           NTCUK_Destruct|NTCUK_Copy);
19246 
19247   // C++2a [basic.def.odr]p4:
19248   //   [...] an expression of non-volatile-qualified non-class type to which
19249   //   the lvalue-to-rvalue conversion is applied [...]
19250   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19251     return E;
19252 
19253   ExprResult Result =
19254       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
19255   if (Result.isInvalid())
19256     return ExprError();
19257   return Result.get() ? Result : E;
19258 }
19259 
19260 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19261   Res = CorrectDelayedTyposInExpr(Res);
19262 
19263   if (!Res.isUsable())
19264     return Res;
19265 
19266   // If a constant-expression is a reference to a variable where we delay
19267   // deciding whether it is an odr-use, just assume we will apply the
19268   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
19269   // (a non-type template argument), we have special handling anyway.
19270   return CheckLValueToRValueConversionOperand(Res.get());
19271 }
19272 
19273 void Sema::CleanupVarDeclMarking() {
19274   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19275   // call.
19276   MaybeODRUseExprSet LocalMaybeODRUseExprs;
19277   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19278 
19279   for (Expr *E : LocalMaybeODRUseExprs) {
19280     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19281       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19282                          DRE->getLocation(), *this);
19283     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19284       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19285                          *this);
19286     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19287       for (VarDecl *VD : *FP)
19288         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19289     } else {
19290       llvm_unreachable("Unexpected expression");
19291     }
19292   }
19293 
19294   assert(MaybeODRUseExprs.empty() &&
19295          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19296 }
19297 
19298 static void DoMarkVarDeclReferenced(
19299     Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19300     llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19301   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19302           isa<FunctionParmPackExpr>(E)) &&
19303          "Invalid Expr argument to DoMarkVarDeclReferenced");
19304   Var->setReferenced();
19305 
19306   if (Var->isInvalidDecl())
19307     return;
19308 
19309   auto *MSI = Var->getMemberSpecializationInfo();
19310   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19311                                        : Var->getTemplateSpecializationKind();
19312 
19313   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19314   bool UsableInConstantExpr =
19315       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
19316 
19317   if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19318     RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19319   }
19320 
19321   // C++20 [expr.const]p12:
19322   //   A variable [...] is needed for constant evaluation if it is [...] a
19323   //   variable whose name appears as a potentially constant evaluated
19324   //   expression that is either a contexpr variable or is of non-volatile
19325   //   const-qualified integral type or of reference type
19326   bool NeededForConstantEvaluation =
19327       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19328 
19329   bool NeedDefinition =
19330       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19331 
19332   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19333          "Can't instantiate a partial template specialization.");
19334 
19335   // If this might be a member specialization of a static data member, check
19336   // the specialization is visible. We already did the checks for variable
19337   // template specializations when we created them.
19338   if (NeedDefinition && TSK != TSK_Undeclared &&
19339       !isa<VarTemplateSpecializationDecl>(Var))
19340     SemaRef.checkSpecializationVisibility(Loc, Var);
19341 
19342   // Perform implicit instantiation of static data members, static data member
19343   // templates of class templates, and variable template specializations. Delay
19344   // instantiations of variable templates, except for those that could be used
19345   // in a constant expression.
19346   if (NeedDefinition && isTemplateInstantiation(TSK)) {
19347     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19348     // instantiation declaration if a variable is usable in a constant
19349     // expression (among other cases).
19350     bool TryInstantiating =
19351         TSK == TSK_ImplicitInstantiation ||
19352         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19353 
19354     if (TryInstantiating) {
19355       SourceLocation PointOfInstantiation =
19356           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19357       bool FirstInstantiation = PointOfInstantiation.isInvalid();
19358       if (FirstInstantiation) {
19359         PointOfInstantiation = Loc;
19360         if (MSI)
19361           MSI->setPointOfInstantiation(PointOfInstantiation);
19362           // FIXME: Notify listener.
19363         else
19364           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19365       }
19366 
19367       if (UsableInConstantExpr) {
19368         // Do not defer instantiations of variables that could be used in a
19369         // constant expression.
19370         SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19371           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19372         });
19373 
19374         // Re-set the member to trigger a recomputation of the dependence bits
19375         // for the expression.
19376         if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19377           DRE->setDecl(DRE->getDecl());
19378         else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19379           ME->setMemberDecl(ME->getMemberDecl());
19380       } else if (FirstInstantiation ||
19381                  isa<VarTemplateSpecializationDecl>(Var)) {
19382         // FIXME: For a specialization of a variable template, we don't
19383         // distinguish between "declaration and type implicitly instantiated"
19384         // and "implicit instantiation of definition requested", so we have
19385         // no direct way to avoid enqueueing the pending instantiation
19386         // multiple times.
19387         SemaRef.PendingInstantiations
19388             .push_back(std::make_pair(Var, PointOfInstantiation));
19389       }
19390     }
19391   }
19392 
19393   // C++2a [basic.def.odr]p4:
19394   //   A variable x whose name appears as a potentially-evaluated expression e
19395   //   is odr-used by e unless
19396   //   -- x is a reference that is usable in constant expressions
19397   //   -- x is a variable of non-reference type that is usable in constant
19398   //      expressions and has no mutable subobjects [FIXME], and e is an
19399   //      element of the set of potential results of an expression of
19400   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
19401   //      conversion is applied
19402   //   -- x is a variable of non-reference type, and e is an element of the set
19403   //      of potential results of a discarded-value expression to which the
19404   //      lvalue-to-rvalue conversion is not applied [FIXME]
19405   //
19406   // We check the first part of the second bullet here, and
19407   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19408   // FIXME: To get the third bullet right, we need to delay this even for
19409   // variables that are not usable in constant expressions.
19410 
19411   // If we already know this isn't an odr-use, there's nothing more to do.
19412   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19413     if (DRE->isNonOdrUse())
19414       return;
19415   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19416     if (ME->isNonOdrUse())
19417       return;
19418 
19419   switch (OdrUse) {
19420   case OdrUseContext::None:
19421     assert((!E || isa<FunctionParmPackExpr>(E)) &&
19422            "missing non-odr-use marking for unevaluated decl ref");
19423     break;
19424 
19425   case OdrUseContext::FormallyOdrUsed:
19426     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19427     // behavior.
19428     break;
19429 
19430   case OdrUseContext::Used:
19431     // If we might later find that this expression isn't actually an odr-use,
19432     // delay the marking.
19433     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
19434       SemaRef.MaybeODRUseExprs.insert(E);
19435     else
19436       MarkVarDeclODRUsed(Var, Loc, SemaRef);
19437     break;
19438 
19439   case OdrUseContext::Dependent:
19440     // If this is a dependent context, we don't need to mark variables as
19441     // odr-used, but we may still need to track them for lambda capture.
19442     // FIXME: Do we also need to do this inside dependent typeid expressions
19443     // (which are modeled as unevaluated at this point)?
19444     const bool RefersToEnclosingScope =
19445         (SemaRef.CurContext != Var->getDeclContext() &&
19446          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
19447     if (RefersToEnclosingScope) {
19448       LambdaScopeInfo *const LSI =
19449           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19450       if (LSI && (!LSI->CallOperator ||
19451                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19452         // If a variable could potentially be odr-used, defer marking it so
19453         // until we finish analyzing the full expression for any
19454         // lvalue-to-rvalue
19455         // or discarded value conversions that would obviate odr-use.
19456         // Add it to the list of potential captures that will be analyzed
19457         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19458         // unless the variable is a reference that was initialized by a constant
19459         // expression (this will never need to be captured or odr-used).
19460         //
19461         // FIXME: We can simplify this a lot after implementing P0588R1.
19462         assert(E && "Capture variable should be used in an expression.");
19463         if (!Var->getType()->isReferenceType() ||
19464             !Var->isUsableInConstantExpressions(SemaRef.Context))
19465           LSI->addPotentialCapture(E->IgnoreParens());
19466       }
19467     }
19468     break;
19469   }
19470 }
19471 
19472 /// Mark a variable referenced, and check whether it is odr-used
19473 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
19474 /// used directly for normal expressions referring to VarDecl.
19475 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
19476   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19477 }
19478 
19479 static void
19480 MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
19481                    bool MightBeOdrUse,
19482                    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19483   if (SemaRef.isInOpenMPDeclareTargetContext())
19484     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
19485 
19486   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19487     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
19488     return;
19489   }
19490 
19491   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19492 
19493   // If this is a call to a method via a cast, also mark the method in the
19494   // derived class used in case codegen can devirtualize the call.
19495   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19496   if (!ME)
19497     return;
19498   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19499   if (!MD)
19500     return;
19501   // Only attempt to devirtualize if this is truly a virtual call.
19502   bool IsVirtualCall = MD->isVirtual() &&
19503                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
19504   if (!IsVirtualCall)
19505     return;
19506 
19507   // If it's possible to devirtualize the call, mark the called function
19508   // referenced.
19509   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
19510       ME->getBase(), SemaRef.getLangOpts().AppleKext);
19511   if (DM)
19512     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19513 }
19514 
19515 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19516 ///
19517 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19518 /// handled with care if the DeclRefExpr is not newly-created.
19519 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
19520   // TODO: update this with DR# once a defect report is filed.
19521   // C++11 defect. The address of a pure member should not be an ODR use, even
19522   // if it's a qualified reference.
19523   bool OdrUse = true;
19524   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19525     if (Method->isVirtual() &&
19526         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19527       OdrUse = false;
19528 
19529   if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
19530     if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19531         FD->isConsteval() && !RebuildingImmediateInvocation)
19532       ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19533   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19534                      RefsMinusAssignments);
19535 }
19536 
19537 /// Perform reference-marking and odr-use handling for a MemberExpr.
19538 void Sema::MarkMemberReferenced(MemberExpr *E) {
19539   // C++11 [basic.def.odr]p2:
19540   //   A non-overloaded function whose name appears as a potentially-evaluated
19541   //   expression or a member of a set of candidate functions, if selected by
19542   //   overload resolution when referred to from a potentially-evaluated
19543   //   expression, is odr-used, unless it is a pure virtual function and its
19544   //   name is not explicitly qualified.
19545   bool MightBeOdrUse = true;
19546   if (E->performsVirtualDispatch(getLangOpts())) {
19547     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19548       if (Method->isPure())
19549         MightBeOdrUse = false;
19550   }
19551   SourceLocation Loc =
19552       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19553   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19554                      RefsMinusAssignments);
19555 }
19556 
19557 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
19558 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
19559   for (VarDecl *VD : *E)
19560     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19561                        RefsMinusAssignments);
19562 }
19563 
19564 /// Perform marking for a reference to an arbitrary declaration.  It
19565 /// marks the declaration referenced, and performs odr-use checking for
19566 /// functions and variables. This method should not be used when building a
19567 /// normal expression which refers to a variable.
19568 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
19569                                  bool MightBeOdrUse) {
19570   if (MightBeOdrUse) {
19571     if (auto *VD = dyn_cast<VarDecl>(D)) {
19572       MarkVariableReferenced(Loc, VD);
19573       return;
19574     }
19575   }
19576   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19577     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19578     return;
19579   }
19580   D->setReferenced();
19581 }
19582 
19583 namespace {
19584   // Mark all of the declarations used by a type as referenced.
19585   // FIXME: Not fully implemented yet! We need to have a better understanding
19586   // of when we're entering a context we should not recurse into.
19587   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19588   // TreeTransforms rebuilding the type in a new context. Rather than
19589   // duplicating the TreeTransform logic, we should consider reusing it here.
19590   // Currently that causes problems when rebuilding LambdaExprs.
19591   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19592     Sema &S;
19593     SourceLocation Loc;
19594 
19595   public:
19596     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
19597 
19598     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19599 
19600     bool TraverseTemplateArgument(const TemplateArgument &Arg);
19601   };
19602 }
19603 
19604 bool MarkReferencedDecls::TraverseTemplateArgument(
19605     const TemplateArgument &Arg) {
19606   {
19607     // A non-type template argument is a constant-evaluated context.
19608     EnterExpressionEvaluationContext Evaluated(
19609         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
19610     if (Arg.getKind() == TemplateArgument::Declaration) {
19611       if (Decl *D = Arg.getAsDecl())
19612         S.MarkAnyDeclReferenced(Loc, D, true);
19613     } else if (Arg.getKind() == TemplateArgument::Expression) {
19614       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
19615     }
19616   }
19617 
19618   return Inherited::TraverseTemplateArgument(Arg);
19619 }
19620 
19621 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
19622   MarkReferencedDecls Marker(*this, Loc);
19623   Marker.TraverseType(T);
19624 }
19625 
19626 namespace {
19627 /// Helper class that marks all of the declarations referenced by
19628 /// potentially-evaluated subexpressions as "referenced".
19629 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19630 public:
19631   typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19632   bool SkipLocalVariables;
19633   ArrayRef<const Expr *> StopAt;
19634 
19635   EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19636                       ArrayRef<const Expr *> StopAt)
19637       : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19638 
19639   void visitUsedDecl(SourceLocation Loc, Decl *D) {
19640     S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19641   }
19642 
19643   void Visit(Expr *E) {
19644     if (std::find(StopAt.begin(), StopAt.end(), E) != StopAt.end())
19645       return;
19646     Inherited::Visit(E);
19647   }
19648 
19649   void VisitDeclRefExpr(DeclRefExpr *E) {
19650     // If we were asked not to visit local variables, don't.
19651     if (SkipLocalVariables) {
19652       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19653         if (VD->hasLocalStorage())
19654           return;
19655     }
19656 
19657     // FIXME: This can trigger the instantiation of the initializer of a
19658     // variable, which can cause the expression to become value-dependent
19659     // or error-dependent. Do we need to propagate the new dependence bits?
19660     S.MarkDeclRefReferenced(E);
19661   }
19662 
19663   void VisitMemberExpr(MemberExpr *E) {
19664     S.MarkMemberReferenced(E);
19665     Visit(E->getBase());
19666   }
19667 };
19668 } // namespace
19669 
19670 /// Mark any declarations that appear within this expression or any
19671 /// potentially-evaluated subexpressions as "referenced".
19672 ///
19673 /// \param SkipLocalVariables If true, don't mark local variables as
19674 /// 'referenced'.
19675 /// \param StopAt Subexpressions that we shouldn't recurse into.
19676 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
19677                                             bool SkipLocalVariables,
19678                                             ArrayRef<const Expr*> StopAt) {
19679   EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19680 }
19681 
19682 /// Emit a diagnostic when statements are reachable.
19683 /// FIXME: check for reachability even in expressions for which we don't build a
19684 ///        CFG (eg, in the initializer of a global or in a constant expression).
19685 ///        For example,
19686 ///        namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19687 bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
19688                            const PartialDiagnostic &PD) {
19689   if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19690     if (!FunctionScopes.empty())
19691       FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19692           sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
19693     return true;
19694   }
19695 
19696   // The initializer of a constexpr variable or of the first declaration of a
19697   // static data member is not syntactically a constant evaluated constant,
19698   // but nonetheless is always required to be a constant expression, so we
19699   // can skip diagnosing.
19700   // FIXME: Using the mangling context here is a hack.
19701   if (auto *VD = dyn_cast_or_null<VarDecl>(
19702           ExprEvalContexts.back().ManglingContextDecl)) {
19703     if (VD->isConstexpr() ||
19704         (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19705       return false;
19706     // FIXME: For any other kind of variable, we should build a CFG for its
19707     // initializer and check whether the context in question is reachable.
19708   }
19709 
19710   Diag(Loc, PD);
19711   return true;
19712 }
19713 
19714 /// Emit a diagnostic that describes an effect on the run-time behavior
19715 /// of the program being compiled.
19716 ///
19717 /// This routine emits the given diagnostic when the code currently being
19718 /// type-checked is "potentially evaluated", meaning that there is a
19719 /// possibility that the code will actually be executable. Code in sizeof()
19720 /// expressions, code used only during overload resolution, etc., are not
19721 /// potentially evaluated. This routine will suppress such diagnostics or,
19722 /// in the absolutely nutty case of potentially potentially evaluated
19723 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
19724 /// later.
19725 ///
19726 /// This routine should be used for all diagnostics that describe the run-time
19727 /// behavior of a program, such as passing a non-POD value through an ellipsis.
19728 /// Failure to do so will likely result in spurious diagnostics or failures
19729 /// during overload resolution or within sizeof/alignof/typeof/typeid.
19730 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
19731                                const PartialDiagnostic &PD) {
19732 
19733   if (ExprEvalContexts.back().isDiscardedStatementContext())
19734     return false;
19735 
19736   switch (ExprEvalContexts.back().Context) {
19737   case ExpressionEvaluationContext::Unevaluated:
19738   case ExpressionEvaluationContext::UnevaluatedList:
19739   case ExpressionEvaluationContext::UnevaluatedAbstract:
19740   case ExpressionEvaluationContext::DiscardedStatement:
19741     // The argument will never be evaluated, so don't complain.
19742     break;
19743 
19744   case ExpressionEvaluationContext::ConstantEvaluated:
19745   case ExpressionEvaluationContext::ImmediateFunctionContext:
19746     // Relevant diagnostics should be produced by constant evaluation.
19747     break;
19748 
19749   case ExpressionEvaluationContext::PotentiallyEvaluated:
19750   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
19751     return DiagIfReachable(Loc, Stmts, PD);
19752   }
19753 
19754   return false;
19755 }
19756 
19757 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
19758                                const PartialDiagnostic &PD) {
19759   return DiagRuntimeBehavior(
19760       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
19761 }
19762 
19763 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
19764                                CallExpr *CE, FunctionDecl *FD) {
19765   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19766     return false;
19767 
19768   // If we're inside a decltype's expression, don't check for a valid return
19769   // type or construct temporaries until we know whether this is the last call.
19770   if (ExprEvalContexts.back().ExprContext ==
19771       ExpressionEvaluationContextRecord::EK_Decltype) {
19772     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19773     return false;
19774   }
19775 
19776   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19777     FunctionDecl *FD;
19778     CallExpr *CE;
19779 
19780   public:
19781     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
19782       : FD(FD), CE(CE) { }
19783 
19784     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
19785       if (!FD) {
19786         S.Diag(Loc, diag::err_call_incomplete_return)
19787           << T << CE->getSourceRange();
19788         return;
19789       }
19790 
19791       S.Diag(Loc, diag::err_call_function_incomplete_return)
19792           << CE->getSourceRange() << FD << T;
19793       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
19794           << FD->getDeclName();
19795     }
19796   } Diagnoser(FD, CE);
19797 
19798   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
19799     return true;
19800 
19801   return false;
19802 }
19803 
19804 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
19805 // will prevent this condition from triggering, which is what we want.
19806 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
19807   SourceLocation Loc;
19808 
19809   unsigned diagnostic = diag::warn_condition_is_assignment;
19810   bool IsOrAssign = false;
19811 
19812   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
19813     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
19814       return;
19815 
19816     IsOrAssign = Op->getOpcode() == BO_OrAssign;
19817 
19818     // Greylist some idioms by putting them into a warning subcategory.
19819     if (ObjCMessageExpr *ME
19820           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
19821       Selector Sel = ME->getSelector();
19822 
19823       // self = [<foo> init...]
19824       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
19825         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19826 
19827       // <foo> = [<bar> nextObject]
19828       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
19829         diagnostic = diag::warn_condition_is_idiomatic_assignment;
19830     }
19831 
19832     Loc = Op->getOperatorLoc();
19833   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
19834     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
19835       return;
19836 
19837     IsOrAssign = Op->getOperator() == OO_PipeEqual;
19838     Loc = Op->getOperatorLoc();
19839   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
19840     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
19841   else {
19842     // Not an assignment.
19843     return;
19844   }
19845 
19846   Diag(Loc, diagnostic) << E->getSourceRange();
19847 
19848   SourceLocation Open = E->getBeginLoc();
19849   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
19850   Diag(Loc, diag::note_condition_assign_silence)
19851         << FixItHint::CreateInsertion(Open, "(")
19852         << FixItHint::CreateInsertion(Close, ")");
19853 
19854   if (IsOrAssign)
19855     Diag(Loc, diag::note_condition_or_assign_to_comparison)
19856       << FixItHint::CreateReplacement(Loc, "!=");
19857   else
19858     Diag(Loc, diag::note_condition_assign_to_comparison)
19859       << FixItHint::CreateReplacement(Loc, "==");
19860 }
19861 
19862 /// Redundant parentheses over an equality comparison can indicate
19863 /// that the user intended an assignment used as condition.
19864 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
19865   // Don't warn if the parens came from a macro.
19866   SourceLocation parenLoc = ParenE->getBeginLoc();
19867   if (parenLoc.isInvalid() || parenLoc.isMacroID())
19868     return;
19869   // Don't warn for dependent expressions.
19870   if (ParenE->isTypeDependent())
19871     return;
19872 
19873   Expr *E = ParenE->IgnoreParens();
19874 
19875   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
19876     if (opE->getOpcode() == BO_EQ &&
19877         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
19878                                                            == Expr::MLV_Valid) {
19879       SourceLocation Loc = opE->getOperatorLoc();
19880 
19881       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
19882       SourceRange ParenERange = ParenE->getSourceRange();
19883       Diag(Loc, diag::note_equality_comparison_silence)
19884         << FixItHint::CreateRemoval(ParenERange.getBegin())
19885         << FixItHint::CreateRemoval(ParenERange.getEnd());
19886       Diag(Loc, diag::note_equality_comparison_to_assign)
19887         << FixItHint::CreateReplacement(Loc, "=");
19888     }
19889 }
19890 
19891 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
19892                                        bool IsConstexpr) {
19893   DiagnoseAssignmentAsCondition(E);
19894   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
19895     DiagnoseEqualityWithExtraParens(parenE);
19896 
19897   ExprResult result = CheckPlaceholderExpr(E);
19898   if (result.isInvalid()) return ExprError();
19899   E = result.get();
19900 
19901   if (!E->isTypeDependent()) {
19902     if (getLangOpts().CPlusPlus)
19903       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
19904 
19905     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
19906     if (ERes.isInvalid())
19907       return ExprError();
19908     E = ERes.get();
19909 
19910     QualType T = E->getType();
19911     if (!T->isScalarType()) { // C99 6.8.4.1p1
19912       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
19913         << T << E->getSourceRange();
19914       return ExprError();
19915     }
19916     CheckBoolLikeConversion(E, Loc);
19917   }
19918 
19919   return E;
19920 }
19921 
19922 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
19923                                            Expr *SubExpr, ConditionKind CK,
19924                                            bool MissingOK) {
19925   // MissingOK indicates whether having no condition expression is valid
19926   // (for loop) or invalid (e.g. while loop).
19927   if (!SubExpr)
19928     return MissingOK ? ConditionResult() : ConditionError();
19929 
19930   ExprResult Cond;
19931   switch (CK) {
19932   case ConditionKind::Boolean:
19933     Cond = CheckBooleanCondition(Loc, SubExpr);
19934     break;
19935 
19936   case ConditionKind::ConstexprIf:
19937     Cond = CheckBooleanCondition(Loc, SubExpr, true);
19938     break;
19939 
19940   case ConditionKind::Switch:
19941     Cond = CheckSwitchCondition(Loc, SubExpr);
19942     break;
19943   }
19944   if (Cond.isInvalid()) {
19945     Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
19946                               {SubExpr}, PreferredConditionType(CK));
19947     if (!Cond.get())
19948       return ConditionError();
19949   }
19950   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
19951   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
19952   if (!FullExpr.get())
19953     return ConditionError();
19954 
19955   return ConditionResult(*this, nullptr, FullExpr,
19956                          CK == ConditionKind::ConstexprIf);
19957 }
19958 
19959 namespace {
19960   /// A visitor for rebuilding a call to an __unknown_any expression
19961   /// to have an appropriate type.
19962   struct RebuildUnknownAnyFunction
19963     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
19964 
19965     Sema &S;
19966 
19967     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
19968 
19969     ExprResult VisitStmt(Stmt *S) {
19970       llvm_unreachable("unexpected statement!");
19971     }
19972 
19973     ExprResult VisitExpr(Expr *E) {
19974       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
19975         << E->getSourceRange();
19976       return ExprError();
19977     }
19978 
19979     /// Rebuild an expression which simply semantically wraps another
19980     /// expression which it shares the type and value kind of.
19981     template <class T> ExprResult rebuildSugarExpr(T *E) {
19982       ExprResult SubResult = Visit(E->getSubExpr());
19983       if (SubResult.isInvalid()) return ExprError();
19984 
19985       Expr *SubExpr = SubResult.get();
19986       E->setSubExpr(SubExpr);
19987       E->setType(SubExpr->getType());
19988       E->setValueKind(SubExpr->getValueKind());
19989       assert(E->getObjectKind() == OK_Ordinary);
19990       return E;
19991     }
19992 
19993     ExprResult VisitParenExpr(ParenExpr *E) {
19994       return rebuildSugarExpr(E);
19995     }
19996 
19997     ExprResult VisitUnaryExtension(UnaryOperator *E) {
19998       return rebuildSugarExpr(E);
19999     }
20000 
20001     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20002       ExprResult SubResult = Visit(E->getSubExpr());
20003       if (SubResult.isInvalid()) return ExprError();
20004 
20005       Expr *SubExpr = SubResult.get();
20006       E->setSubExpr(SubExpr);
20007       E->setType(S.Context.getPointerType(SubExpr->getType()));
20008       assert(E->isPRValue());
20009       assert(E->getObjectKind() == OK_Ordinary);
20010       return E;
20011     }
20012 
20013     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20014       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20015 
20016       E->setType(VD->getType());
20017 
20018       assert(E->isPRValue());
20019       if (S.getLangOpts().CPlusPlus &&
20020           !(isa<CXXMethodDecl>(VD) &&
20021             cast<CXXMethodDecl>(VD)->isInstance()))
20022         E->setValueKind(VK_LValue);
20023 
20024       return E;
20025     }
20026 
20027     ExprResult VisitMemberExpr(MemberExpr *E) {
20028       return resolveDecl(E, E->getMemberDecl());
20029     }
20030 
20031     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20032       return resolveDecl(E, E->getDecl());
20033     }
20034   };
20035 }
20036 
20037 /// Given a function expression of unknown-any type, try to rebuild it
20038 /// to have a function type.
20039 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20040   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20041   if (Result.isInvalid()) return ExprError();
20042   return S.DefaultFunctionArrayConversion(Result.get());
20043 }
20044 
20045 namespace {
20046   /// A visitor for rebuilding an expression of type __unknown_anytype
20047   /// into one which resolves the type directly on the referring
20048   /// expression.  Strict preservation of the original source
20049   /// structure is not a goal.
20050   struct RebuildUnknownAnyExpr
20051     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20052 
20053     Sema &S;
20054 
20055     /// The current destination type.
20056     QualType DestType;
20057 
20058     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20059       : S(S), DestType(CastType) {}
20060 
20061     ExprResult VisitStmt(Stmt *S) {
20062       llvm_unreachable("unexpected statement!");
20063     }
20064 
20065     ExprResult VisitExpr(Expr *E) {
20066       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20067         << E->getSourceRange();
20068       return ExprError();
20069     }
20070 
20071     ExprResult VisitCallExpr(CallExpr *E);
20072     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20073 
20074     /// Rebuild an expression which simply semantically wraps another
20075     /// expression which it shares the type and value kind of.
20076     template <class T> ExprResult rebuildSugarExpr(T *E) {
20077       ExprResult SubResult = Visit(E->getSubExpr());
20078       if (SubResult.isInvalid()) return ExprError();
20079       Expr *SubExpr = SubResult.get();
20080       E->setSubExpr(SubExpr);
20081       E->setType(SubExpr->getType());
20082       E->setValueKind(SubExpr->getValueKind());
20083       assert(E->getObjectKind() == OK_Ordinary);
20084       return E;
20085     }
20086 
20087     ExprResult VisitParenExpr(ParenExpr *E) {
20088       return rebuildSugarExpr(E);
20089     }
20090 
20091     ExprResult VisitUnaryExtension(UnaryOperator *E) {
20092       return rebuildSugarExpr(E);
20093     }
20094 
20095     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20096       const PointerType *Ptr = DestType->getAs<PointerType>();
20097       if (!Ptr) {
20098         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20099           << E->getSourceRange();
20100         return ExprError();
20101       }
20102 
20103       if (isa<CallExpr>(E->getSubExpr())) {
20104         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20105           << E->getSourceRange();
20106         return ExprError();
20107       }
20108 
20109       assert(E->isPRValue());
20110       assert(E->getObjectKind() == OK_Ordinary);
20111       E->setType(DestType);
20112 
20113       // Build the sub-expression as if it were an object of the pointee type.
20114       DestType = Ptr->getPointeeType();
20115       ExprResult SubResult = Visit(E->getSubExpr());
20116       if (SubResult.isInvalid()) return ExprError();
20117       E->setSubExpr(SubResult.get());
20118       return E;
20119     }
20120 
20121     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20122 
20123     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20124 
20125     ExprResult VisitMemberExpr(MemberExpr *E) {
20126       return resolveDecl(E, E->getMemberDecl());
20127     }
20128 
20129     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20130       return resolveDecl(E, E->getDecl());
20131     }
20132   };
20133 }
20134 
20135 /// Rebuilds a call expression which yielded __unknown_anytype.
20136 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20137   Expr *CalleeExpr = E->getCallee();
20138 
20139   enum FnKind {
20140     FK_MemberFunction,
20141     FK_FunctionPointer,
20142     FK_BlockPointer
20143   };
20144 
20145   FnKind Kind;
20146   QualType CalleeType = CalleeExpr->getType();
20147   if (CalleeType == S.Context.BoundMemberTy) {
20148     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20149     Kind = FK_MemberFunction;
20150     CalleeType = Expr::findBoundMemberType(CalleeExpr);
20151   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20152     CalleeType = Ptr->getPointeeType();
20153     Kind = FK_FunctionPointer;
20154   } else {
20155     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20156     Kind = FK_BlockPointer;
20157   }
20158   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20159 
20160   // Verify that this is a legal result type of a function.
20161   if (DestType->isArrayType() || DestType->isFunctionType()) {
20162     unsigned diagID = diag::err_func_returning_array_function;
20163     if (Kind == FK_BlockPointer)
20164       diagID = diag::err_block_returning_array_function;
20165 
20166     S.Diag(E->getExprLoc(), diagID)
20167       << DestType->isFunctionType() << DestType;
20168     return ExprError();
20169   }
20170 
20171   // Otherwise, go ahead and set DestType as the call's result.
20172   E->setType(DestType.getNonLValueExprType(S.Context));
20173   E->setValueKind(Expr::getValueKindForType(DestType));
20174   assert(E->getObjectKind() == OK_Ordinary);
20175 
20176   // Rebuild the function type, replacing the result type with DestType.
20177   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20178   if (Proto) {
20179     // __unknown_anytype(...) is a special case used by the debugger when
20180     // it has no idea what a function's signature is.
20181     //
20182     // We want to build this call essentially under the K&R
20183     // unprototyped rules, but making a FunctionNoProtoType in C++
20184     // would foul up all sorts of assumptions.  However, we cannot
20185     // simply pass all arguments as variadic arguments, nor can we
20186     // portably just call the function under a non-variadic type; see
20187     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20188     // However, it turns out that in practice it is generally safe to
20189     // call a function declared as "A foo(B,C,D);" under the prototype
20190     // "A foo(B,C,D,...);".  The only known exception is with the
20191     // Windows ABI, where any variadic function is implicitly cdecl
20192     // regardless of its normal CC.  Therefore we change the parameter
20193     // types to match the types of the arguments.
20194     //
20195     // This is a hack, but it is far superior to moving the
20196     // corresponding target-specific code from IR-gen to Sema/AST.
20197 
20198     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20199     SmallVector<QualType, 8> ArgTypes;
20200     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20201       ArgTypes.reserve(E->getNumArgs());
20202       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20203         ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20204       }
20205       ParamTypes = ArgTypes;
20206     }
20207     DestType = S.Context.getFunctionType(DestType, ParamTypes,
20208                                          Proto->getExtProtoInfo());
20209   } else {
20210     DestType = S.Context.getFunctionNoProtoType(DestType,
20211                                                 FnType->getExtInfo());
20212   }
20213 
20214   // Rebuild the appropriate pointer-to-function type.
20215   switch (Kind) {
20216   case FK_MemberFunction:
20217     // Nothing to do.
20218     break;
20219 
20220   case FK_FunctionPointer:
20221     DestType = S.Context.getPointerType(DestType);
20222     break;
20223 
20224   case FK_BlockPointer:
20225     DestType = S.Context.getBlockPointerType(DestType);
20226     break;
20227   }
20228 
20229   // Finally, we can recurse.
20230   ExprResult CalleeResult = Visit(CalleeExpr);
20231   if (!CalleeResult.isUsable()) return ExprError();
20232   E->setCallee(CalleeResult.get());
20233 
20234   // Bind a temporary if necessary.
20235   return S.MaybeBindToTemporary(E);
20236 }
20237 
20238 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20239   // Verify that this is a legal result type of a call.
20240   if (DestType->isArrayType() || DestType->isFunctionType()) {
20241     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20242       << DestType->isFunctionType() << DestType;
20243     return ExprError();
20244   }
20245 
20246   // Rewrite the method result type if available.
20247   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20248     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20249     Method->setReturnType(DestType);
20250   }
20251 
20252   // Change the type of the message.
20253   E->setType(DestType.getNonReferenceType());
20254   E->setValueKind(Expr::getValueKindForType(DestType));
20255 
20256   return S.MaybeBindToTemporary(E);
20257 }
20258 
20259 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20260   // The only case we should ever see here is a function-to-pointer decay.
20261   if (E->getCastKind() == CK_FunctionToPointerDecay) {
20262     assert(E->isPRValue());
20263     assert(E->getObjectKind() == OK_Ordinary);
20264 
20265     E->setType(DestType);
20266 
20267     // Rebuild the sub-expression as the pointee (function) type.
20268     DestType = DestType->castAs<PointerType>()->getPointeeType();
20269 
20270     ExprResult Result = Visit(E->getSubExpr());
20271     if (!Result.isUsable()) return ExprError();
20272 
20273     E->setSubExpr(Result.get());
20274     return E;
20275   } else if (E->getCastKind() == CK_LValueToRValue) {
20276     assert(E->isPRValue());
20277     assert(E->getObjectKind() == OK_Ordinary);
20278 
20279     assert(isa<BlockPointerType>(E->getType()));
20280 
20281     E->setType(DestType);
20282 
20283     // The sub-expression has to be a lvalue reference, so rebuild it as such.
20284     DestType = S.Context.getLValueReferenceType(DestType);
20285 
20286     ExprResult Result = Visit(E->getSubExpr());
20287     if (!Result.isUsable()) return ExprError();
20288 
20289     E->setSubExpr(Result.get());
20290     return E;
20291   } else {
20292     llvm_unreachable("Unhandled cast type!");
20293   }
20294 }
20295 
20296 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20297   ExprValueKind ValueKind = VK_LValue;
20298   QualType Type = DestType;
20299 
20300   // We know how to make this work for certain kinds of decls:
20301 
20302   //  - functions
20303   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20304     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20305       DestType = Ptr->getPointeeType();
20306       ExprResult Result = resolveDecl(E, VD);
20307       if (Result.isInvalid()) return ExprError();
20308       return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20309                                  VK_PRValue);
20310     }
20311 
20312     if (!Type->isFunctionType()) {
20313       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20314         << VD << E->getSourceRange();
20315       return ExprError();
20316     }
20317     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20318       // We must match the FunctionDecl's type to the hack introduced in
20319       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20320       // type. See the lengthy commentary in that routine.
20321       QualType FDT = FD->getType();
20322       const FunctionType *FnType = FDT->castAs<FunctionType>();
20323       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20324       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20325       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20326         SourceLocation Loc = FD->getLocation();
20327         FunctionDecl *NewFD = FunctionDecl::Create(
20328             S.Context, FD->getDeclContext(), Loc, Loc,
20329             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20330             SC_None, S.getCurFPFeatures().isFPConstrained(),
20331             false /*isInlineSpecified*/, FD->hasPrototype(),
20332             /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20333 
20334         if (FD->getQualifier())
20335           NewFD->setQualifierInfo(FD->getQualifierLoc());
20336 
20337         SmallVector<ParmVarDecl*, 16> Params;
20338         for (const auto &AI : FT->param_types()) {
20339           ParmVarDecl *Param =
20340             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
20341           Param->setScopeInfo(0, Params.size());
20342           Params.push_back(Param);
20343         }
20344         NewFD->setParams(Params);
20345         DRE->setDecl(NewFD);
20346         VD = DRE->getDecl();
20347       }
20348     }
20349 
20350     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20351       if (MD->isInstance()) {
20352         ValueKind = VK_PRValue;
20353         Type = S.Context.BoundMemberTy;
20354       }
20355 
20356     // Function references aren't l-values in C.
20357     if (!S.getLangOpts().CPlusPlus)
20358       ValueKind = VK_PRValue;
20359 
20360   //  - variables
20361   } else if (isa<VarDecl>(VD)) {
20362     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20363       Type = RefTy->getPointeeType();
20364     } else if (Type->isFunctionType()) {
20365       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20366         << VD << E->getSourceRange();
20367       return ExprError();
20368     }
20369 
20370   //  - nothing else
20371   } else {
20372     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20373       << VD << E->getSourceRange();
20374     return ExprError();
20375   }
20376 
20377   // Modifying the declaration like this is friendly to IR-gen but
20378   // also really dangerous.
20379   VD->setType(DestType);
20380   E->setType(Type);
20381   E->setValueKind(ValueKind);
20382   return E;
20383 }
20384 
20385 /// Check a cast of an unknown-any type.  We intentionally only
20386 /// trigger this for C-style casts.
20387 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
20388                                      Expr *CastExpr, CastKind &CastKind,
20389                                      ExprValueKind &VK, CXXCastPath &Path) {
20390   // The type we're casting to must be either void or complete.
20391   if (!CastType->isVoidType() &&
20392       RequireCompleteType(TypeRange.getBegin(), CastType,
20393                           diag::err_typecheck_cast_to_incomplete))
20394     return ExprError();
20395 
20396   // Rewrite the casted expression from scratch.
20397   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20398   if (!result.isUsable()) return ExprError();
20399 
20400   CastExpr = result.get();
20401   VK = CastExpr->getValueKind();
20402   CastKind = CK_NoOp;
20403 
20404   return CastExpr;
20405 }
20406 
20407 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
20408   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20409 }
20410 
20411 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
20412                                     Expr *arg, QualType &paramType) {
20413   // If the syntactic form of the argument is not an explicit cast of
20414   // any sort, just do default argument promotion.
20415   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20416   if (!castArg) {
20417     ExprResult result = DefaultArgumentPromotion(arg);
20418     if (result.isInvalid()) return ExprError();
20419     paramType = result.get()->getType();
20420     return result;
20421   }
20422 
20423   // Otherwise, use the type that was written in the explicit cast.
20424   assert(!arg->hasPlaceholderType());
20425   paramType = castArg->getTypeAsWritten();
20426 
20427   // Copy-initialize a parameter of that type.
20428   InitializedEntity entity =
20429     InitializedEntity::InitializeParameter(Context, paramType,
20430                                            /*consumed*/ false);
20431   return PerformCopyInitialization(entity, callLoc, arg);
20432 }
20433 
20434 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
20435   Expr *orig = E;
20436   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20437   while (true) {
20438     E = E->IgnoreParenImpCasts();
20439     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20440       E = call->getCallee();
20441       diagID = diag::err_uncasted_call_of_unknown_any;
20442     } else {
20443       break;
20444     }
20445   }
20446 
20447   SourceLocation loc;
20448   NamedDecl *d;
20449   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20450     loc = ref->getLocation();
20451     d = ref->getDecl();
20452   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20453     loc = mem->getMemberLoc();
20454     d = mem->getMemberDecl();
20455   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20456     diagID = diag::err_uncasted_call_of_unknown_any;
20457     loc = msg->getSelectorStartLoc();
20458     d = msg->getMethodDecl();
20459     if (!d) {
20460       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20461         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20462         << orig->getSourceRange();
20463       return ExprError();
20464     }
20465   } else {
20466     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20467       << E->getSourceRange();
20468     return ExprError();
20469   }
20470 
20471   S.Diag(loc, diagID) << d << orig->getSourceRange();
20472 
20473   // Never recoverable.
20474   return ExprError();
20475 }
20476 
20477 /// Check for operands with placeholder types and complain if found.
20478 /// Returns ExprError() if there was an error and no recovery was possible.
20479 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
20480   if (!Context.isDependenceAllowed()) {
20481     // C cannot handle TypoExpr nodes on either side of a binop because it
20482     // doesn't handle dependent types properly, so make sure any TypoExprs have
20483     // been dealt with before checking the operands.
20484     ExprResult Result = CorrectDelayedTyposInExpr(E);
20485     if (!Result.isUsable()) return ExprError();
20486     E = Result.get();
20487   }
20488 
20489   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20490   if (!placeholderType) return E;
20491 
20492   switch (placeholderType->getKind()) {
20493 
20494   // Overloaded expressions.
20495   case BuiltinType::Overload: {
20496     // Try to resolve a single function template specialization.
20497     // This is obligatory.
20498     ExprResult Result = E;
20499     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
20500       return Result;
20501 
20502     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20503     // leaves Result unchanged on failure.
20504     Result = E;
20505     if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
20506       return Result;
20507 
20508     // If that failed, try to recover with a call.
20509     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20510                          /*complain*/ true);
20511     return Result;
20512   }
20513 
20514   // Bound member functions.
20515   case BuiltinType::BoundMember: {
20516     ExprResult result = E;
20517     const Expr *BME = E->IgnoreParens();
20518     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20519     // Try to give a nicer diagnostic if it is a bound member that we recognize.
20520     if (isa<CXXPseudoDestructorExpr>(BME)) {
20521       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20522     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20523       if (ME->getMemberNameInfo().getName().getNameKind() ==
20524           DeclarationName::CXXDestructorName)
20525         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20526     }
20527     tryToRecoverWithCall(result, PD,
20528                          /*complain*/ true);
20529     return result;
20530   }
20531 
20532   // ARC unbridged casts.
20533   case BuiltinType::ARCUnbridgedCast: {
20534     Expr *realCast = stripARCUnbridgedCast(E);
20535     diagnoseARCUnbridgedCast(realCast);
20536     return realCast;
20537   }
20538 
20539   // Expressions of unknown type.
20540   case BuiltinType::UnknownAny:
20541     return diagnoseUnknownAnyExpr(*this, E);
20542 
20543   // Pseudo-objects.
20544   case BuiltinType::PseudoObject:
20545     return checkPseudoObjectRValue(E);
20546 
20547   case BuiltinType::BuiltinFn: {
20548     // Accept __noop without parens by implicitly converting it to a call expr.
20549     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20550     if (DRE) {
20551       auto *FD = cast<FunctionDecl>(DRE->getDecl());
20552       unsigned BuiltinID = FD->getBuiltinID();
20553       if (BuiltinID == Builtin::BI__noop) {
20554         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20555                               CK_BuiltinFnToFnPtr)
20556                 .get();
20557         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20558                                 VK_PRValue, SourceLocation(),
20559                                 FPOptionsOverride());
20560       }
20561 
20562       if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20563         // Any use of these other than a direct call is ill-formed as of C++20,
20564         // because they are not addressable functions. In earlier language
20565         // modes, warn and force an instantiation of the real body.
20566         Diag(E->getBeginLoc(),
20567              getLangOpts().CPlusPlus20
20568                  ? diag::err_use_of_unaddressable_function
20569                  : diag::warn_cxx20_compat_use_of_unaddressable_function);
20570         if (FD->isImplicitlyInstantiable()) {
20571           // Require a definition here because a normal attempt at
20572           // instantiation for a builtin will be ignored, and we won't try
20573           // again later. We assume that the definition of the template
20574           // precedes this use.
20575           InstantiateFunctionDefinition(E->getBeginLoc(), FD,
20576                                         /*Recursive=*/false,
20577                                         /*DefinitionRequired=*/true,
20578                                         /*AtEndOfTU=*/false);
20579         }
20580         // Produce a properly-typed reference to the function.
20581         CXXScopeSpec SS;
20582         SS.Adopt(DRE->getQualifierLoc());
20583         TemplateArgumentListInfo TemplateArgs;
20584         DRE->copyTemplateArgumentsInto(TemplateArgs);
20585         return BuildDeclRefExpr(
20586             FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20587             DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20588             DRE->getTemplateKeywordLoc(),
20589             DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20590       }
20591     }
20592 
20593     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20594     return ExprError();
20595   }
20596 
20597   case BuiltinType::IncompleteMatrixIdx:
20598     Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20599              ->getRowIdx()
20600              ->getBeginLoc(),
20601          diag::err_matrix_incomplete_index);
20602     return ExprError();
20603 
20604   // Expressions of unknown type.
20605   case BuiltinType::OMPArraySection:
20606     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
20607     return ExprError();
20608 
20609   // Expressions of unknown type.
20610   case BuiltinType::OMPArrayShaping:
20611     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20612 
20613   case BuiltinType::OMPIterator:
20614     return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20615 
20616   // Everything else should be impossible.
20617 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20618   case BuiltinType::Id:
20619 #include "clang/Basic/OpenCLImageTypes.def"
20620 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20621   case BuiltinType::Id:
20622 #include "clang/Basic/OpenCLExtensionTypes.def"
20623 #define SVE_TYPE(Name, Id, SingletonId) \
20624   case BuiltinType::Id:
20625 #include "clang/Basic/AArch64SVEACLETypes.def"
20626 #define PPC_VECTOR_TYPE(Name, Id, Size) \
20627   case BuiltinType::Id:
20628 #include "clang/Basic/PPCTypes.def"
20629 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20630 #include "clang/Basic/RISCVVTypes.def"
20631 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20632 #define PLACEHOLDER_TYPE(Id, SingletonId)
20633 #include "clang/AST/BuiltinTypes.def"
20634     break;
20635   }
20636 
20637   llvm_unreachable("invalid placeholder type!");
20638 }
20639 
20640 bool Sema::CheckCaseExpression(Expr *E) {
20641   if (E->isTypeDependent())
20642     return true;
20643   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
20644     return E->getType()->isIntegralOrEnumerationType();
20645   return false;
20646 }
20647 
20648 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
20649 ExprResult
20650 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
20651   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
20652          "Unknown Objective-C Boolean value!");
20653   QualType BoolT = Context.ObjCBuiltinBoolTy;
20654   if (!Context.getBOOLDecl()) {
20655     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
20656                         Sema::LookupOrdinaryName);
20657     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
20658       NamedDecl *ND = Result.getFoundDecl();
20659       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
20660         Context.setBOOLDecl(TD);
20661     }
20662   }
20663   if (Context.getBOOLDecl())
20664     BoolT = Context.getBOOLType();
20665   return new (Context)
20666       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
20667 }
20668 
20669 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
20670     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
20671     SourceLocation RParen) {
20672   auto FindSpecVersion = [&](StringRef Platform) -> Optional<VersionTuple> {
20673     auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20674       return Spec.getPlatform() == Platform;
20675     });
20676     // Transcribe the "ios" availability check to "maccatalyst" when compiling
20677     // for "maccatalyst" if "maccatalyst" is not specified.
20678     if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
20679       Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
20680         return Spec.getPlatform() == "ios";
20681       });
20682     }
20683     if (Spec == AvailSpecs.end())
20684       return None;
20685     return Spec->getVersion();
20686   };
20687 
20688   VersionTuple Version;
20689   if (auto MaybeVersion =
20690           FindSpecVersion(Context.getTargetInfo().getPlatformName()))
20691     Version = *MaybeVersion;
20692 
20693   // The use of `@available` in the enclosing context should be analyzed to
20694   // warn when it's used inappropriately (i.e. not if(@available)).
20695   if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
20696     Context->HasPotentialAvailabilityViolations = true;
20697 
20698   return new (Context)
20699       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
20700 }
20701 
20702 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
20703                                     ArrayRef<Expr *> SubExprs, QualType T) {
20704   if (!Context.getLangOpts().RecoveryAST)
20705     return ExprError();
20706 
20707   if (isSFINAEContext())
20708     return ExprError();
20709 
20710   if (T.isNull() || T->isUndeducedType() ||
20711       !Context.getLangOpts().RecoveryASTType)
20712     // We don't know the concrete type, fallback to dependent type.
20713     T = Context.DependentTy;
20714 
20715   return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20716 }
20717