xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Sema/SemaExpr.cpp (revision 154bfe8e089c1a0a4e9ed8414f08d3da90949162)
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 "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/FixedPoint.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68 
69     // See if this is an aligned allocation/deallocation function that is
70     // unavailable.
71     if (TreatUnavailableAsInvalid &&
72         isUnavailableAlignedAllocationFunction(*FD))
73       return false;
74   }
75 
76   // See if this function is unavailable.
77   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
78       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
79     return false;
80 
81   return true;
82 }
83 
84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
85   // Warn if this is used but marked unused.
86   if (const auto *A = D->getAttr<UnusedAttr>()) {
87     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
88     // should diagnose them.
89     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
90         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
91       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
92       if (DC && !DC->hasAttr<UnusedAttr>())
93         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
94     }
95   }
96 }
97 
98 /// Emit a note explaining that this function is deleted.
99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
100   assert(Decl->isDeleted());
101 
102   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
103 
104   if (Method && Method->isDeleted() && Method->isDefaulted()) {
105     // If the method was explicitly defaulted, point at that declaration.
106     if (!Method->isImplicit())
107       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108 
109     // Try to diagnose why this special member function was implicitly
110     // deleted. This might fail, if that reason no longer applies.
111     CXXSpecialMember CSM = getSpecialMember(Method);
112     if (CSM != CXXInvalid)
113       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
114 
115     return;
116   }
117 
118   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119   if (Ctor && Ctor->isInheritingConstructor())
120     return NoteDeletedInheritingConstructor(Ctor);
121 
122   Diag(Decl->getLocation(), diag::note_availability_specified_here)
123     << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129   for (auto I : D->redecls()) {
130     if (I->getStorageClass() != SC_None)
131       return true;
132   }
133   return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145                                                       const NamedDecl *D,
146                                                       SourceLocation Loc) {
147   // This is disabled under C++; there are too many ways for this to fire in
148   // contexts where the warning is a false positive, or where it is technically
149   // correct but benign.
150   if (S.getLangOpts().CPlusPlus)
151     return;
152 
153   // Check if this is an inlined function or method.
154   FunctionDecl *Current = S.getCurFunctionDecl();
155   if (!Current)
156     return;
157   if (!Current->isInlined())
158     return;
159   if (!Current->isExternallyVisible())
160     return;
161 
162   // Check if the decl has internal linkage.
163   if (D->getFormalLinkage() != InternalLinkage)
164     return;
165 
166   // Downgrade from ExtWarn to Extension if
167   //  (1) the supposedly external inline function is in the main file,
168   //      and probably won't be included anywhere else.
169   //  (2) the thing we're referencing is a pure function.
170   //  (3) the thing we're referencing is another inline function.
171   // This last can give us false negatives, but it's better than warning on
172   // wrappers for simple C library functions.
173   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175   if (!DowngradeWarning && UsedFn)
176     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179                                : diag::ext_internal_in_extern_inline)
180     << /*IsVar=*/!UsedFn << D;
181 
182   S.MaybeSuggestAddingStaticToDecl(Current);
183 
184   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185       << D;
186 }
187 
188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189   const FunctionDecl *First = Cur->getFirstDecl();
190 
191   // Suggest "static" on the function, if possible.
192   if (!hasAnyExplicitStorageClass(First)) {
193     SourceLocation DeclBegin = First->getSourceRange().getBegin();
194     Diag(DeclBegin, diag::note_convert_inline_to_static)
195       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196   }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212                              const ObjCInterfaceDecl *UnknownObjCClass,
213                              bool ObjCPropertyAccess,
214                              bool AvoidPartialAvailabilityChecks,
215                              ObjCInterfaceDecl *ClassReceiver) {
216   SourceLocation Loc = Locs.front();
217   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218     // If there were any diagnostics suppressed by template argument deduction,
219     // emit them now.
220     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221     if (Pos != SuppressedDiagnostics.end()) {
222       for (const PartialDiagnosticAt &Suppressed : Pos->second)
223         Diag(Suppressed.first, Suppressed.second);
224 
225       // Clear out the list of suppressed diagnostics, so that we don't emit
226       // them again for this specialization. However, we don't obsolete this
227       // entry from the table, because we want to avoid ever emitting these
228       // diagnostics again.
229       Pos->second.clear();
230     }
231 
232     // C++ [basic.start.main]p3:
233     //   The function 'main' shall not be used within a program.
234     if (cast<FunctionDecl>(D)->isMain())
235       Diag(Loc, diag::ext_main_used);
236 
237     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238   }
239 
240   // See if this is an auto-typed variable whose initializer we are parsing.
241   if (ParsingInitForAutoVars.count(D)) {
242     if (isa<BindingDecl>(D)) {
243       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244         << D->getDeclName();
245     } else {
246       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247         << D->getDeclName() << cast<VarDecl>(D)->getType();
248     }
249     return true;
250   }
251 
252   // See if this is a deleted function.
253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254     if (FD->isDeleted()) {
255       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256       if (Ctor && Ctor->isInheritingConstructor())
257         Diag(Loc, diag::err_deleted_inherited_ctor_use)
258             << Ctor->getParent()
259             << Ctor->getInheritedConstructor().getConstructor()->getParent();
260       else
261         Diag(Loc, diag::err_deleted_function_use);
262       NoteDeletedFunction(FD);
263       return true;
264     }
265 
266     // If the function has a deduced return type, and we can't deduce it,
267     // then we can't use it either.
268     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
269         DeduceReturnType(FD, Loc))
270       return true;
271 
272     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
273       return true;
274   }
275 
276   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
277     // Lambdas are only default-constructible or assignable in C++2a onwards.
278     if (MD->getParent()->isLambda() &&
279         ((isa<CXXConstructorDecl>(MD) &&
280           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
281          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
282       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
283         << !isa<CXXConstructorDecl>(MD);
284     }
285   }
286 
287   auto getReferencedObjCProp = [](const NamedDecl *D) ->
288                                       const ObjCPropertyDecl * {
289     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
290       return MD->findPropertyDecl();
291     return nullptr;
292   };
293   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
294     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
295       return true;
296   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
297       return true;
298   }
299 
300   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
301   // Only the variables omp_in and omp_out are allowed in the combiner.
302   // Only the variables omp_priv and omp_orig are allowed in the
303   // initializer-clause.
304   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
305   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
306       isa<VarDecl>(D)) {
307     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
308         << getCurFunction()->HasOMPDeclareReductionCombiner;
309     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
310     return true;
311   }
312 
313   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
314   //  List-items in map clauses on this construct may only refer to the declared
315   //  variable var and entities that could be referenced by a procedure defined
316   //  at the same location
317   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
318   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
319       isa<VarDecl>(D)) {
320     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
321         << DMD->getVarName().getAsString();
322     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
323     return true;
324   }
325 
326   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
327                              AvoidPartialAvailabilityChecks, ClassReceiver);
328 
329   DiagnoseUnusedOfDecl(*this, D, Loc);
330 
331   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
332 
333   return false;
334 }
335 
336 /// DiagnoseSentinelCalls - This routine checks whether a call or
337 /// message-send is to a declaration with the sentinel attribute, and
338 /// if so, it checks that the requirements of the sentinel are
339 /// satisfied.
340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
341                                  ArrayRef<Expr *> Args) {
342   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
343   if (!attr)
344     return;
345 
346   // The number of formal parameters of the declaration.
347   unsigned numFormalParams;
348 
349   // The kind of declaration.  This is also an index into a %select in
350   // the diagnostic.
351   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
352 
353   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
354     numFormalParams = MD->param_size();
355     calleeType = CT_Method;
356   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
357     numFormalParams = FD->param_size();
358     calleeType = CT_Function;
359   } else if (isa<VarDecl>(D)) {
360     QualType type = cast<ValueDecl>(D)->getType();
361     const FunctionType *fn = nullptr;
362     if (const PointerType *ptr = type->getAs<PointerType>()) {
363       fn = ptr->getPointeeType()->getAs<FunctionType>();
364       if (!fn) return;
365       calleeType = CT_Function;
366     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
367       fn = ptr->getPointeeType()->castAs<FunctionType>();
368       calleeType = CT_Block;
369     } else {
370       return;
371     }
372 
373     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
374       numFormalParams = proto->getNumParams();
375     } else {
376       numFormalParams = 0;
377     }
378   } else {
379     return;
380   }
381 
382   // "nullPos" is the number of formal parameters at the end which
383   // effectively count as part of the variadic arguments.  This is
384   // useful if you would prefer to not have *any* formal parameters,
385   // but the language forces you to have at least one.
386   unsigned nullPos = attr->getNullPos();
387   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
388   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
389 
390   // The number of arguments which should follow the sentinel.
391   unsigned numArgsAfterSentinel = attr->getSentinel();
392 
393   // If there aren't enough arguments for all the formal parameters,
394   // the sentinel, and the args after the sentinel, complain.
395   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
396     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
397     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
398     return;
399   }
400 
401   // Otherwise, find the sentinel expression.
402   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
403   if (!sentinelExpr) return;
404   if (sentinelExpr->isValueDependent()) return;
405   if (Context.isSentinelNullExpr(sentinelExpr)) return;
406 
407   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
408   // or 'NULL' if those are actually defined in the context.  Only use
409   // 'nil' for ObjC methods, where it's much more likely that the
410   // variadic arguments form a list of object pointers.
411   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
412   std::string NullValue;
413   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
414     NullValue = "nil";
415   else if (getLangOpts().CPlusPlus11)
416     NullValue = "nullptr";
417   else if (PP.isMacroDefined("NULL"))
418     NullValue = "NULL";
419   else
420     NullValue = "(void*) 0";
421 
422   if (MissingNilLoc.isInvalid())
423     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
424   else
425     Diag(MissingNilLoc, diag::warn_missing_sentinel)
426       << int(calleeType)
427       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
428   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429 }
430 
431 SourceRange Sema::getExprRange(Expr *E) const {
432   return E ? E->getSourceRange() : SourceRange();
433 }
434 
435 //===----------------------------------------------------------------------===//
436 //  Standard Promotions and Conversions
437 //===----------------------------------------------------------------------===//
438 
439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
441   // Handle any placeholder expressions which made it here.
442   if (E->getType()->isPlaceholderType()) {
443     ExprResult result = CheckPlaceholderExpr(E);
444     if (result.isInvalid()) return ExprError();
445     E = result.get();
446   }
447 
448   QualType Ty = E->getType();
449   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
450 
451   if (Ty->isFunctionType()) {
452     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
453       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
454         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
455           return ExprError();
456 
457     E = ImpCastExprToType(E, Context.getPointerType(Ty),
458                           CK_FunctionToPointerDecay).get();
459   } else if (Ty->isArrayType()) {
460     // In C90 mode, arrays only promote to pointers if the array expression is
461     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
462     // type 'array of type' is converted to an expression that has type 'pointer
463     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
464     // that has type 'array of type' ...".  The relevant change is "an lvalue"
465     // (C90) to "an expression" (C99).
466     //
467     // C++ 4.2p1:
468     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
469     // T" can be converted to an rvalue of type "pointer to T".
470     //
471     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
472       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
473                             CK_ArrayToPointerDecay).get();
474   }
475   return E;
476 }
477 
478 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
479   // Check to see if we are dereferencing a null pointer.  If so,
480   // and if not volatile-qualified, this is undefined behavior that the
481   // optimizer will delete, so warn about it.  People sometimes try to use this
482   // to get a deterministic trap and are surprised by clang's behavior.  This
483   // only handles the pattern "*null", which is a very syntactic check.
484   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
485     if (UO->getOpcode() == UO_Deref &&
486         UO->getSubExpr()->IgnoreParenCasts()->
487           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
488         !UO->getType().isVolatileQualified()) {
489     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
490                           S.PDiag(diag::warn_indirection_through_null)
491                             << UO->getSubExpr()->getSourceRange());
492     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
493                         S.PDiag(diag::note_indirection_through_null));
494   }
495 }
496 
497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
498                                     SourceLocation AssignLoc,
499                                     const Expr* RHS) {
500   const ObjCIvarDecl *IV = OIRE->getDecl();
501   if (!IV)
502     return;
503 
504   DeclarationName MemberName = IV->getDeclName();
505   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
506   if (!Member || !Member->isStr("isa"))
507     return;
508 
509   const Expr *Base = OIRE->getBase();
510   QualType BaseType = Base->getType();
511   if (OIRE->isArrow())
512     BaseType = BaseType->getPointeeType();
513   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
514     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
515       ObjCInterfaceDecl *ClassDeclared = nullptr;
516       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
517       if (!ClassDeclared->getSuperClass()
518           && (*ClassDeclared->ivar_begin()) == IV) {
519         if (RHS) {
520           NamedDecl *ObjectSetClass =
521             S.LookupSingleName(S.TUScope,
522                                &S.Context.Idents.get("object_setClass"),
523                                SourceLocation(), S.LookupOrdinaryName);
524           if (ObjectSetClass) {
525             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
526             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
527                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
528                                               "object_setClass(")
529                 << FixItHint::CreateReplacement(
530                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
531                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
532           }
533           else
534             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
535         } else {
536           NamedDecl *ObjectGetClass =
537             S.LookupSingleName(S.TUScope,
538                                &S.Context.Idents.get("object_getClass"),
539                                SourceLocation(), S.LookupOrdinaryName);
540           if (ObjectGetClass)
541             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
542                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
543                                               "object_getClass(")
544                 << FixItHint::CreateReplacement(
545                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
546           else
547             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
548         }
549         S.Diag(IV->getLocation(), diag::note_ivar_decl);
550       }
551     }
552 }
553 
554 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
555   // Handle any placeholder expressions which made it here.
556   if (E->getType()->isPlaceholderType()) {
557     ExprResult result = CheckPlaceholderExpr(E);
558     if (result.isInvalid()) return ExprError();
559     E = result.get();
560   }
561 
562   // C++ [conv.lval]p1:
563   //   A glvalue of a non-function, non-array type T can be
564   //   converted to a prvalue.
565   if (!E->isGLValue()) return E;
566 
567   QualType T = E->getType();
568   assert(!T.isNull() && "r-value conversion on typeless expression?");
569 
570   // We don't want to throw lvalue-to-rvalue casts on top of
571   // expressions of certain types in C++.
572   if (getLangOpts().CPlusPlus &&
573       (E->getType() == Context.OverloadTy ||
574        T->isDependentType() ||
575        T->isRecordType()))
576     return E;
577 
578   // The C standard is actually really unclear on this point, and
579   // DR106 tells us what the result should be but not why.  It's
580   // generally best to say that void types just doesn't undergo
581   // lvalue-to-rvalue at all.  Note that expressions of unqualified
582   // 'void' type are never l-values, but qualified void can be.
583   if (T->isVoidType())
584     return E;
585 
586   // OpenCL usually rejects direct accesses to values of 'half' type.
587   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
588       T->isHalfType()) {
589     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
590       << 0 << T;
591     return ExprError();
592   }
593 
594   CheckForNullPointerDereference(*this, E);
595   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
596     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
597                                      &Context.Idents.get("object_getClass"),
598                                      SourceLocation(), LookupOrdinaryName);
599     if (ObjectGetClass)
600       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
601           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
602           << FixItHint::CreateReplacement(
603                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
604     else
605       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
606   }
607   else if (const ObjCIvarRefExpr *OIRE =
608             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
609     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
610 
611   // C++ [conv.lval]p1:
612   //   [...] If T is a non-class type, the type of the prvalue is the
613   //   cv-unqualified version of T. Otherwise, the type of the
614   //   rvalue is T.
615   //
616   // C99 6.3.2.1p2:
617   //   If the lvalue has qualified type, the value has the unqualified
618   //   version of the type of the lvalue; otherwise, the value has the
619   //   type of the lvalue.
620   if (T.hasQualifiers())
621     T = T.getUnqualifiedType();
622 
623   // Under the MS ABI, lock down the inheritance model now.
624   if (T->isMemberPointerType() &&
625       Context.getTargetInfo().getCXXABI().isMicrosoft())
626     (void)isCompleteType(E->getExprLoc(), T);
627 
628   ExprResult Res = CheckLValueToRValueConversionOperand(E);
629   if (Res.isInvalid())
630     return Res;
631   E = Res.get();
632 
633   // Loading a __weak object implicitly retains the value, so we need a cleanup to
634   // balance that.
635   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
636     Cleanup.setExprNeedsCleanups(true);
637 
638   // C++ [conv.lval]p3:
639   //   If T is cv std::nullptr_t, the result is a null pointer constant.
640   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
641   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
642 
643   // C11 6.3.2.1p2:
644   //   ... if the lvalue has atomic type, the value has the non-atomic version
645   //   of the type of the lvalue ...
646   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
647     T = Atomic->getValueType().getUnqualifiedType();
648     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
649                                    nullptr, VK_RValue);
650   }
651 
652   return Res;
653 }
654 
655 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
656   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
657   if (Res.isInvalid())
658     return ExprError();
659   Res = DefaultLvalueConversion(Res.get());
660   if (Res.isInvalid())
661     return ExprError();
662   return Res;
663 }
664 
665 /// CallExprUnaryConversions - a special case of an unary conversion
666 /// performed on a function designator of a call expression.
667 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
668   QualType Ty = E->getType();
669   ExprResult Res = E;
670   // Only do implicit cast for a function type, but not for a pointer
671   // to function type.
672   if (Ty->isFunctionType()) {
673     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
674                             CK_FunctionToPointerDecay).get();
675     if (Res.isInvalid())
676       return ExprError();
677   }
678   Res = DefaultLvalueConversion(Res.get());
679   if (Res.isInvalid())
680     return ExprError();
681   return Res.get();
682 }
683 
684 /// UsualUnaryConversions - Performs various conversions that are common to most
685 /// operators (C99 6.3). The conversions of array and function types are
686 /// sometimes suppressed. For example, the array->pointer conversion doesn't
687 /// apply if the array is an argument to the sizeof or address (&) operators.
688 /// In these instances, this routine should *not* be called.
689 ExprResult Sema::UsualUnaryConversions(Expr *E) {
690   // First, convert to an r-value.
691   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
692   if (Res.isInvalid())
693     return ExprError();
694   E = Res.get();
695 
696   QualType Ty = E->getType();
697   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
698 
699   // Half FP have to be promoted to float unless it is natively supported
700   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
701     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
702 
703   // Try to perform integral promotions if the object has a theoretically
704   // promotable type.
705   if (Ty->isIntegralOrUnscopedEnumerationType()) {
706     // C99 6.3.1.1p2:
707     //
708     //   The following may be used in an expression wherever an int or
709     //   unsigned int may be used:
710     //     - an object or expression with an integer type whose integer
711     //       conversion rank is less than or equal to the rank of int
712     //       and unsigned int.
713     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
714     //
715     //   If an int can represent all values of the original type, the
716     //   value is converted to an int; otherwise, it is converted to an
717     //   unsigned int. These are called the integer promotions. All
718     //   other types are unchanged by the integer promotions.
719 
720     QualType PTy = Context.isPromotableBitField(E);
721     if (!PTy.isNull()) {
722       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
723       return E;
724     }
725     if (Ty->isPromotableIntegerType()) {
726       QualType PT = Context.getPromotedIntegerType(Ty);
727       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
728       return E;
729     }
730   }
731   return E;
732 }
733 
734 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
735 /// do not have a prototype. Arguments that have type float or __fp16
736 /// are promoted to double. All other argument types are converted by
737 /// UsualUnaryConversions().
738 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
739   QualType Ty = E->getType();
740   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
741 
742   ExprResult Res = UsualUnaryConversions(E);
743   if (Res.isInvalid())
744     return ExprError();
745   E = Res.get();
746 
747   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
748   // promote to double.
749   // Note that default argument promotion applies only to float (and
750   // half/fp16); it does not apply to _Float16.
751   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
752   if (BTy && (BTy->getKind() == BuiltinType::Half ||
753               BTy->getKind() == BuiltinType::Float)) {
754     if (getLangOpts().OpenCL &&
755         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
756         if (BTy->getKind() == BuiltinType::Half) {
757             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
758         }
759     } else {
760       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
761     }
762   }
763 
764   // C++ performs lvalue-to-rvalue conversion as a default argument
765   // promotion, even on class types, but note:
766   //   C++11 [conv.lval]p2:
767   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
768   //     operand or a subexpression thereof the value contained in the
769   //     referenced object is not accessed. Otherwise, if the glvalue
770   //     has a class type, the conversion copy-initializes a temporary
771   //     of type T from the glvalue and the result of the conversion
772   //     is a prvalue for the temporary.
773   // FIXME: add some way to gate this entire thing for correctness in
774   // potentially potentially evaluated contexts.
775   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
776     ExprResult Temp = PerformCopyInitialization(
777                        InitializedEntity::InitializeTemporary(E->getType()),
778                                                 E->getExprLoc(), E);
779     if (Temp.isInvalid())
780       return ExprError();
781     E = Temp.get();
782   }
783 
784   return E;
785 }
786 
787 /// Determine the degree of POD-ness for an expression.
788 /// Incomplete types are considered POD, since this check can be performed
789 /// when we're in an unevaluated context.
790 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
791   if (Ty->isIncompleteType()) {
792     // C++11 [expr.call]p7:
793     //   After these conversions, if the argument does not have arithmetic,
794     //   enumeration, pointer, pointer to member, or class type, the program
795     //   is ill-formed.
796     //
797     // Since we've already performed array-to-pointer and function-to-pointer
798     // decay, the only such type in C++ is cv void. This also handles
799     // initializer lists as variadic arguments.
800     if (Ty->isVoidType())
801       return VAK_Invalid;
802 
803     if (Ty->isObjCObjectType())
804       return VAK_Invalid;
805     return VAK_Valid;
806   }
807 
808   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
809     return VAK_Invalid;
810 
811   if (Ty.isCXX98PODType(Context))
812     return VAK_Valid;
813 
814   // C++11 [expr.call]p7:
815   //   Passing a potentially-evaluated argument of class type (Clause 9)
816   //   having a non-trivial copy constructor, a non-trivial move constructor,
817   //   or a non-trivial destructor, with no corresponding parameter,
818   //   is conditionally-supported with implementation-defined semantics.
819   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
820     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
821       if (!Record->hasNonTrivialCopyConstructor() &&
822           !Record->hasNonTrivialMoveConstructor() &&
823           !Record->hasNonTrivialDestructor())
824         return VAK_ValidInCXX11;
825 
826   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
827     return VAK_Valid;
828 
829   if (Ty->isObjCObjectType())
830     return VAK_Invalid;
831 
832   if (getLangOpts().MSVCCompat)
833     return VAK_MSVCUndefined;
834 
835   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
836   // permitted to reject them. We should consider doing so.
837   return VAK_Undefined;
838 }
839 
840 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
841   // Don't allow one to pass an Objective-C interface to a vararg.
842   const QualType &Ty = E->getType();
843   VarArgKind VAK = isValidVarArgType(Ty);
844 
845   // Complain about passing non-POD types through varargs.
846   switch (VAK) {
847   case VAK_ValidInCXX11:
848     DiagRuntimeBehavior(
849         E->getBeginLoc(), nullptr,
850         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
851     LLVM_FALLTHROUGH;
852   case VAK_Valid:
853     if (Ty->isRecordType()) {
854       // This is unlikely to be what the user intended. If the class has a
855       // 'c_str' member function, the user probably meant to call that.
856       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
857                           PDiag(diag::warn_pass_class_arg_to_vararg)
858                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
859     }
860     break;
861 
862   case VAK_Undefined:
863   case VAK_MSVCUndefined:
864     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
865                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
866                             << getLangOpts().CPlusPlus11 << Ty << CT);
867     break;
868 
869   case VAK_Invalid:
870     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
871       Diag(E->getBeginLoc(),
872            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
873           << Ty << CT;
874     else if (Ty->isObjCObjectType())
875       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
876                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
877                               << Ty << CT);
878     else
879       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
880           << isa<InitListExpr>(E) << Ty << CT;
881     break;
882   }
883 }
884 
885 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
886 /// will create a trap if the resulting type is not a POD type.
887 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
888                                                   FunctionDecl *FDecl) {
889   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
890     // Strip the unbridged-cast placeholder expression off, if applicable.
891     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
892         (CT == VariadicMethod ||
893          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
894       E = stripARCUnbridgedCast(E);
895 
896     // Otherwise, do normal placeholder checking.
897     } else {
898       ExprResult ExprRes = CheckPlaceholderExpr(E);
899       if (ExprRes.isInvalid())
900         return ExprError();
901       E = ExprRes.get();
902     }
903   }
904 
905   ExprResult ExprRes = DefaultArgumentPromotion(E);
906   if (ExprRes.isInvalid())
907     return ExprError();
908   E = ExprRes.get();
909 
910   // Diagnostics regarding non-POD argument types are
911   // emitted along with format string checking in Sema::CheckFunctionCall().
912   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
913     // Turn this into a trap.
914     CXXScopeSpec SS;
915     SourceLocation TemplateKWLoc;
916     UnqualifiedId Name;
917     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
918                        E->getBeginLoc());
919     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
920                                           /*HasTrailingLParen=*/true,
921                                           /*IsAddressOfOperand=*/false);
922     if (TrapFn.isInvalid())
923       return ExprError();
924 
925     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
926                                     None, E->getEndLoc());
927     if (Call.isInvalid())
928       return ExprError();
929 
930     ExprResult Comma =
931         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
932     if (Comma.isInvalid())
933       return ExprError();
934     return Comma.get();
935   }
936 
937   if (!getLangOpts().CPlusPlus &&
938       RequireCompleteType(E->getExprLoc(), E->getType(),
939                           diag::err_call_incomplete_argument))
940     return ExprError();
941 
942   return E;
943 }
944 
945 /// Converts an integer to complex float type.  Helper function of
946 /// UsualArithmeticConversions()
947 ///
948 /// \return false if the integer expression is an integer type and is
949 /// successfully converted to the complex type.
950 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
951                                                   ExprResult &ComplexExpr,
952                                                   QualType IntTy,
953                                                   QualType ComplexTy,
954                                                   bool SkipCast) {
955   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
956   if (SkipCast) return false;
957   if (IntTy->isIntegerType()) {
958     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
959     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
960     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
961                                   CK_FloatingRealToComplex);
962   } else {
963     assert(IntTy->isComplexIntegerType());
964     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
965                                   CK_IntegralComplexToFloatingComplex);
966   }
967   return false;
968 }
969 
970 /// Handle arithmetic conversion with complex types.  Helper function of
971 /// UsualArithmeticConversions()
972 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
973                                              ExprResult &RHS, QualType LHSType,
974                                              QualType RHSType,
975                                              bool IsCompAssign) {
976   // if we have an integer operand, the result is the complex type.
977   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
978                                              /*skipCast*/false))
979     return LHSType;
980   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
981                                              /*skipCast*/IsCompAssign))
982     return RHSType;
983 
984   // This handles complex/complex, complex/float, or float/complex.
985   // When both operands are complex, the shorter operand is converted to the
986   // type of the longer, and that is the type of the result. This corresponds
987   // to what is done when combining two real floating-point operands.
988   // The fun begins when size promotion occur across type domains.
989   // From H&S 6.3.4: When one operand is complex and the other is a real
990   // floating-point type, the less precise type is converted, within it's
991   // real or complex domain, to the precision of the other type. For example,
992   // when combining a "long double" with a "double _Complex", the
993   // "double _Complex" is promoted to "long double _Complex".
994 
995   // Compute the rank of the two types, regardless of whether they are complex.
996   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
997 
998   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
999   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1000   QualType LHSElementType =
1001       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1002   QualType RHSElementType =
1003       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1004 
1005   QualType ResultType = S.Context.getComplexType(LHSElementType);
1006   if (Order < 0) {
1007     // Promote the precision of the LHS if not an assignment.
1008     ResultType = S.Context.getComplexType(RHSElementType);
1009     if (!IsCompAssign) {
1010       if (LHSComplexType)
1011         LHS =
1012             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1013       else
1014         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1015     }
1016   } else if (Order > 0) {
1017     // Promote the precision of the RHS.
1018     if (RHSComplexType)
1019       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1020     else
1021       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1022   }
1023   return ResultType;
1024 }
1025 
1026 /// Handle arithmetic conversion from integer to float.  Helper function
1027 /// of UsualArithmeticConversions()
1028 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1029                                            ExprResult &IntExpr,
1030                                            QualType FloatTy, QualType IntTy,
1031                                            bool ConvertFloat, bool ConvertInt) {
1032   if (IntTy->isIntegerType()) {
1033     if (ConvertInt)
1034       // Convert intExpr to the lhs floating point type.
1035       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1036                                     CK_IntegralToFloating);
1037     return FloatTy;
1038   }
1039 
1040   // Convert both sides to the appropriate complex float.
1041   assert(IntTy->isComplexIntegerType());
1042   QualType result = S.Context.getComplexType(FloatTy);
1043 
1044   // _Complex int -> _Complex float
1045   if (ConvertInt)
1046     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1047                                   CK_IntegralComplexToFloatingComplex);
1048 
1049   // float -> _Complex float
1050   if (ConvertFloat)
1051     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1052                                     CK_FloatingRealToComplex);
1053 
1054   return result;
1055 }
1056 
1057 /// Handle arithmethic conversion with floating point types.  Helper
1058 /// function of UsualArithmeticConversions()
1059 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1060                                       ExprResult &RHS, QualType LHSType,
1061                                       QualType RHSType, bool IsCompAssign) {
1062   bool LHSFloat = LHSType->isRealFloatingType();
1063   bool RHSFloat = RHSType->isRealFloatingType();
1064 
1065   // If we have two real floating types, convert the smaller operand
1066   // to the bigger result.
1067   if (LHSFloat && RHSFloat) {
1068     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1069     if (order > 0) {
1070       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1071       return LHSType;
1072     }
1073 
1074     assert(order < 0 && "illegal float comparison");
1075     if (!IsCompAssign)
1076       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1077     return RHSType;
1078   }
1079 
1080   if (LHSFloat) {
1081     // Half FP has to be promoted to float unless it is natively supported
1082     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1083       LHSType = S.Context.FloatTy;
1084 
1085     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1086                                       /*ConvertFloat=*/!IsCompAssign,
1087                                       /*ConvertInt=*/ true);
1088   }
1089   assert(RHSFloat);
1090   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1091                                     /*convertInt=*/ true,
1092                                     /*convertFloat=*/!IsCompAssign);
1093 }
1094 
1095 /// Diagnose attempts to convert between __float128 and long double if
1096 /// there is no support for such conversion. Helper function of
1097 /// UsualArithmeticConversions().
1098 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1099                                       QualType RHSType) {
1100   /*  No issue converting if at least one of the types is not a floating point
1101       type or the two types have the same rank.
1102   */
1103   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1104       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1105     return false;
1106 
1107   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1108          "The remaining types must be floating point types.");
1109 
1110   auto *LHSComplex = LHSType->getAs<ComplexType>();
1111   auto *RHSComplex = RHSType->getAs<ComplexType>();
1112 
1113   QualType LHSElemType = LHSComplex ?
1114     LHSComplex->getElementType() : LHSType;
1115   QualType RHSElemType = RHSComplex ?
1116     RHSComplex->getElementType() : RHSType;
1117 
1118   // No issue if the two types have the same representation
1119   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1120       &S.Context.getFloatTypeSemantics(RHSElemType))
1121     return false;
1122 
1123   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1124                                 RHSElemType == S.Context.LongDoubleTy);
1125   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1126                             RHSElemType == S.Context.Float128Ty);
1127 
1128   // We've handled the situation where __float128 and long double have the same
1129   // representation. We allow all conversions for all possible long double types
1130   // except PPC's double double.
1131   return Float128AndLongDouble &&
1132     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1133      &llvm::APFloat::PPCDoubleDouble());
1134 }
1135 
1136 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1137 
1138 namespace {
1139 /// These helper callbacks are placed in an anonymous namespace to
1140 /// permit their use as function template parameters.
1141 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1142   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1143 }
1144 
1145 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1146   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1147                              CK_IntegralComplexCast);
1148 }
1149 }
1150 
1151 /// Handle integer arithmetic conversions.  Helper function of
1152 /// UsualArithmeticConversions()
1153 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1154 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1155                                         ExprResult &RHS, QualType LHSType,
1156                                         QualType RHSType, bool IsCompAssign) {
1157   // The rules for this case are in C99 6.3.1.8
1158   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1159   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1160   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1161   if (LHSSigned == RHSSigned) {
1162     // Same signedness; use the higher-ranked type
1163     if (order >= 0) {
1164       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1165       return LHSType;
1166     } else if (!IsCompAssign)
1167       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1168     return RHSType;
1169   } else if (order != (LHSSigned ? 1 : -1)) {
1170     // The unsigned type has greater than or equal rank to the
1171     // signed type, so use the unsigned type
1172     if (RHSSigned) {
1173       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1174       return LHSType;
1175     } else if (!IsCompAssign)
1176       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1177     return RHSType;
1178   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1179     // The two types are different widths; if we are here, that
1180     // means the signed type is larger than the unsigned type, so
1181     // use the signed type.
1182     if (LHSSigned) {
1183       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1184       return LHSType;
1185     } else if (!IsCompAssign)
1186       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1187     return RHSType;
1188   } else {
1189     // The signed type is higher-ranked than the unsigned type,
1190     // but isn't actually any bigger (like unsigned int and long
1191     // on most 32-bit systems).  Use the unsigned type corresponding
1192     // to the signed type.
1193     QualType result =
1194       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1195     RHS = (*doRHSCast)(S, RHS.get(), result);
1196     if (!IsCompAssign)
1197       LHS = (*doLHSCast)(S, LHS.get(), result);
1198     return result;
1199   }
1200 }
1201 
1202 /// Handle conversions with GCC complex int extension.  Helper function
1203 /// of UsualArithmeticConversions()
1204 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1205                                            ExprResult &RHS, QualType LHSType,
1206                                            QualType RHSType,
1207                                            bool IsCompAssign) {
1208   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1209   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1210 
1211   if (LHSComplexInt && RHSComplexInt) {
1212     QualType LHSEltType = LHSComplexInt->getElementType();
1213     QualType RHSEltType = RHSComplexInt->getElementType();
1214     QualType ScalarType =
1215       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1216         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1217 
1218     return S.Context.getComplexType(ScalarType);
1219   }
1220 
1221   if (LHSComplexInt) {
1222     QualType LHSEltType = LHSComplexInt->getElementType();
1223     QualType ScalarType =
1224       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1225         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1226     QualType ComplexType = S.Context.getComplexType(ScalarType);
1227     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1228                               CK_IntegralRealToComplex);
1229 
1230     return ComplexType;
1231   }
1232 
1233   assert(RHSComplexInt);
1234 
1235   QualType RHSEltType = RHSComplexInt->getElementType();
1236   QualType ScalarType =
1237     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1238       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1239   QualType ComplexType = S.Context.getComplexType(ScalarType);
1240 
1241   if (!IsCompAssign)
1242     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1243                               CK_IntegralRealToComplex);
1244   return ComplexType;
1245 }
1246 
1247 /// Return the rank of a given fixed point or integer type. The value itself
1248 /// doesn't matter, but the values must be increasing with proper increasing
1249 /// rank as described in N1169 4.1.1.
1250 static unsigned GetFixedPointRank(QualType Ty) {
1251   const auto *BTy = Ty->getAs<BuiltinType>();
1252   assert(BTy && "Expected a builtin type.");
1253 
1254   switch (BTy->getKind()) {
1255   case BuiltinType::ShortFract:
1256   case BuiltinType::UShortFract:
1257   case BuiltinType::SatShortFract:
1258   case BuiltinType::SatUShortFract:
1259     return 1;
1260   case BuiltinType::Fract:
1261   case BuiltinType::UFract:
1262   case BuiltinType::SatFract:
1263   case BuiltinType::SatUFract:
1264     return 2;
1265   case BuiltinType::LongFract:
1266   case BuiltinType::ULongFract:
1267   case BuiltinType::SatLongFract:
1268   case BuiltinType::SatULongFract:
1269     return 3;
1270   case BuiltinType::ShortAccum:
1271   case BuiltinType::UShortAccum:
1272   case BuiltinType::SatShortAccum:
1273   case BuiltinType::SatUShortAccum:
1274     return 4;
1275   case BuiltinType::Accum:
1276   case BuiltinType::UAccum:
1277   case BuiltinType::SatAccum:
1278   case BuiltinType::SatUAccum:
1279     return 5;
1280   case BuiltinType::LongAccum:
1281   case BuiltinType::ULongAccum:
1282   case BuiltinType::SatLongAccum:
1283   case BuiltinType::SatULongAccum:
1284     return 6;
1285   default:
1286     if (BTy->isInteger())
1287       return 0;
1288     llvm_unreachable("Unexpected fixed point or integer type");
1289   }
1290 }
1291 
1292 /// handleFixedPointConversion - Fixed point operations between fixed
1293 /// point types and integers or other fixed point types do not fall under
1294 /// usual arithmetic conversion since these conversions could result in loss
1295 /// of precsision (N1169 4.1.4). These operations should be calculated with
1296 /// the full precision of their result type (N1169 4.1.6.2.1).
1297 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1298                                            QualType RHSTy) {
1299   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1300          "Expected at least one of the operands to be a fixed point type");
1301   assert((LHSTy->isFixedPointOrIntegerType() ||
1302           RHSTy->isFixedPointOrIntegerType()) &&
1303          "Special fixed point arithmetic operation conversions are only "
1304          "applied to ints or other fixed point types");
1305 
1306   // If one operand has signed fixed-point type and the other operand has
1307   // unsigned fixed-point type, then the unsigned fixed-point operand is
1308   // converted to its corresponding signed fixed-point type and the resulting
1309   // type is the type of the converted operand.
1310   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1311     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1312   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1313     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1314 
1315   // The result type is the type with the highest rank, whereby a fixed-point
1316   // conversion rank is always greater than an integer conversion rank; if the
1317   // type of either of the operands is a saturating fixedpoint type, the result
1318   // type shall be the saturating fixed-point type corresponding to the type
1319   // with the highest rank; the resulting value is converted (taking into
1320   // account rounding and overflow) to the precision of the resulting type.
1321   // Same ranks between signed and unsigned types are resolved earlier, so both
1322   // types are either signed or both unsigned at this point.
1323   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1324   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1325 
1326   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1327 
1328   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1329     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1330 
1331   return ResultTy;
1332 }
1333 
1334 /// UsualArithmeticConversions - Performs various conversions that are common to
1335 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1336 /// routine returns the first non-arithmetic type found. The client is
1337 /// responsible for emitting appropriate error diagnostics.
1338 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1339                                           bool IsCompAssign) {
1340   if (!IsCompAssign) {
1341     LHS = UsualUnaryConversions(LHS.get());
1342     if (LHS.isInvalid())
1343       return QualType();
1344   }
1345 
1346   RHS = UsualUnaryConversions(RHS.get());
1347   if (RHS.isInvalid())
1348     return QualType();
1349 
1350   // For conversion purposes, we ignore any qualifiers.
1351   // For example, "const float" and "float" are equivalent.
1352   QualType LHSType =
1353     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1354   QualType RHSType =
1355     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1356 
1357   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1358   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1359     LHSType = AtomicLHS->getValueType();
1360 
1361   // If both types are identical, no conversion is needed.
1362   if (LHSType == RHSType)
1363     return LHSType;
1364 
1365   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1366   // The caller can deal with this (e.g. pointer + int).
1367   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1368     return QualType();
1369 
1370   // Apply unary and bitfield promotions to the LHS's type.
1371   QualType LHSUnpromotedType = LHSType;
1372   if (LHSType->isPromotableIntegerType())
1373     LHSType = Context.getPromotedIntegerType(LHSType);
1374   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1375   if (!LHSBitfieldPromoteTy.isNull())
1376     LHSType = LHSBitfieldPromoteTy;
1377   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1378     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1379 
1380   // If both types are identical, no conversion is needed.
1381   if (LHSType == RHSType)
1382     return LHSType;
1383 
1384   // At this point, we have two different arithmetic types.
1385 
1386   // Diagnose attempts to convert between __float128 and long double where
1387   // such conversions currently can't be handled.
1388   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1389     return QualType();
1390 
1391   // Handle complex types first (C99 6.3.1.8p1).
1392   if (LHSType->isComplexType() || RHSType->isComplexType())
1393     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1394                                         IsCompAssign);
1395 
1396   // Now handle "real" floating types (i.e. float, double, long double).
1397   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1398     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1399                                  IsCompAssign);
1400 
1401   // Handle GCC complex int extension.
1402   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1403     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1404                                       IsCompAssign);
1405 
1406   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1407     return handleFixedPointConversion(*this, LHSType, RHSType);
1408 
1409   // Finally, we have two differing integer types.
1410   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1411            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1412 }
1413 
1414 //===----------------------------------------------------------------------===//
1415 //  Semantic Analysis for various Expression Types
1416 //===----------------------------------------------------------------------===//
1417 
1418 
1419 ExprResult
1420 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1421                                 SourceLocation DefaultLoc,
1422                                 SourceLocation RParenLoc,
1423                                 Expr *ControllingExpr,
1424                                 ArrayRef<ParsedType> ArgTypes,
1425                                 ArrayRef<Expr *> ArgExprs) {
1426   unsigned NumAssocs = ArgTypes.size();
1427   assert(NumAssocs == ArgExprs.size());
1428 
1429   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1430   for (unsigned i = 0; i < NumAssocs; ++i) {
1431     if (ArgTypes[i])
1432       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1433     else
1434       Types[i] = nullptr;
1435   }
1436 
1437   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1438                                              ControllingExpr,
1439                                              llvm::makeArrayRef(Types, NumAssocs),
1440                                              ArgExprs);
1441   delete [] Types;
1442   return ER;
1443 }
1444 
1445 ExprResult
1446 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1447                                  SourceLocation DefaultLoc,
1448                                  SourceLocation RParenLoc,
1449                                  Expr *ControllingExpr,
1450                                  ArrayRef<TypeSourceInfo *> Types,
1451                                  ArrayRef<Expr *> Exprs) {
1452   unsigned NumAssocs = Types.size();
1453   assert(NumAssocs == Exprs.size());
1454 
1455   // Decay and strip qualifiers for the controlling expression type, and handle
1456   // placeholder type replacement. See committee discussion from WG14 DR423.
1457   {
1458     EnterExpressionEvaluationContext Unevaluated(
1459         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1460     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1461     if (R.isInvalid())
1462       return ExprError();
1463     ControllingExpr = R.get();
1464   }
1465 
1466   // The controlling expression is an unevaluated operand, so side effects are
1467   // likely unintended.
1468   if (!inTemplateInstantiation() &&
1469       ControllingExpr->HasSideEffects(Context, false))
1470     Diag(ControllingExpr->getExprLoc(),
1471          diag::warn_side_effects_unevaluated_context);
1472 
1473   bool TypeErrorFound = false,
1474        IsResultDependent = ControllingExpr->isTypeDependent(),
1475        ContainsUnexpandedParameterPack
1476          = ControllingExpr->containsUnexpandedParameterPack();
1477 
1478   for (unsigned i = 0; i < NumAssocs; ++i) {
1479     if (Exprs[i]->containsUnexpandedParameterPack())
1480       ContainsUnexpandedParameterPack = true;
1481 
1482     if (Types[i]) {
1483       if (Types[i]->getType()->containsUnexpandedParameterPack())
1484         ContainsUnexpandedParameterPack = true;
1485 
1486       if (Types[i]->getType()->isDependentType()) {
1487         IsResultDependent = true;
1488       } else {
1489         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1490         // complete object type other than a variably modified type."
1491         unsigned D = 0;
1492         if (Types[i]->getType()->isIncompleteType())
1493           D = diag::err_assoc_type_incomplete;
1494         else if (!Types[i]->getType()->isObjectType())
1495           D = diag::err_assoc_type_nonobject;
1496         else if (Types[i]->getType()->isVariablyModifiedType())
1497           D = diag::err_assoc_type_variably_modified;
1498 
1499         if (D != 0) {
1500           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1501             << Types[i]->getTypeLoc().getSourceRange()
1502             << Types[i]->getType();
1503           TypeErrorFound = true;
1504         }
1505 
1506         // C11 6.5.1.1p2 "No two generic associations in the same generic
1507         // selection shall specify compatible types."
1508         for (unsigned j = i+1; j < NumAssocs; ++j)
1509           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1510               Context.typesAreCompatible(Types[i]->getType(),
1511                                          Types[j]->getType())) {
1512             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1513                  diag::err_assoc_compatible_types)
1514               << Types[j]->getTypeLoc().getSourceRange()
1515               << Types[j]->getType()
1516               << Types[i]->getType();
1517             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1518                  diag::note_compat_assoc)
1519               << Types[i]->getTypeLoc().getSourceRange()
1520               << Types[i]->getType();
1521             TypeErrorFound = true;
1522           }
1523       }
1524     }
1525   }
1526   if (TypeErrorFound)
1527     return ExprError();
1528 
1529   // If we determined that the generic selection is result-dependent, don't
1530   // try to compute the result expression.
1531   if (IsResultDependent)
1532     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1533                                         Exprs, DefaultLoc, RParenLoc,
1534                                         ContainsUnexpandedParameterPack);
1535 
1536   SmallVector<unsigned, 1> CompatIndices;
1537   unsigned DefaultIndex = -1U;
1538   for (unsigned i = 0; i < NumAssocs; ++i) {
1539     if (!Types[i])
1540       DefaultIndex = i;
1541     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1542                                         Types[i]->getType()))
1543       CompatIndices.push_back(i);
1544   }
1545 
1546   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1547   // type compatible with at most one of the types named in its generic
1548   // association list."
1549   if (CompatIndices.size() > 1) {
1550     // We strip parens here because the controlling expression is typically
1551     // parenthesized in macro definitions.
1552     ControllingExpr = ControllingExpr->IgnoreParens();
1553     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1554         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1555         << (unsigned)CompatIndices.size();
1556     for (unsigned I : CompatIndices) {
1557       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1558            diag::note_compat_assoc)
1559         << Types[I]->getTypeLoc().getSourceRange()
1560         << Types[I]->getType();
1561     }
1562     return ExprError();
1563   }
1564 
1565   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1566   // its controlling expression shall have type compatible with exactly one of
1567   // the types named in its generic association list."
1568   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1569     // We strip parens here because the controlling expression is typically
1570     // parenthesized in macro definitions.
1571     ControllingExpr = ControllingExpr->IgnoreParens();
1572     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1573         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1574     return ExprError();
1575   }
1576 
1577   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1578   // type name that is compatible with the type of the controlling expression,
1579   // then the result expression of the generic selection is the expression
1580   // in that generic association. Otherwise, the result expression of the
1581   // generic selection is the expression in the default generic association."
1582   unsigned ResultIndex =
1583     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1584 
1585   return GenericSelectionExpr::Create(
1586       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1587       ContainsUnexpandedParameterPack, ResultIndex);
1588 }
1589 
1590 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1591 /// location of the token and the offset of the ud-suffix within it.
1592 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1593                                      unsigned Offset) {
1594   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1595                                         S.getLangOpts());
1596 }
1597 
1598 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1599 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1600 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1601                                                  IdentifierInfo *UDSuffix,
1602                                                  SourceLocation UDSuffixLoc,
1603                                                  ArrayRef<Expr*> Args,
1604                                                  SourceLocation LitEndLoc) {
1605   assert(Args.size() <= 2 && "too many arguments for literal operator");
1606 
1607   QualType ArgTy[2];
1608   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1609     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1610     if (ArgTy[ArgIdx]->isArrayType())
1611       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1612   }
1613 
1614   DeclarationName OpName =
1615     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1616   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1617   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1618 
1619   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1620   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1621                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1622                               /*AllowStringTemplate*/ false,
1623                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1624     return ExprError();
1625 
1626   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1627 }
1628 
1629 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1630 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1631 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1632 /// multiple tokens.  However, the common case is that StringToks points to one
1633 /// string.
1634 ///
1635 ExprResult
1636 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1637   assert(!StringToks.empty() && "Must have at least one string!");
1638 
1639   StringLiteralParser Literal(StringToks, PP);
1640   if (Literal.hadError)
1641     return ExprError();
1642 
1643   SmallVector<SourceLocation, 4> StringTokLocs;
1644   for (const Token &Tok : StringToks)
1645     StringTokLocs.push_back(Tok.getLocation());
1646 
1647   QualType CharTy = Context.CharTy;
1648   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1649   if (Literal.isWide()) {
1650     CharTy = Context.getWideCharType();
1651     Kind = StringLiteral::Wide;
1652   } else if (Literal.isUTF8()) {
1653     if (getLangOpts().Char8)
1654       CharTy = Context.Char8Ty;
1655     Kind = StringLiteral::UTF8;
1656   } else if (Literal.isUTF16()) {
1657     CharTy = Context.Char16Ty;
1658     Kind = StringLiteral::UTF16;
1659   } else if (Literal.isUTF32()) {
1660     CharTy = Context.Char32Ty;
1661     Kind = StringLiteral::UTF32;
1662   } else if (Literal.isPascal()) {
1663     CharTy = Context.UnsignedCharTy;
1664   }
1665 
1666   // Warn on initializing an array of char from a u8 string literal; this
1667   // becomes ill-formed in C++2a.
1668   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1669       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1670     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1671 
1672     // Create removals for all 'u8' prefixes in the string literal(s). This
1673     // ensures C++2a compatibility (but may change the program behavior when
1674     // built by non-Clang compilers for which the execution character set is
1675     // not always UTF-8).
1676     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1677     SourceLocation RemovalDiagLoc;
1678     for (const Token &Tok : StringToks) {
1679       if (Tok.getKind() == tok::utf8_string_literal) {
1680         if (RemovalDiagLoc.isInvalid())
1681           RemovalDiagLoc = Tok.getLocation();
1682         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1683             Tok.getLocation(),
1684             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1685                                            getSourceManager(), getLangOpts())));
1686       }
1687     }
1688     Diag(RemovalDiagLoc, RemovalDiag);
1689   }
1690 
1691   QualType StrTy =
1692       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1693 
1694   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1695   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1696                                              Kind, Literal.Pascal, StrTy,
1697                                              &StringTokLocs[0],
1698                                              StringTokLocs.size());
1699   if (Literal.getUDSuffix().empty())
1700     return Lit;
1701 
1702   // We're building a user-defined literal.
1703   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1704   SourceLocation UDSuffixLoc =
1705     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1706                    Literal.getUDSuffixOffset());
1707 
1708   // Make sure we're allowed user-defined literals here.
1709   if (!UDLScope)
1710     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1711 
1712   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1713   //   operator "" X (str, len)
1714   QualType SizeType = Context.getSizeType();
1715 
1716   DeclarationName OpName =
1717     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1718   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1719   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1720 
1721   QualType ArgTy[] = {
1722     Context.getArrayDecayedType(StrTy), SizeType
1723   };
1724 
1725   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1726   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1727                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1728                                 /*AllowStringTemplate*/ true,
1729                                 /*DiagnoseMissing*/ true)) {
1730 
1731   case LOLR_Cooked: {
1732     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1733     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1734                                                     StringTokLocs[0]);
1735     Expr *Args[] = { Lit, LenArg };
1736 
1737     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1738   }
1739 
1740   case LOLR_StringTemplate: {
1741     TemplateArgumentListInfo ExplicitArgs;
1742 
1743     unsigned CharBits = Context.getIntWidth(CharTy);
1744     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1745     llvm::APSInt Value(CharBits, CharIsUnsigned);
1746 
1747     TemplateArgument TypeArg(CharTy);
1748     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1749     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1750 
1751     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1752       Value = Lit->getCodeUnit(I);
1753       TemplateArgument Arg(Context, Value, CharTy);
1754       TemplateArgumentLocInfo ArgInfo;
1755       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1756     }
1757     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1758                                     &ExplicitArgs);
1759   }
1760   case LOLR_Raw:
1761   case LOLR_Template:
1762   case LOLR_ErrorNoDiagnostic:
1763     llvm_unreachable("unexpected literal operator lookup result");
1764   case LOLR_Error:
1765     return ExprError();
1766   }
1767   llvm_unreachable("unexpected literal operator lookup result");
1768 }
1769 
1770 DeclRefExpr *
1771 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1772                        SourceLocation Loc,
1773                        const CXXScopeSpec *SS) {
1774   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1775   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1776 }
1777 
1778 DeclRefExpr *
1779 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1780                        const DeclarationNameInfo &NameInfo,
1781                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1782                        SourceLocation TemplateKWLoc,
1783                        const TemplateArgumentListInfo *TemplateArgs) {
1784   NestedNameSpecifierLoc NNS =
1785       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1786   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1787                           TemplateArgs);
1788 }
1789 
1790 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1791   // A declaration named in an unevaluated operand never constitutes an odr-use.
1792   if (isUnevaluatedContext())
1793     return NOUR_Unevaluated;
1794 
1795   // C++2a [basic.def.odr]p4:
1796   //   A variable x whose name appears as a potentially-evaluated expression e
1797   //   is odr-used by e unless [...] x is a reference that is usable in
1798   //   constant expressions.
1799   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800     if (VD->getType()->isReferenceType() &&
1801         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1802         VD->isUsableInConstantExpressions(Context))
1803       return NOUR_Constant;
1804   }
1805 
1806   // All remaining non-variable cases constitute an odr-use. For variables, we
1807   // need to wait and see how the expression is used.
1808   return NOUR_None;
1809 }
1810 
1811 /// BuildDeclRefExpr - Build an expression that references a
1812 /// declaration that does not require a closure capture.
1813 DeclRefExpr *
1814 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1815                        const DeclarationNameInfo &NameInfo,
1816                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1817                        SourceLocation TemplateKWLoc,
1818                        const TemplateArgumentListInfo *TemplateArgs) {
1819   bool RefersToCapturedVariable =
1820       isa<VarDecl>(D) &&
1821       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1822 
1823   DeclRefExpr *E = DeclRefExpr::Create(
1824       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1825       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1826   MarkDeclRefReferenced(E);
1827 
1828   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1829       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1830       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1831     getCurFunction()->recordUseOfWeak(E);
1832 
1833   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1834   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1835     FD = IFD->getAnonField();
1836   if (FD) {
1837     UnusedPrivateFields.remove(FD);
1838     // Just in case we're building an illegal pointer-to-member.
1839     if (FD->isBitField())
1840       E->setObjectKind(OK_BitField);
1841   }
1842 
1843   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1844   // designates a bit-field.
1845   if (auto *BD = dyn_cast<BindingDecl>(D))
1846     if (auto *BE = BD->getBinding())
1847       E->setObjectKind(BE->getObjectKind());
1848 
1849   return E;
1850 }
1851 
1852 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1853 /// possibly a list of template arguments.
1854 ///
1855 /// If this produces template arguments, it is permitted to call
1856 /// DecomposeTemplateName.
1857 ///
1858 /// This actually loses a lot of source location information for
1859 /// non-standard name kinds; we should consider preserving that in
1860 /// some way.
1861 void
1862 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1863                              TemplateArgumentListInfo &Buffer,
1864                              DeclarationNameInfo &NameInfo,
1865                              const TemplateArgumentListInfo *&TemplateArgs) {
1866   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1867     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1868     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1869 
1870     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1871                                        Id.TemplateId->NumArgs);
1872     translateTemplateArguments(TemplateArgsPtr, Buffer);
1873 
1874     TemplateName TName = Id.TemplateId->Template.get();
1875     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1876     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1877     TemplateArgs = &Buffer;
1878   } else {
1879     NameInfo = GetNameFromUnqualifiedId(Id);
1880     TemplateArgs = nullptr;
1881   }
1882 }
1883 
1884 static void emitEmptyLookupTypoDiagnostic(
1885     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1886     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1887     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1888   DeclContext *Ctx =
1889       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1890   if (!TC) {
1891     // Emit a special diagnostic for failed member lookups.
1892     // FIXME: computing the declaration context might fail here (?)
1893     if (Ctx)
1894       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1895                                                  << SS.getRange();
1896     else
1897       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1898     return;
1899   }
1900 
1901   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1902   bool DroppedSpecifier =
1903       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1904   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1905                         ? diag::note_implicit_param_decl
1906                         : diag::note_previous_decl;
1907   if (!Ctx)
1908     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1909                          SemaRef.PDiag(NoteID));
1910   else
1911     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1912                                  << Typo << Ctx << DroppedSpecifier
1913                                  << SS.getRange(),
1914                          SemaRef.PDiag(NoteID));
1915 }
1916 
1917 /// Diagnose an empty lookup.
1918 ///
1919 /// \return false if new lookup candidates were found
1920 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1921                                CorrectionCandidateCallback &CCC,
1922                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1923                                ArrayRef<Expr *> Args, TypoExpr **Out) {
1924   DeclarationName Name = R.getLookupName();
1925 
1926   unsigned diagnostic = diag::err_undeclared_var_use;
1927   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1928   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1929       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1930       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1931     diagnostic = diag::err_undeclared_use;
1932     diagnostic_suggest = diag::err_undeclared_use_suggest;
1933   }
1934 
1935   // If the original lookup was an unqualified lookup, fake an
1936   // unqualified lookup.  This is useful when (for example) the
1937   // original lookup would not have found something because it was a
1938   // dependent name.
1939   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1940   while (DC) {
1941     if (isa<CXXRecordDecl>(DC)) {
1942       LookupQualifiedName(R, DC);
1943 
1944       if (!R.empty()) {
1945         // Don't give errors about ambiguities in this lookup.
1946         R.suppressDiagnostics();
1947 
1948         // During a default argument instantiation the CurContext points
1949         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1950         // function parameter list, hence add an explicit check.
1951         bool isDefaultArgument =
1952             !CodeSynthesisContexts.empty() &&
1953             CodeSynthesisContexts.back().Kind ==
1954                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1955         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1956         bool isInstance = CurMethod &&
1957                           CurMethod->isInstance() &&
1958                           DC == CurMethod->getParent() && !isDefaultArgument;
1959 
1960         // Give a code modification hint to insert 'this->'.
1961         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1962         // Actually quite difficult!
1963         if (getLangOpts().MSVCCompat)
1964           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1965         if (isInstance) {
1966           Diag(R.getNameLoc(), diagnostic) << Name
1967             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1968           CheckCXXThisCapture(R.getNameLoc());
1969         } else {
1970           Diag(R.getNameLoc(), diagnostic) << Name;
1971         }
1972 
1973         // Do we really want to note all of these?
1974         for (NamedDecl *D : R)
1975           Diag(D->getLocation(), diag::note_dependent_var_use);
1976 
1977         // Return true if we are inside a default argument instantiation
1978         // and the found name refers to an instance member function, otherwise
1979         // the function calling DiagnoseEmptyLookup will try to create an
1980         // implicit member call and this is wrong for default argument.
1981         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1982           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1983           return true;
1984         }
1985 
1986         // Tell the callee to try to recover.
1987         return false;
1988       }
1989 
1990       R.clear();
1991     }
1992 
1993     DC = DC->getLookupParent();
1994   }
1995 
1996   // We didn't find anything, so try to correct for a typo.
1997   TypoCorrection Corrected;
1998   if (S && Out) {
1999     SourceLocation TypoLoc = R.getNameLoc();
2000     assert(!ExplicitTemplateArgs &&
2001            "Diagnosing an empty lookup with explicit template args!");
2002     *Out = CorrectTypoDelayed(
2003         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2004         [=](const TypoCorrection &TC) {
2005           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2006                                         diagnostic, diagnostic_suggest);
2007         },
2008         nullptr, CTK_ErrorRecovery);
2009     if (*Out)
2010       return true;
2011   } else if (S &&
2012              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2013                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2014     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2015     bool DroppedSpecifier =
2016         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2017     R.setLookupName(Corrected.getCorrection());
2018 
2019     bool AcceptableWithRecovery = false;
2020     bool AcceptableWithoutRecovery = false;
2021     NamedDecl *ND = Corrected.getFoundDecl();
2022     if (ND) {
2023       if (Corrected.isOverloaded()) {
2024         OverloadCandidateSet OCS(R.getNameLoc(),
2025                                  OverloadCandidateSet::CSK_Normal);
2026         OverloadCandidateSet::iterator Best;
2027         for (NamedDecl *CD : Corrected) {
2028           if (FunctionTemplateDecl *FTD =
2029                    dyn_cast<FunctionTemplateDecl>(CD))
2030             AddTemplateOverloadCandidate(
2031                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2032                 Args, OCS);
2033           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2034             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2035               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2036                                    Args, OCS);
2037         }
2038         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2039         case OR_Success:
2040           ND = Best->FoundDecl;
2041           Corrected.setCorrectionDecl(ND);
2042           break;
2043         default:
2044           // FIXME: Arbitrarily pick the first declaration for the note.
2045           Corrected.setCorrectionDecl(ND);
2046           break;
2047         }
2048       }
2049       R.addDecl(ND);
2050       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2051         CXXRecordDecl *Record = nullptr;
2052         if (Corrected.getCorrectionSpecifier()) {
2053           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2054           Record = Ty->getAsCXXRecordDecl();
2055         }
2056         if (!Record)
2057           Record = cast<CXXRecordDecl>(
2058               ND->getDeclContext()->getRedeclContext());
2059         R.setNamingClass(Record);
2060       }
2061 
2062       auto *UnderlyingND = ND->getUnderlyingDecl();
2063       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2064                                isa<FunctionTemplateDecl>(UnderlyingND);
2065       // FIXME: If we ended up with a typo for a type name or
2066       // Objective-C class name, we're in trouble because the parser
2067       // is in the wrong place to recover. Suggest the typo
2068       // correction, but don't make it a fix-it since we're not going
2069       // to recover well anyway.
2070       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2071                                   getAsTypeTemplateDecl(UnderlyingND) ||
2072                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2073     } else {
2074       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2075       // because we aren't able to recover.
2076       AcceptableWithoutRecovery = true;
2077     }
2078 
2079     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2080       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2081                             ? diag::note_implicit_param_decl
2082                             : diag::note_previous_decl;
2083       if (SS.isEmpty())
2084         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2085                      PDiag(NoteID), AcceptableWithRecovery);
2086       else
2087         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2088                                   << Name << computeDeclContext(SS, false)
2089                                   << DroppedSpecifier << SS.getRange(),
2090                      PDiag(NoteID), AcceptableWithRecovery);
2091 
2092       // Tell the callee whether to try to recover.
2093       return !AcceptableWithRecovery;
2094     }
2095   }
2096   R.clear();
2097 
2098   // Emit a special diagnostic for failed member lookups.
2099   // FIXME: computing the declaration context might fail here (?)
2100   if (!SS.isEmpty()) {
2101     Diag(R.getNameLoc(), diag::err_no_member)
2102       << Name << computeDeclContext(SS, false)
2103       << SS.getRange();
2104     return true;
2105   }
2106 
2107   // Give up, we can't recover.
2108   Diag(R.getNameLoc(), diagnostic) << Name;
2109   return true;
2110 }
2111 
2112 /// In Microsoft mode, if we are inside a template class whose parent class has
2113 /// dependent base classes, and we can't resolve an unqualified identifier, then
2114 /// assume the identifier is a member of a dependent base class.  We can only
2115 /// recover successfully in static methods, instance methods, and other contexts
2116 /// where 'this' is available.  This doesn't precisely match MSVC's
2117 /// instantiation model, but it's close enough.
2118 static Expr *
2119 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2120                                DeclarationNameInfo &NameInfo,
2121                                SourceLocation TemplateKWLoc,
2122                                const TemplateArgumentListInfo *TemplateArgs) {
2123   // Only try to recover from lookup into dependent bases in static methods or
2124   // contexts where 'this' is available.
2125   QualType ThisType = S.getCurrentThisType();
2126   const CXXRecordDecl *RD = nullptr;
2127   if (!ThisType.isNull())
2128     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2129   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2130     RD = MD->getParent();
2131   if (!RD || !RD->hasAnyDependentBases())
2132     return nullptr;
2133 
2134   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2135   // is available, suggest inserting 'this->' as a fixit.
2136   SourceLocation Loc = NameInfo.getLoc();
2137   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2138   DB << NameInfo.getName() << RD;
2139 
2140   if (!ThisType.isNull()) {
2141     DB << FixItHint::CreateInsertion(Loc, "this->");
2142     return CXXDependentScopeMemberExpr::Create(
2143         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2144         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2145         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2146   }
2147 
2148   // Synthesize a fake NNS that points to the derived class.  This will
2149   // perform name lookup during template instantiation.
2150   CXXScopeSpec SS;
2151   auto *NNS =
2152       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2153   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2154   return DependentScopeDeclRefExpr::Create(
2155       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2156       TemplateArgs);
2157 }
2158 
2159 ExprResult
2160 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2161                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2162                         bool HasTrailingLParen, bool IsAddressOfOperand,
2163                         CorrectionCandidateCallback *CCC,
2164                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2165   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2166          "cannot be direct & operand and have a trailing lparen");
2167   if (SS.isInvalid())
2168     return ExprError();
2169 
2170   TemplateArgumentListInfo TemplateArgsBuffer;
2171 
2172   // Decompose the UnqualifiedId into the following data.
2173   DeclarationNameInfo NameInfo;
2174   const TemplateArgumentListInfo *TemplateArgs;
2175   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2176 
2177   DeclarationName Name = NameInfo.getName();
2178   IdentifierInfo *II = Name.getAsIdentifierInfo();
2179   SourceLocation NameLoc = NameInfo.getLoc();
2180 
2181   if (II && II->isEditorPlaceholder()) {
2182     // FIXME: When typed placeholders are supported we can create a typed
2183     // placeholder expression node.
2184     return ExprError();
2185   }
2186 
2187   // C++ [temp.dep.expr]p3:
2188   //   An id-expression is type-dependent if it contains:
2189   //     -- an identifier that was declared with a dependent type,
2190   //        (note: handled after lookup)
2191   //     -- a template-id that is dependent,
2192   //        (note: handled in BuildTemplateIdExpr)
2193   //     -- a conversion-function-id that specifies a dependent type,
2194   //     -- a nested-name-specifier that contains a class-name that
2195   //        names a dependent type.
2196   // Determine whether this is a member of an unknown specialization;
2197   // we need to handle these differently.
2198   bool DependentID = false;
2199   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2200       Name.getCXXNameType()->isDependentType()) {
2201     DependentID = true;
2202   } else if (SS.isSet()) {
2203     if (DeclContext *DC = computeDeclContext(SS, false)) {
2204       if (RequireCompleteDeclContext(SS, DC))
2205         return ExprError();
2206     } else {
2207       DependentID = true;
2208     }
2209   }
2210 
2211   if (DependentID)
2212     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2213                                       IsAddressOfOperand, TemplateArgs);
2214 
2215   // Perform the required lookup.
2216   LookupResult R(*this, NameInfo,
2217                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2218                      ? LookupObjCImplicitSelfParam
2219                      : LookupOrdinaryName);
2220   if (TemplateKWLoc.isValid() || TemplateArgs) {
2221     // Lookup the template name again to correctly establish the context in
2222     // which it was found. This is really unfortunate as we already did the
2223     // lookup to determine that it was a template name in the first place. If
2224     // this becomes a performance hit, we can work harder to preserve those
2225     // results until we get here but it's likely not worth it.
2226     bool MemberOfUnknownSpecialization;
2227     AssumedTemplateKind AssumedTemplate;
2228     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2229                            MemberOfUnknownSpecialization, TemplateKWLoc,
2230                            &AssumedTemplate))
2231       return ExprError();
2232 
2233     if (MemberOfUnknownSpecialization ||
2234         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2235       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2236                                         IsAddressOfOperand, TemplateArgs);
2237   } else {
2238     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2239     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2240 
2241     // If the result might be in a dependent base class, this is a dependent
2242     // id-expression.
2243     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2244       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2245                                         IsAddressOfOperand, TemplateArgs);
2246 
2247     // If this reference is in an Objective-C method, then we need to do
2248     // some special Objective-C lookup, too.
2249     if (IvarLookupFollowUp) {
2250       ExprResult E(LookupInObjCMethod(R, S, II, true));
2251       if (E.isInvalid())
2252         return ExprError();
2253 
2254       if (Expr *Ex = E.getAs<Expr>())
2255         return Ex;
2256     }
2257   }
2258 
2259   if (R.isAmbiguous())
2260     return ExprError();
2261 
2262   // This could be an implicitly declared function reference (legal in C90,
2263   // extension in C99, forbidden in C++).
2264   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2265     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2266     if (D) R.addDecl(D);
2267   }
2268 
2269   // Determine whether this name might be a candidate for
2270   // argument-dependent lookup.
2271   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2272 
2273   if (R.empty() && !ADL) {
2274     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2275       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2276                                                    TemplateKWLoc, TemplateArgs))
2277         return E;
2278     }
2279 
2280     // Don't diagnose an empty lookup for inline assembly.
2281     if (IsInlineAsmIdentifier)
2282       return ExprError();
2283 
2284     // If this name wasn't predeclared and if this is not a function
2285     // call, diagnose the problem.
2286     TypoExpr *TE = nullptr;
2287     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2288                                                        : nullptr);
2289     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2290     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2291            "Typo correction callback misconfigured");
2292     if (CCC) {
2293       // Make sure the callback knows what the typo being diagnosed is.
2294       CCC->setTypoName(II);
2295       if (SS.isValid())
2296         CCC->setTypoNNS(SS.getScopeRep());
2297     }
2298     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2299     // a template name, but we happen to have always already looked up the name
2300     // before we get here if it must be a template name.
2301     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2302                             None, &TE)) {
2303       if (TE && KeywordReplacement) {
2304         auto &State = getTypoExprState(TE);
2305         auto BestTC = State.Consumer->getNextCorrection();
2306         if (BestTC.isKeyword()) {
2307           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2308           if (State.DiagHandler)
2309             State.DiagHandler(BestTC);
2310           KeywordReplacement->startToken();
2311           KeywordReplacement->setKind(II->getTokenID());
2312           KeywordReplacement->setIdentifierInfo(II);
2313           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2314           // Clean up the state associated with the TypoExpr, since it has
2315           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2316           clearDelayedTypo(TE);
2317           // Signal that a correction to a keyword was performed by returning a
2318           // valid-but-null ExprResult.
2319           return (Expr*)nullptr;
2320         }
2321         State.Consumer->resetCorrectionStream();
2322       }
2323       return TE ? TE : ExprError();
2324     }
2325 
2326     assert(!R.empty() &&
2327            "DiagnoseEmptyLookup returned false but added no results");
2328 
2329     // If we found an Objective-C instance variable, let
2330     // LookupInObjCMethod build the appropriate expression to
2331     // reference the ivar.
2332     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2333       R.clear();
2334       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2335       // In a hopelessly buggy code, Objective-C instance variable
2336       // lookup fails and no expression will be built to reference it.
2337       if (!E.isInvalid() && !E.get())
2338         return ExprError();
2339       return E;
2340     }
2341   }
2342 
2343   // This is guaranteed from this point on.
2344   assert(!R.empty() || ADL);
2345 
2346   // Check whether this might be a C++ implicit instance member access.
2347   // C++ [class.mfct.non-static]p3:
2348   //   When an id-expression that is not part of a class member access
2349   //   syntax and not used to form a pointer to member is used in the
2350   //   body of a non-static member function of class X, if name lookup
2351   //   resolves the name in the id-expression to a non-static non-type
2352   //   member of some class C, the id-expression is transformed into a
2353   //   class member access expression using (*this) as the
2354   //   postfix-expression to the left of the . operator.
2355   //
2356   // But we don't actually need to do this for '&' operands if R
2357   // resolved to a function or overloaded function set, because the
2358   // expression is ill-formed if it actually works out to be a
2359   // non-static member function:
2360   //
2361   // C++ [expr.ref]p4:
2362   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2363   //   [t]he expression can be used only as the left-hand operand of a
2364   //   member function call.
2365   //
2366   // There are other safeguards against such uses, but it's important
2367   // to get this right here so that we don't end up making a
2368   // spuriously dependent expression if we're inside a dependent
2369   // instance method.
2370   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2371     bool MightBeImplicitMember;
2372     if (!IsAddressOfOperand)
2373       MightBeImplicitMember = true;
2374     else if (!SS.isEmpty())
2375       MightBeImplicitMember = false;
2376     else if (R.isOverloadedResult())
2377       MightBeImplicitMember = false;
2378     else if (R.isUnresolvableResult())
2379       MightBeImplicitMember = true;
2380     else
2381       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2382                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2383                               isa<MSPropertyDecl>(R.getFoundDecl());
2384 
2385     if (MightBeImplicitMember)
2386       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2387                                              R, TemplateArgs, S);
2388   }
2389 
2390   if (TemplateArgs || TemplateKWLoc.isValid()) {
2391 
2392     // In C++1y, if this is a variable template id, then check it
2393     // in BuildTemplateIdExpr().
2394     // The single lookup result must be a variable template declaration.
2395     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2396         Id.TemplateId->Kind == TNK_Var_template) {
2397       assert(R.getAsSingle<VarTemplateDecl>() &&
2398              "There should only be one declaration found.");
2399     }
2400 
2401     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2402   }
2403 
2404   return BuildDeclarationNameExpr(SS, R, ADL);
2405 }
2406 
2407 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2408 /// declaration name, generally during template instantiation.
2409 /// There's a large number of things which don't need to be done along
2410 /// this path.
2411 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2412     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2413     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2414   DeclContext *DC = computeDeclContext(SS, false);
2415   if (!DC)
2416     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2417                                      NameInfo, /*TemplateArgs=*/nullptr);
2418 
2419   if (RequireCompleteDeclContext(SS, DC))
2420     return ExprError();
2421 
2422   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2423   LookupQualifiedName(R, DC);
2424 
2425   if (R.isAmbiguous())
2426     return ExprError();
2427 
2428   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2429     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2430                                      NameInfo, /*TemplateArgs=*/nullptr);
2431 
2432   if (R.empty()) {
2433     Diag(NameInfo.getLoc(), diag::err_no_member)
2434       << NameInfo.getName() << DC << SS.getRange();
2435     return ExprError();
2436   }
2437 
2438   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2439     // Diagnose a missing typename if this resolved unambiguously to a type in
2440     // a dependent context.  If we can recover with a type, downgrade this to
2441     // a warning in Microsoft compatibility mode.
2442     unsigned DiagID = diag::err_typename_missing;
2443     if (RecoveryTSI && getLangOpts().MSVCCompat)
2444       DiagID = diag::ext_typename_missing;
2445     SourceLocation Loc = SS.getBeginLoc();
2446     auto D = Diag(Loc, DiagID);
2447     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2448       << SourceRange(Loc, NameInfo.getEndLoc());
2449 
2450     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2451     // context.
2452     if (!RecoveryTSI)
2453       return ExprError();
2454 
2455     // Only issue the fixit if we're prepared to recover.
2456     D << FixItHint::CreateInsertion(Loc, "typename ");
2457 
2458     // Recover by pretending this was an elaborated type.
2459     QualType Ty = Context.getTypeDeclType(TD);
2460     TypeLocBuilder TLB;
2461     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2462 
2463     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2464     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2465     QTL.setElaboratedKeywordLoc(SourceLocation());
2466     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2467 
2468     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2469 
2470     return ExprEmpty();
2471   }
2472 
2473   // Defend against this resolving to an implicit member access. We usually
2474   // won't get here if this might be a legitimate a class member (we end up in
2475   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2476   // a pointer-to-member or in an unevaluated context in C++11.
2477   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2478     return BuildPossibleImplicitMemberExpr(SS,
2479                                            /*TemplateKWLoc=*/SourceLocation(),
2480                                            R, /*TemplateArgs=*/nullptr, S);
2481 
2482   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2483 }
2484 
2485 /// The parser has read a name in, and Sema has detected that we're currently
2486 /// inside an ObjC method. Perform some additional checks and determine if we
2487 /// should form a reference to an ivar.
2488 ///
2489 /// Ideally, most of this would be done by lookup, but there's
2490 /// actually quite a lot of extra work involved.
2491 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2492                                         IdentifierInfo *II) {
2493   SourceLocation Loc = Lookup.getNameLoc();
2494   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2495 
2496   // Check for error condition which is already reported.
2497   if (!CurMethod)
2498     return DeclResult(true);
2499 
2500   // There are two cases to handle here.  1) scoped lookup could have failed,
2501   // in which case we should look for an ivar.  2) scoped lookup could have
2502   // found a decl, but that decl is outside the current instance method (i.e.
2503   // a global variable).  In these two cases, we do a lookup for an ivar with
2504   // this name, if the lookup sucedes, we replace it our current decl.
2505 
2506   // If we're in a class method, we don't normally want to look for
2507   // ivars.  But if we don't find anything else, and there's an
2508   // ivar, that's an error.
2509   bool IsClassMethod = CurMethod->isClassMethod();
2510 
2511   bool LookForIvars;
2512   if (Lookup.empty())
2513     LookForIvars = true;
2514   else if (IsClassMethod)
2515     LookForIvars = false;
2516   else
2517     LookForIvars = (Lookup.isSingleResult() &&
2518                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2519   ObjCInterfaceDecl *IFace = nullptr;
2520   if (LookForIvars) {
2521     IFace = CurMethod->getClassInterface();
2522     ObjCInterfaceDecl *ClassDeclared;
2523     ObjCIvarDecl *IV = nullptr;
2524     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2525       // Diagnose using an ivar in a class method.
2526       if (IsClassMethod) {
2527         Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2528         return DeclResult(true);
2529       }
2530 
2531       // Diagnose the use of an ivar outside of the declaring class.
2532       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2533           !declaresSameEntity(ClassDeclared, IFace) &&
2534           !getLangOpts().DebuggerSupport)
2535         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2536 
2537       // Success.
2538       return IV;
2539     }
2540   } else if (CurMethod->isInstanceMethod()) {
2541     // We should warn if a local variable hides an ivar.
2542     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2543       ObjCInterfaceDecl *ClassDeclared;
2544       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2545         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2546             declaresSameEntity(IFace, ClassDeclared))
2547           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2548       }
2549     }
2550   } else if (Lookup.isSingleResult() &&
2551              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2552     // If accessing a stand-alone ivar in a class method, this is an error.
2553     if (const ObjCIvarDecl *IV =
2554             dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2555       Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2556       return DeclResult(true);
2557     }
2558   }
2559 
2560   // Didn't encounter an error, didn't find an ivar.
2561   return DeclResult(false);
2562 }
2563 
2564 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2565                                   ObjCIvarDecl *IV) {
2566   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2567   assert(CurMethod && CurMethod->isInstanceMethod() &&
2568          "should not reference ivar from this context");
2569 
2570   ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2571   assert(IFace && "should not reference ivar from this context");
2572 
2573   // If we're referencing an invalid decl, just return this as a silent
2574   // error node.  The error diagnostic was already emitted on the decl.
2575   if (IV->isInvalidDecl())
2576     return ExprError();
2577 
2578   // Check if referencing a field with __attribute__((deprecated)).
2579   if (DiagnoseUseOfDecl(IV, Loc))
2580     return ExprError();
2581 
2582   // FIXME: This should use a new expr for a direct reference, don't
2583   // turn this into Self->ivar, just return a BareIVarExpr or something.
2584   IdentifierInfo &II = Context.Idents.get("self");
2585   UnqualifiedId SelfName;
2586   SelfName.setIdentifier(&II, SourceLocation());
2587   SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2588   CXXScopeSpec SelfScopeSpec;
2589   SourceLocation TemplateKWLoc;
2590   ExprResult SelfExpr =
2591       ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2592                         /*HasTrailingLParen=*/false,
2593                         /*IsAddressOfOperand=*/false);
2594   if (SelfExpr.isInvalid())
2595     return ExprError();
2596 
2597   SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2598   if (SelfExpr.isInvalid())
2599     return ExprError();
2600 
2601   MarkAnyDeclReferenced(Loc, IV, true);
2602 
2603   ObjCMethodFamily MF = CurMethod->getMethodFamily();
2604   if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2605       !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2606     Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2607 
2608   ObjCIvarRefExpr *Result = new (Context)
2609       ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2610                       IV->getLocation(), SelfExpr.get(), true, true);
2611 
2612   if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2613     if (!isUnevaluatedContext() &&
2614         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2615       getCurFunction()->recordUseOfWeak(Result);
2616   }
2617   if (getLangOpts().ObjCAutoRefCount)
2618     if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2619       ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2620 
2621   return Result;
2622 }
2623 
2624 /// The parser has read a name in, and Sema has detected that we're currently
2625 /// inside an ObjC method. Perform some additional checks and determine if we
2626 /// should form a reference to an ivar. If so, build an expression referencing
2627 /// that ivar.
2628 ExprResult
2629 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2630                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2631   // FIXME: Integrate this lookup step into LookupParsedName.
2632   DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2633   if (Ivar.isInvalid())
2634     return ExprError();
2635   if (Ivar.isUsable())
2636     return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2637                             cast<ObjCIvarDecl>(Ivar.get()));
2638 
2639   if (Lookup.empty() && II && AllowBuiltinCreation)
2640     LookupBuiltin(Lookup);
2641 
2642   // Sentinel value saying that we didn't do anything special.
2643   return ExprResult(false);
2644 }
2645 
2646 /// Cast a base object to a member's actual type.
2647 ///
2648 /// Logically this happens in three phases:
2649 ///
2650 /// * First we cast from the base type to the naming class.
2651 ///   The naming class is the class into which we were looking
2652 ///   when we found the member;  it's the qualifier type if a
2653 ///   qualifier was provided, and otherwise it's the base type.
2654 ///
2655 /// * Next we cast from the naming class to the declaring class.
2656 ///   If the member we found was brought into a class's scope by
2657 ///   a using declaration, this is that class;  otherwise it's
2658 ///   the class declaring the member.
2659 ///
2660 /// * Finally we cast from the declaring class to the "true"
2661 ///   declaring class of the member.  This conversion does not
2662 ///   obey access control.
2663 ExprResult
2664 Sema::PerformObjectMemberConversion(Expr *From,
2665                                     NestedNameSpecifier *Qualifier,
2666                                     NamedDecl *FoundDecl,
2667                                     NamedDecl *Member) {
2668   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2669   if (!RD)
2670     return From;
2671 
2672   QualType DestRecordType;
2673   QualType DestType;
2674   QualType FromRecordType;
2675   QualType FromType = From->getType();
2676   bool PointerConversions = false;
2677   if (isa<FieldDecl>(Member)) {
2678     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2679     auto FromPtrType = FromType->getAs<PointerType>();
2680     DestRecordType = Context.getAddrSpaceQualType(
2681         DestRecordType, FromPtrType
2682                             ? FromType->getPointeeType().getAddressSpace()
2683                             : FromType.getAddressSpace());
2684 
2685     if (FromPtrType) {
2686       DestType = Context.getPointerType(DestRecordType);
2687       FromRecordType = FromPtrType->getPointeeType();
2688       PointerConversions = true;
2689     } else {
2690       DestType = DestRecordType;
2691       FromRecordType = FromType;
2692     }
2693   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2694     if (Method->isStatic())
2695       return From;
2696 
2697     DestType = Method->getThisType();
2698     DestRecordType = DestType->getPointeeType();
2699 
2700     if (FromType->getAs<PointerType>()) {
2701       FromRecordType = FromType->getPointeeType();
2702       PointerConversions = true;
2703     } else {
2704       FromRecordType = FromType;
2705       DestType = DestRecordType;
2706     }
2707   } else {
2708     // No conversion necessary.
2709     return From;
2710   }
2711 
2712   if (DestType->isDependentType() || FromType->isDependentType())
2713     return From;
2714 
2715   // If the unqualified types are the same, no conversion is necessary.
2716   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2717     return From;
2718 
2719   SourceRange FromRange = From->getSourceRange();
2720   SourceLocation FromLoc = FromRange.getBegin();
2721 
2722   ExprValueKind VK = From->getValueKind();
2723 
2724   // C++ [class.member.lookup]p8:
2725   //   [...] Ambiguities can often be resolved by qualifying a name with its
2726   //   class name.
2727   //
2728   // If the member was a qualified name and the qualified referred to a
2729   // specific base subobject type, we'll cast to that intermediate type
2730   // first and then to the object in which the member is declared. That allows
2731   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2732   //
2733   //   class Base { public: int x; };
2734   //   class Derived1 : public Base { };
2735   //   class Derived2 : public Base { };
2736   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2737   //
2738   //   void VeryDerived::f() {
2739   //     x = 17; // error: ambiguous base subobjects
2740   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2741   //   }
2742   if (Qualifier && Qualifier->getAsType()) {
2743     QualType QType = QualType(Qualifier->getAsType(), 0);
2744     assert(QType->isRecordType() && "lookup done with non-record type");
2745 
2746     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2747 
2748     // In C++98, the qualifier type doesn't actually have to be a base
2749     // type of the object type, in which case we just ignore it.
2750     // Otherwise build the appropriate casts.
2751     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2752       CXXCastPath BasePath;
2753       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2754                                        FromLoc, FromRange, &BasePath))
2755         return ExprError();
2756 
2757       if (PointerConversions)
2758         QType = Context.getPointerType(QType);
2759       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2760                                VK, &BasePath).get();
2761 
2762       FromType = QType;
2763       FromRecordType = QRecordType;
2764 
2765       // If the qualifier type was the same as the destination type,
2766       // we're done.
2767       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2768         return From;
2769     }
2770   }
2771 
2772   bool IgnoreAccess = false;
2773 
2774   // If we actually found the member through a using declaration, cast
2775   // down to the using declaration's type.
2776   //
2777   // Pointer equality is fine here because only one declaration of a
2778   // class ever has member declarations.
2779   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2780     assert(isa<UsingShadowDecl>(FoundDecl));
2781     QualType URecordType = Context.getTypeDeclType(
2782                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2783 
2784     // We only need to do this if the naming-class to declaring-class
2785     // conversion is non-trivial.
2786     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2787       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2788       CXXCastPath BasePath;
2789       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2790                                        FromLoc, FromRange, &BasePath))
2791         return ExprError();
2792 
2793       QualType UType = URecordType;
2794       if (PointerConversions)
2795         UType = Context.getPointerType(UType);
2796       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2797                                VK, &BasePath).get();
2798       FromType = UType;
2799       FromRecordType = URecordType;
2800     }
2801 
2802     // We don't do access control for the conversion from the
2803     // declaring class to the true declaring class.
2804     IgnoreAccess = true;
2805   }
2806 
2807   CXXCastPath BasePath;
2808   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2809                                    FromLoc, FromRange, &BasePath,
2810                                    IgnoreAccess))
2811     return ExprError();
2812 
2813   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2814                            VK, &BasePath);
2815 }
2816 
2817 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2818                                       const LookupResult &R,
2819                                       bool HasTrailingLParen) {
2820   // Only when used directly as the postfix-expression of a call.
2821   if (!HasTrailingLParen)
2822     return false;
2823 
2824   // Never if a scope specifier was provided.
2825   if (SS.isSet())
2826     return false;
2827 
2828   // Only in C++ or ObjC++.
2829   if (!getLangOpts().CPlusPlus)
2830     return false;
2831 
2832   // Turn off ADL when we find certain kinds of declarations during
2833   // normal lookup:
2834   for (NamedDecl *D : R) {
2835     // C++0x [basic.lookup.argdep]p3:
2836     //     -- a declaration of a class member
2837     // Since using decls preserve this property, we check this on the
2838     // original decl.
2839     if (D->isCXXClassMember())
2840       return false;
2841 
2842     // C++0x [basic.lookup.argdep]p3:
2843     //     -- a block-scope function declaration that is not a
2844     //        using-declaration
2845     // NOTE: we also trigger this for function templates (in fact, we
2846     // don't check the decl type at all, since all other decl types
2847     // turn off ADL anyway).
2848     if (isa<UsingShadowDecl>(D))
2849       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2850     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2851       return false;
2852 
2853     // C++0x [basic.lookup.argdep]p3:
2854     //     -- a declaration that is neither a function or a function
2855     //        template
2856     // And also for builtin functions.
2857     if (isa<FunctionDecl>(D)) {
2858       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2859 
2860       // But also builtin functions.
2861       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2862         return false;
2863     } else if (!isa<FunctionTemplateDecl>(D))
2864       return false;
2865   }
2866 
2867   return true;
2868 }
2869 
2870 
2871 /// Diagnoses obvious problems with the use of the given declaration
2872 /// as an expression.  This is only actually called for lookups that
2873 /// were not overloaded, and it doesn't promise that the declaration
2874 /// will in fact be used.
2875 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2876   if (D->isInvalidDecl())
2877     return true;
2878 
2879   if (isa<TypedefNameDecl>(D)) {
2880     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2881     return true;
2882   }
2883 
2884   if (isa<ObjCInterfaceDecl>(D)) {
2885     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2886     return true;
2887   }
2888 
2889   if (isa<NamespaceDecl>(D)) {
2890     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2891     return true;
2892   }
2893 
2894   return false;
2895 }
2896 
2897 // Certain multiversion types should be treated as overloaded even when there is
2898 // only one result.
2899 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2900   assert(R.isSingleResult() && "Expected only a single result");
2901   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2902   return FD &&
2903          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2904 }
2905 
2906 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2907                                           LookupResult &R, bool NeedsADL,
2908                                           bool AcceptInvalidDecl) {
2909   // If this is a single, fully-resolved result and we don't need ADL,
2910   // just build an ordinary singleton decl ref.
2911   if (!NeedsADL && R.isSingleResult() &&
2912       !R.getAsSingle<FunctionTemplateDecl>() &&
2913       !ShouldLookupResultBeMultiVersionOverload(R))
2914     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2915                                     R.getRepresentativeDecl(), nullptr,
2916                                     AcceptInvalidDecl);
2917 
2918   // We only need to check the declaration if there's exactly one
2919   // result, because in the overloaded case the results can only be
2920   // functions and function templates.
2921   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2922       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2923     return ExprError();
2924 
2925   // Otherwise, just build an unresolved lookup expression.  Suppress
2926   // any lookup-related diagnostics; we'll hash these out later, when
2927   // we've picked a target.
2928   R.suppressDiagnostics();
2929 
2930   UnresolvedLookupExpr *ULE
2931     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2932                                    SS.getWithLocInContext(Context),
2933                                    R.getLookupNameInfo(),
2934                                    NeedsADL, R.isOverloadedResult(),
2935                                    R.begin(), R.end());
2936 
2937   return ULE;
2938 }
2939 
2940 static void
2941 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2942                                    ValueDecl *var, DeclContext *DC);
2943 
2944 /// Complete semantic analysis for a reference to the given declaration.
2945 ExprResult Sema::BuildDeclarationNameExpr(
2946     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2947     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2948     bool AcceptInvalidDecl) {
2949   assert(D && "Cannot refer to a NULL declaration");
2950   assert(!isa<FunctionTemplateDecl>(D) &&
2951          "Cannot refer unambiguously to a function template");
2952 
2953   SourceLocation Loc = NameInfo.getLoc();
2954   if (CheckDeclInExpr(*this, Loc, D))
2955     return ExprError();
2956 
2957   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2958     // Specifically diagnose references to class templates that are missing
2959     // a template argument list.
2960     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2961     return ExprError();
2962   }
2963 
2964   // Make sure that we're referring to a value.
2965   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2966   if (!VD) {
2967     Diag(Loc, diag::err_ref_non_value)
2968       << D << SS.getRange();
2969     Diag(D->getLocation(), diag::note_declared_at);
2970     return ExprError();
2971   }
2972 
2973   // Check whether this declaration can be used. Note that we suppress
2974   // this check when we're going to perform argument-dependent lookup
2975   // on this function name, because this might not be the function
2976   // that overload resolution actually selects.
2977   if (DiagnoseUseOfDecl(VD, Loc))
2978     return ExprError();
2979 
2980   // Only create DeclRefExpr's for valid Decl's.
2981   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2982     return ExprError();
2983 
2984   // Handle members of anonymous structs and unions.  If we got here,
2985   // and the reference is to a class member indirect field, then this
2986   // must be the subject of a pointer-to-member expression.
2987   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2988     if (!indirectField->isCXXClassMember())
2989       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2990                                                       indirectField);
2991 
2992   {
2993     QualType type = VD->getType();
2994     if (type.isNull())
2995       return ExprError();
2996     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2997       // C++ [except.spec]p17:
2998       //   An exception-specification is considered to be needed when:
2999       //   - in an expression, the function is the unique lookup result or
3000       //     the selected member of a set of overloaded functions.
3001       ResolveExceptionSpec(Loc, FPT);
3002       type = VD->getType();
3003     }
3004     ExprValueKind valueKind = VK_RValue;
3005 
3006     switch (D->getKind()) {
3007     // Ignore all the non-ValueDecl kinds.
3008 #define ABSTRACT_DECL(kind)
3009 #define VALUE(type, base)
3010 #define DECL(type, base) \
3011     case Decl::type:
3012 #include "clang/AST/DeclNodes.inc"
3013       llvm_unreachable("invalid value decl kind");
3014 
3015     // These shouldn't make it here.
3016     case Decl::ObjCAtDefsField:
3017       llvm_unreachable("forming non-member reference to ivar?");
3018 
3019     // Enum constants are always r-values and never references.
3020     // Unresolved using declarations are dependent.
3021     case Decl::EnumConstant:
3022     case Decl::UnresolvedUsingValue:
3023     case Decl::OMPDeclareReduction:
3024     case Decl::OMPDeclareMapper:
3025       valueKind = VK_RValue;
3026       break;
3027 
3028     // Fields and indirect fields that got here must be for
3029     // pointer-to-member expressions; we just call them l-values for
3030     // internal consistency, because this subexpression doesn't really
3031     // exist in the high-level semantics.
3032     case Decl::Field:
3033     case Decl::IndirectField:
3034     case Decl::ObjCIvar:
3035       assert(getLangOpts().CPlusPlus &&
3036              "building reference to field in C?");
3037 
3038       // These can't have reference type in well-formed programs, but
3039       // for internal consistency we do this anyway.
3040       type = type.getNonReferenceType();
3041       valueKind = VK_LValue;
3042       break;
3043 
3044     // Non-type template parameters are either l-values or r-values
3045     // depending on the type.
3046     case Decl::NonTypeTemplateParm: {
3047       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3048         type = reftype->getPointeeType();
3049         valueKind = VK_LValue; // even if the parameter is an r-value reference
3050         break;
3051       }
3052 
3053       // For non-references, we need to strip qualifiers just in case
3054       // the template parameter was declared as 'const int' or whatever.
3055       valueKind = VK_RValue;
3056       type = type.getUnqualifiedType();
3057       break;
3058     }
3059 
3060     case Decl::Var:
3061     case Decl::VarTemplateSpecialization:
3062     case Decl::VarTemplatePartialSpecialization:
3063     case Decl::Decomposition:
3064     case Decl::OMPCapturedExpr:
3065       // In C, "extern void blah;" is valid and is an r-value.
3066       if (!getLangOpts().CPlusPlus &&
3067           !type.hasQualifiers() &&
3068           type->isVoidType()) {
3069         valueKind = VK_RValue;
3070         break;
3071       }
3072       LLVM_FALLTHROUGH;
3073 
3074     case Decl::ImplicitParam:
3075     case Decl::ParmVar: {
3076       // These are always l-values.
3077       valueKind = VK_LValue;
3078       type = type.getNonReferenceType();
3079 
3080       // FIXME: Does the addition of const really only apply in
3081       // potentially-evaluated contexts? Since the variable isn't actually
3082       // captured in an unevaluated context, it seems that the answer is no.
3083       if (!isUnevaluatedContext()) {
3084         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3085         if (!CapturedType.isNull())
3086           type = CapturedType;
3087       }
3088 
3089       break;
3090     }
3091 
3092     case Decl::Binding: {
3093       // These are always lvalues.
3094       valueKind = VK_LValue;
3095       type = type.getNonReferenceType();
3096       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3097       // decides how that's supposed to work.
3098       auto *BD = cast<BindingDecl>(VD);
3099       if (BD->getDeclContext() != CurContext) {
3100         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3101         if (DD && DD->hasLocalStorage())
3102           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3103       }
3104       break;
3105     }
3106 
3107     case Decl::Function: {
3108       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3109         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3110           type = Context.BuiltinFnTy;
3111           valueKind = VK_RValue;
3112           break;
3113         }
3114       }
3115 
3116       const FunctionType *fty = type->castAs<FunctionType>();
3117 
3118       // If we're referring to a function with an __unknown_anytype
3119       // result type, make the entire expression __unknown_anytype.
3120       if (fty->getReturnType() == Context.UnknownAnyTy) {
3121         type = Context.UnknownAnyTy;
3122         valueKind = VK_RValue;
3123         break;
3124       }
3125 
3126       // Functions are l-values in C++.
3127       if (getLangOpts().CPlusPlus) {
3128         valueKind = VK_LValue;
3129         break;
3130       }
3131 
3132       // C99 DR 316 says that, if a function type comes from a
3133       // function definition (without a prototype), that type is only
3134       // used for checking compatibility. Therefore, when referencing
3135       // the function, we pretend that we don't have the full function
3136       // type.
3137       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3138           isa<FunctionProtoType>(fty))
3139         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3140                                               fty->getExtInfo());
3141 
3142       // Functions are r-values in C.
3143       valueKind = VK_RValue;
3144       break;
3145     }
3146 
3147     case Decl::CXXDeductionGuide:
3148       llvm_unreachable("building reference to deduction guide");
3149 
3150     case Decl::MSProperty:
3151       valueKind = VK_LValue;
3152       break;
3153 
3154     case Decl::CXXMethod:
3155       // If we're referring to a method with an __unknown_anytype
3156       // result type, make the entire expression __unknown_anytype.
3157       // This should only be possible with a type written directly.
3158       if (const FunctionProtoType *proto
3159             = dyn_cast<FunctionProtoType>(VD->getType()))
3160         if (proto->getReturnType() == Context.UnknownAnyTy) {
3161           type = Context.UnknownAnyTy;
3162           valueKind = VK_RValue;
3163           break;
3164         }
3165 
3166       // C++ methods are l-values if static, r-values if non-static.
3167       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3168         valueKind = VK_LValue;
3169         break;
3170       }
3171       LLVM_FALLTHROUGH;
3172 
3173     case Decl::CXXConversion:
3174     case Decl::CXXDestructor:
3175     case Decl::CXXConstructor:
3176       valueKind = VK_RValue;
3177       break;
3178     }
3179 
3180     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3181                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3182                             TemplateArgs);
3183   }
3184 }
3185 
3186 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3187                                     SmallString<32> &Target) {
3188   Target.resize(CharByteWidth * (Source.size() + 1));
3189   char *ResultPtr = &Target[0];
3190   const llvm::UTF8 *ErrorPtr;
3191   bool success =
3192       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3193   (void)success;
3194   assert(success);
3195   Target.resize(ResultPtr - &Target[0]);
3196 }
3197 
3198 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3199                                      PredefinedExpr::IdentKind IK) {
3200   // Pick the current block, lambda, captured statement or function.
3201   Decl *currentDecl = nullptr;
3202   if (const BlockScopeInfo *BSI = getCurBlock())
3203     currentDecl = BSI->TheDecl;
3204   else if (const LambdaScopeInfo *LSI = getCurLambda())
3205     currentDecl = LSI->CallOperator;
3206   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3207     currentDecl = CSI->TheCapturedDecl;
3208   else
3209     currentDecl = getCurFunctionOrMethodDecl();
3210 
3211   if (!currentDecl) {
3212     Diag(Loc, diag::ext_predef_outside_function);
3213     currentDecl = Context.getTranslationUnitDecl();
3214   }
3215 
3216   QualType ResTy;
3217   StringLiteral *SL = nullptr;
3218   if (cast<DeclContext>(currentDecl)->isDependentContext())
3219     ResTy = Context.DependentTy;
3220   else {
3221     // Pre-defined identifiers are of type char[x], where x is the length of
3222     // the string.
3223     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3224     unsigned Length = Str.length();
3225 
3226     llvm::APInt LengthI(32, Length + 1);
3227     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3228       ResTy =
3229           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3230       SmallString<32> RawChars;
3231       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3232                               Str, RawChars);
3233       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3234                                            ArrayType::Normal,
3235                                            /*IndexTypeQuals*/ 0);
3236       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3237                                  /*Pascal*/ false, ResTy, Loc);
3238     } else {
3239       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3240       ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3241                                            ArrayType::Normal,
3242                                            /*IndexTypeQuals*/ 0);
3243       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3244                                  /*Pascal*/ false, ResTy, Loc);
3245     }
3246   }
3247 
3248   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3249 }
3250 
3251 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3252   PredefinedExpr::IdentKind IK;
3253 
3254   switch (Kind) {
3255   default: llvm_unreachable("Unknown simple primary expr!");
3256   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3257   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3258   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3259   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3260   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3261   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3262   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3263   }
3264 
3265   return BuildPredefinedExpr(Loc, IK);
3266 }
3267 
3268 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3269   SmallString<16> CharBuffer;
3270   bool Invalid = false;
3271   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3272   if (Invalid)
3273     return ExprError();
3274 
3275   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3276                             PP, Tok.getKind());
3277   if (Literal.hadError())
3278     return ExprError();
3279 
3280   QualType Ty;
3281   if (Literal.isWide())
3282     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3283   else if (Literal.isUTF8() && getLangOpts().Char8)
3284     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3285   else if (Literal.isUTF16())
3286     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3287   else if (Literal.isUTF32())
3288     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3289   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3290     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3291   else
3292     Ty = Context.CharTy;  // 'x' -> char in C++
3293 
3294   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3295   if (Literal.isWide())
3296     Kind = CharacterLiteral::Wide;
3297   else if (Literal.isUTF16())
3298     Kind = CharacterLiteral::UTF16;
3299   else if (Literal.isUTF32())
3300     Kind = CharacterLiteral::UTF32;
3301   else if (Literal.isUTF8())
3302     Kind = CharacterLiteral::UTF8;
3303 
3304   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3305                                              Tok.getLocation());
3306 
3307   if (Literal.getUDSuffix().empty())
3308     return Lit;
3309 
3310   // We're building a user-defined literal.
3311   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3312   SourceLocation UDSuffixLoc =
3313     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3314 
3315   // Make sure we're allowed user-defined literals here.
3316   if (!UDLScope)
3317     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3318 
3319   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3320   //   operator "" X (ch)
3321   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3322                                         Lit, Tok.getLocation());
3323 }
3324 
3325 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3326   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3327   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3328                                 Context.IntTy, Loc);
3329 }
3330 
3331 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3332                                   QualType Ty, SourceLocation Loc) {
3333   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3334 
3335   using llvm::APFloat;
3336   APFloat Val(Format);
3337 
3338   APFloat::opStatus result = Literal.GetFloatValue(Val);
3339 
3340   // Overflow is always an error, but underflow is only an error if
3341   // we underflowed to zero (APFloat reports denormals as underflow).
3342   if ((result & APFloat::opOverflow) ||
3343       ((result & APFloat::opUnderflow) && Val.isZero())) {
3344     unsigned diagnostic;
3345     SmallString<20> buffer;
3346     if (result & APFloat::opOverflow) {
3347       diagnostic = diag::warn_float_overflow;
3348       APFloat::getLargest(Format).toString(buffer);
3349     } else {
3350       diagnostic = diag::warn_float_underflow;
3351       APFloat::getSmallest(Format).toString(buffer);
3352     }
3353 
3354     S.Diag(Loc, diagnostic)
3355       << Ty
3356       << StringRef(buffer.data(), buffer.size());
3357   }
3358 
3359   bool isExact = (result == APFloat::opOK);
3360   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3361 }
3362 
3363 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3364   assert(E && "Invalid expression");
3365 
3366   if (E->isValueDependent())
3367     return false;
3368 
3369   QualType QT = E->getType();
3370   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3371     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3372     return true;
3373   }
3374 
3375   llvm::APSInt ValueAPS;
3376   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3377 
3378   if (R.isInvalid())
3379     return true;
3380 
3381   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3382   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3383     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3384         << ValueAPS.toString(10) << ValueIsPositive;
3385     return true;
3386   }
3387 
3388   return false;
3389 }
3390 
3391 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3392   // Fast path for a single digit (which is quite common).  A single digit
3393   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3394   if (Tok.getLength() == 1) {
3395     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3396     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3397   }
3398 
3399   SmallString<128> SpellingBuffer;
3400   // NumericLiteralParser wants to overread by one character.  Add padding to
3401   // the buffer in case the token is copied to the buffer.  If getSpelling()
3402   // returns a StringRef to the memory buffer, it should have a null char at
3403   // the EOF, so it is also safe.
3404   SpellingBuffer.resize(Tok.getLength() + 1);
3405 
3406   // Get the spelling of the token, which eliminates trigraphs, etc.
3407   bool Invalid = false;
3408   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3409   if (Invalid)
3410     return ExprError();
3411 
3412   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3413   if (Literal.hadError)
3414     return ExprError();
3415 
3416   if (Literal.hasUDSuffix()) {
3417     // We're building a user-defined literal.
3418     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3419     SourceLocation UDSuffixLoc =
3420       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3421 
3422     // Make sure we're allowed user-defined literals here.
3423     if (!UDLScope)
3424       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3425 
3426     QualType CookedTy;
3427     if (Literal.isFloatingLiteral()) {
3428       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3429       // long double, the literal is treated as a call of the form
3430       //   operator "" X (f L)
3431       CookedTy = Context.LongDoubleTy;
3432     } else {
3433       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3434       // unsigned long long, the literal is treated as a call of the form
3435       //   operator "" X (n ULL)
3436       CookedTy = Context.UnsignedLongLongTy;
3437     }
3438 
3439     DeclarationName OpName =
3440       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3441     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3442     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3443 
3444     SourceLocation TokLoc = Tok.getLocation();
3445 
3446     // Perform literal operator lookup to determine if we're building a raw
3447     // literal or a cooked one.
3448     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3449     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3450                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3451                                   /*AllowStringTemplate*/ false,
3452                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3453     case LOLR_ErrorNoDiagnostic:
3454       // Lookup failure for imaginary constants isn't fatal, there's still the
3455       // GNU extension producing _Complex types.
3456       break;
3457     case LOLR_Error:
3458       return ExprError();
3459     case LOLR_Cooked: {
3460       Expr *Lit;
3461       if (Literal.isFloatingLiteral()) {
3462         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3463       } else {
3464         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3465         if (Literal.GetIntegerValue(ResultVal))
3466           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3467               << /* Unsigned */ 1;
3468         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3469                                      Tok.getLocation());
3470       }
3471       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3472     }
3473 
3474     case LOLR_Raw: {
3475       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3476       // literal is treated as a call of the form
3477       //   operator "" X ("n")
3478       unsigned Length = Literal.getUDSuffixOffset();
3479       QualType StrTy = Context.getConstantArrayType(
3480           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3481           llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3482       Expr *Lit = StringLiteral::Create(
3483           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3484           /*Pascal*/false, StrTy, &TokLoc, 1);
3485       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3486     }
3487 
3488     case LOLR_Template: {
3489       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3490       // template), L is treated as a call fo the form
3491       //   operator "" X <'c1', 'c2', ... 'ck'>()
3492       // where n is the source character sequence c1 c2 ... ck.
3493       TemplateArgumentListInfo ExplicitArgs;
3494       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3495       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3496       llvm::APSInt Value(CharBits, CharIsUnsigned);
3497       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3498         Value = TokSpelling[I];
3499         TemplateArgument Arg(Context, Value, Context.CharTy);
3500         TemplateArgumentLocInfo ArgInfo;
3501         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3502       }
3503       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3504                                       &ExplicitArgs);
3505     }
3506     case LOLR_StringTemplate:
3507       llvm_unreachable("unexpected literal operator lookup result");
3508     }
3509   }
3510 
3511   Expr *Res;
3512 
3513   if (Literal.isFixedPointLiteral()) {
3514     QualType Ty;
3515 
3516     if (Literal.isAccum) {
3517       if (Literal.isHalf) {
3518         Ty = Context.ShortAccumTy;
3519       } else if (Literal.isLong) {
3520         Ty = Context.LongAccumTy;
3521       } else {
3522         Ty = Context.AccumTy;
3523       }
3524     } else if (Literal.isFract) {
3525       if (Literal.isHalf) {
3526         Ty = Context.ShortFractTy;
3527       } else if (Literal.isLong) {
3528         Ty = Context.LongFractTy;
3529       } else {
3530         Ty = Context.FractTy;
3531       }
3532     }
3533 
3534     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3535 
3536     bool isSigned = !Literal.isUnsigned;
3537     unsigned scale = Context.getFixedPointScale(Ty);
3538     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3539 
3540     llvm::APInt Val(bit_width, 0, isSigned);
3541     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3542     bool ValIsZero = Val.isNullValue() && !Overflowed;
3543 
3544     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3545     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3546       // Clause 6.4.4 - The value of a constant shall be in the range of
3547       // representable values for its type, with exception for constants of a
3548       // fract type with a value of exactly 1; such a constant shall denote
3549       // the maximal value for the type.
3550       --Val;
3551     else if (Val.ugt(MaxVal) || Overflowed)
3552       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3553 
3554     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3555                                               Tok.getLocation(), scale);
3556   } else if (Literal.isFloatingLiteral()) {
3557     QualType Ty;
3558     if (Literal.isHalf){
3559       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3560         Ty = Context.HalfTy;
3561       else {
3562         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3563         return ExprError();
3564       }
3565     } else if (Literal.isFloat)
3566       Ty = Context.FloatTy;
3567     else if (Literal.isLong)
3568       Ty = Context.LongDoubleTy;
3569     else if (Literal.isFloat16)
3570       Ty = Context.Float16Ty;
3571     else if (Literal.isFloat128)
3572       Ty = Context.Float128Ty;
3573     else
3574       Ty = Context.DoubleTy;
3575 
3576     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3577 
3578     if (Ty == Context.DoubleTy) {
3579       if (getLangOpts().SinglePrecisionConstants) {
3580         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3581         if (BTy->getKind() != BuiltinType::Float) {
3582           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3583         }
3584       } else if (getLangOpts().OpenCL &&
3585                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3586         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3587         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3588         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3589       }
3590     }
3591   } else if (!Literal.isIntegerLiteral()) {
3592     return ExprError();
3593   } else {
3594     QualType Ty;
3595 
3596     // 'long long' is a C99 or C++11 feature.
3597     if (!getLangOpts().C99 && Literal.isLongLong) {
3598       if (getLangOpts().CPlusPlus)
3599         Diag(Tok.getLocation(),
3600              getLangOpts().CPlusPlus11 ?
3601              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3602       else
3603         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3604     }
3605 
3606     // Get the value in the widest-possible width.
3607     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3608     llvm::APInt ResultVal(MaxWidth, 0);
3609 
3610     if (Literal.GetIntegerValue(ResultVal)) {
3611       // If this value didn't fit into uintmax_t, error and force to ull.
3612       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3613           << /* Unsigned */ 1;
3614       Ty = Context.UnsignedLongLongTy;
3615       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3616              "long long is not intmax_t?");
3617     } else {
3618       // If this value fits into a ULL, try to figure out what else it fits into
3619       // according to the rules of C99 6.4.4.1p5.
3620 
3621       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3622       // be an unsigned int.
3623       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3624 
3625       // Check from smallest to largest, picking the smallest type we can.
3626       unsigned Width = 0;
3627 
3628       // Microsoft specific integer suffixes are explicitly sized.
3629       if (Literal.MicrosoftInteger) {
3630         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3631           Width = 8;
3632           Ty = Context.CharTy;
3633         } else {
3634           Width = Literal.MicrosoftInteger;
3635           Ty = Context.getIntTypeForBitwidth(Width,
3636                                              /*Signed=*/!Literal.isUnsigned);
3637         }
3638       }
3639 
3640       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3641         // Are int/unsigned possibilities?
3642         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3643 
3644         // Does it fit in a unsigned int?
3645         if (ResultVal.isIntN(IntSize)) {
3646           // Does it fit in a signed int?
3647           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3648             Ty = Context.IntTy;
3649           else if (AllowUnsigned)
3650             Ty = Context.UnsignedIntTy;
3651           Width = IntSize;
3652         }
3653       }
3654 
3655       // Are long/unsigned long possibilities?
3656       if (Ty.isNull() && !Literal.isLongLong) {
3657         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3658 
3659         // Does it fit in a unsigned long?
3660         if (ResultVal.isIntN(LongSize)) {
3661           // Does it fit in a signed long?
3662           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3663             Ty = Context.LongTy;
3664           else if (AllowUnsigned)
3665             Ty = Context.UnsignedLongTy;
3666           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3667           // is compatible.
3668           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3669             const unsigned LongLongSize =
3670                 Context.getTargetInfo().getLongLongWidth();
3671             Diag(Tok.getLocation(),
3672                  getLangOpts().CPlusPlus
3673                      ? Literal.isLong
3674                            ? diag::warn_old_implicitly_unsigned_long_cxx
3675                            : /*C++98 UB*/ diag::
3676                                  ext_old_implicitly_unsigned_long_cxx
3677                      : diag::warn_old_implicitly_unsigned_long)
3678                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3679                                             : /*will be ill-formed*/ 1);
3680             Ty = Context.UnsignedLongTy;
3681           }
3682           Width = LongSize;
3683         }
3684       }
3685 
3686       // Check long long if needed.
3687       if (Ty.isNull()) {
3688         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3689 
3690         // Does it fit in a unsigned long long?
3691         if (ResultVal.isIntN(LongLongSize)) {
3692           // Does it fit in a signed long long?
3693           // To be compatible with MSVC, hex integer literals ending with the
3694           // LL or i64 suffix are always signed in Microsoft mode.
3695           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3696               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3697             Ty = Context.LongLongTy;
3698           else if (AllowUnsigned)
3699             Ty = Context.UnsignedLongLongTy;
3700           Width = LongLongSize;
3701         }
3702       }
3703 
3704       // If we still couldn't decide a type, we probably have something that
3705       // does not fit in a signed long long, but has no U suffix.
3706       if (Ty.isNull()) {
3707         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3708         Ty = Context.UnsignedLongLongTy;
3709         Width = Context.getTargetInfo().getLongLongWidth();
3710       }
3711 
3712       if (ResultVal.getBitWidth() != Width)
3713         ResultVal = ResultVal.trunc(Width);
3714     }
3715     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3716   }
3717 
3718   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3719   if (Literal.isImaginary) {
3720     Res = new (Context) ImaginaryLiteral(Res,
3721                                         Context.getComplexType(Res->getType()));
3722 
3723     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3724   }
3725   return Res;
3726 }
3727 
3728 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3729   assert(E && "ActOnParenExpr() missing expr");
3730   return new (Context) ParenExpr(L, R, E);
3731 }
3732 
3733 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3734                                          SourceLocation Loc,
3735                                          SourceRange ArgRange) {
3736   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3737   // scalar or vector data type argument..."
3738   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3739   // type (C99 6.2.5p18) or void.
3740   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3741     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3742       << T << ArgRange;
3743     return true;
3744   }
3745 
3746   assert((T->isVoidType() || !T->isIncompleteType()) &&
3747          "Scalar types should always be complete");
3748   return false;
3749 }
3750 
3751 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3752                                            SourceLocation Loc,
3753                                            SourceRange ArgRange,
3754                                            UnaryExprOrTypeTrait TraitKind) {
3755   // Invalid types must be hard errors for SFINAE in C++.
3756   if (S.LangOpts.CPlusPlus)
3757     return true;
3758 
3759   // C99 6.5.3.4p1:
3760   if (T->isFunctionType() &&
3761       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3762        TraitKind == UETT_PreferredAlignOf)) {
3763     // sizeof(function)/alignof(function) is allowed as an extension.
3764     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3765       << TraitKind << ArgRange;
3766     return false;
3767   }
3768 
3769   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3770   // this is an error (OpenCL v1.1 s6.3.k)
3771   if (T->isVoidType()) {
3772     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3773                                         : diag::ext_sizeof_alignof_void_type;
3774     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3775     return false;
3776   }
3777 
3778   return true;
3779 }
3780 
3781 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3782                                              SourceLocation Loc,
3783                                              SourceRange ArgRange,
3784                                              UnaryExprOrTypeTrait TraitKind) {
3785   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3786   // runtime doesn't allow it.
3787   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3788     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3789       << T << (TraitKind == UETT_SizeOf)
3790       << ArgRange;
3791     return true;
3792   }
3793 
3794   return false;
3795 }
3796 
3797 /// Check whether E is a pointer from a decayed array type (the decayed
3798 /// pointer type is equal to T) and emit a warning if it is.
3799 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3800                                      Expr *E) {
3801   // Don't warn if the operation changed the type.
3802   if (T != E->getType())
3803     return;
3804 
3805   // Now look for array decays.
3806   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3807   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3808     return;
3809 
3810   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3811                                              << ICE->getType()
3812                                              << ICE->getSubExpr()->getType();
3813 }
3814 
3815 /// Check the constraints on expression operands to unary type expression
3816 /// and type traits.
3817 ///
3818 /// Completes any types necessary and validates the constraints on the operand
3819 /// expression. The logic mostly mirrors the type-based overload, but may modify
3820 /// the expression as it completes the type for that expression through template
3821 /// instantiation, etc.
3822 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3823                                             UnaryExprOrTypeTrait ExprKind) {
3824   QualType ExprTy = E->getType();
3825   assert(!ExprTy->isReferenceType());
3826 
3827   bool IsUnevaluatedOperand =
3828       (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3829        ExprKind == UETT_PreferredAlignOf);
3830   if (IsUnevaluatedOperand) {
3831     ExprResult Result = CheckUnevaluatedOperand(E);
3832     if (Result.isInvalid())
3833       return true;
3834     E = Result.get();
3835   }
3836 
3837   if (ExprKind == UETT_VecStep)
3838     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3839                                         E->getSourceRange());
3840 
3841   // Whitelist some types as extensions
3842   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3843                                       E->getSourceRange(), ExprKind))
3844     return false;
3845 
3846   // 'alignof' applied to an expression only requires the base element type of
3847   // the expression to be complete. 'sizeof' requires the expression's type to
3848   // be complete (and will attempt to complete it if it's an array of unknown
3849   // bound).
3850   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3851     if (RequireCompleteType(E->getExprLoc(),
3852                             Context.getBaseElementType(E->getType()),
3853                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3854                             E->getSourceRange()))
3855       return true;
3856   } else {
3857     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3858                                 ExprKind, E->getSourceRange()))
3859       return true;
3860   }
3861 
3862   // Completing the expression's type may have changed it.
3863   ExprTy = E->getType();
3864   assert(!ExprTy->isReferenceType());
3865 
3866   if (ExprTy->isFunctionType()) {
3867     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3868       << ExprKind << E->getSourceRange();
3869     return true;
3870   }
3871 
3872   // The operand for sizeof and alignof is in an unevaluated expression context,
3873   // so side effects could result in unintended consequences.
3874   if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
3875       E->HasSideEffects(Context, false))
3876     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3877 
3878   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3879                                        E->getSourceRange(), ExprKind))
3880     return true;
3881 
3882   if (ExprKind == UETT_SizeOf) {
3883     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3884       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3885         QualType OType = PVD->getOriginalType();
3886         QualType Type = PVD->getType();
3887         if (Type->isPointerType() && OType->isArrayType()) {
3888           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3889             << Type << OType;
3890           Diag(PVD->getLocation(), diag::note_declared_at);
3891         }
3892       }
3893     }
3894 
3895     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3896     // decays into a pointer and returns an unintended result. This is most
3897     // likely a typo for "sizeof(array) op x".
3898     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3899       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3900                                BO->getLHS());
3901       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3902                                BO->getRHS());
3903     }
3904   }
3905 
3906   return false;
3907 }
3908 
3909 /// Check the constraints on operands to unary expression and type
3910 /// traits.
3911 ///
3912 /// This will complete any types necessary, and validate the various constraints
3913 /// on those operands.
3914 ///
3915 /// The UsualUnaryConversions() function is *not* called by this routine.
3916 /// C99 6.3.2.1p[2-4] all state:
3917 ///   Except when it is the operand of the sizeof operator ...
3918 ///
3919 /// C++ [expr.sizeof]p4
3920 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3921 ///   standard conversions are not applied to the operand of sizeof.
3922 ///
3923 /// This policy is followed for all of the unary trait expressions.
3924 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3925                                             SourceLocation OpLoc,
3926                                             SourceRange ExprRange,
3927                                             UnaryExprOrTypeTrait ExprKind) {
3928   if (ExprType->isDependentType())
3929     return false;
3930 
3931   // C++ [expr.sizeof]p2:
3932   //     When applied to a reference or a reference type, the result
3933   //     is the size of the referenced type.
3934   // C++11 [expr.alignof]p3:
3935   //     When alignof is applied to a reference type, the result
3936   //     shall be the alignment of the referenced type.
3937   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3938     ExprType = Ref->getPointeeType();
3939 
3940   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3941   //   When alignof or _Alignof is applied to an array type, the result
3942   //   is the alignment of the element type.
3943   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3944       ExprKind == UETT_OpenMPRequiredSimdAlign)
3945     ExprType = Context.getBaseElementType(ExprType);
3946 
3947   if (ExprKind == UETT_VecStep)
3948     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3949 
3950   // Whitelist some types as extensions
3951   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3952                                       ExprKind))
3953     return false;
3954 
3955   if (RequireCompleteType(OpLoc, ExprType,
3956                           diag::err_sizeof_alignof_incomplete_type,
3957                           ExprKind, ExprRange))
3958     return true;
3959 
3960   if (ExprType->isFunctionType()) {
3961     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3962       << ExprKind << ExprRange;
3963     return true;
3964   }
3965 
3966   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3967                                        ExprKind))
3968     return true;
3969 
3970   return false;
3971 }
3972 
3973 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3974   // Cannot know anything else if the expression is dependent.
3975   if (E->isTypeDependent())
3976     return false;
3977 
3978   if (E->getObjectKind() == OK_BitField) {
3979     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3980        << 1 << E->getSourceRange();
3981     return true;
3982   }
3983 
3984   ValueDecl *D = nullptr;
3985   Expr *Inner = E->IgnoreParens();
3986   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
3987     D = DRE->getDecl();
3988   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
3989     D = ME->getMemberDecl();
3990   }
3991 
3992   // If it's a field, require the containing struct to have a
3993   // complete definition so that we can compute the layout.
3994   //
3995   // This can happen in C++11 onwards, either by naming the member
3996   // in a way that is not transformed into a member access expression
3997   // (in an unevaluated operand, for instance), or by naming the member
3998   // in a trailing-return-type.
3999   //
4000   // For the record, since __alignof__ on expressions is a GCC
4001   // extension, GCC seems to permit this but always gives the
4002   // nonsensical answer 0.
4003   //
4004   // We don't really need the layout here --- we could instead just
4005   // directly check for all the appropriate alignment-lowing
4006   // attributes --- but that would require duplicating a lot of
4007   // logic that just isn't worth duplicating for such a marginal
4008   // use-case.
4009   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4010     // Fast path this check, since we at least know the record has a
4011     // definition if we can find a member of it.
4012     if (!FD->getParent()->isCompleteDefinition()) {
4013       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4014         << E->getSourceRange();
4015       return true;
4016     }
4017 
4018     // Otherwise, if it's a field, and the field doesn't have
4019     // reference type, then it must have a complete type (or be a
4020     // flexible array member, which we explicitly want to
4021     // white-list anyway), which makes the following checks trivial.
4022     if (!FD->getType()->isReferenceType())
4023       return false;
4024   }
4025 
4026   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4027 }
4028 
4029 bool Sema::CheckVecStepExpr(Expr *E) {
4030   E = E->IgnoreParens();
4031 
4032   // Cannot know anything else if the expression is dependent.
4033   if (E->isTypeDependent())
4034     return false;
4035 
4036   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4037 }
4038 
4039 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4040                                         CapturingScopeInfo *CSI) {
4041   assert(T->isVariablyModifiedType());
4042   assert(CSI != nullptr);
4043 
4044   // We're going to walk down into the type and look for VLA expressions.
4045   do {
4046     const Type *Ty = T.getTypePtr();
4047     switch (Ty->getTypeClass()) {
4048 #define TYPE(Class, Base)
4049 #define ABSTRACT_TYPE(Class, Base)
4050 #define NON_CANONICAL_TYPE(Class, Base)
4051 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4052 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4053 #include "clang/AST/TypeNodes.inc"
4054       T = QualType();
4055       break;
4056     // These types are never variably-modified.
4057     case Type::Builtin:
4058     case Type::Complex:
4059     case Type::Vector:
4060     case Type::ExtVector:
4061     case Type::Record:
4062     case Type::Enum:
4063     case Type::Elaborated:
4064     case Type::TemplateSpecialization:
4065     case Type::ObjCObject:
4066     case Type::ObjCInterface:
4067     case Type::ObjCObjectPointer:
4068     case Type::ObjCTypeParam:
4069     case Type::Pipe:
4070       llvm_unreachable("type class is never variably-modified!");
4071     case Type::Adjusted:
4072       T = cast<AdjustedType>(Ty)->getOriginalType();
4073       break;
4074     case Type::Decayed:
4075       T = cast<DecayedType>(Ty)->getPointeeType();
4076       break;
4077     case Type::Pointer:
4078       T = cast<PointerType>(Ty)->getPointeeType();
4079       break;
4080     case Type::BlockPointer:
4081       T = cast<BlockPointerType>(Ty)->getPointeeType();
4082       break;
4083     case Type::LValueReference:
4084     case Type::RValueReference:
4085       T = cast<ReferenceType>(Ty)->getPointeeType();
4086       break;
4087     case Type::MemberPointer:
4088       T = cast<MemberPointerType>(Ty)->getPointeeType();
4089       break;
4090     case Type::ConstantArray:
4091     case Type::IncompleteArray:
4092       // Losing element qualification here is fine.
4093       T = cast<ArrayType>(Ty)->getElementType();
4094       break;
4095     case Type::VariableArray: {
4096       // Losing element qualification here is fine.
4097       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4098 
4099       // Unknown size indication requires no size computation.
4100       // Otherwise, evaluate and record it.
4101       auto Size = VAT->getSizeExpr();
4102       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4103           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4104         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4105 
4106       T = VAT->getElementType();
4107       break;
4108     }
4109     case Type::FunctionProto:
4110     case Type::FunctionNoProto:
4111       T = cast<FunctionType>(Ty)->getReturnType();
4112       break;
4113     case Type::Paren:
4114     case Type::TypeOf:
4115     case Type::UnaryTransform:
4116     case Type::Attributed:
4117     case Type::SubstTemplateTypeParm:
4118     case Type::PackExpansion:
4119     case Type::MacroQualified:
4120       // Keep walking after single level desugaring.
4121       T = T.getSingleStepDesugaredType(Context);
4122       break;
4123     case Type::Typedef:
4124       T = cast<TypedefType>(Ty)->desugar();
4125       break;
4126     case Type::Decltype:
4127       T = cast<DecltypeType>(Ty)->desugar();
4128       break;
4129     case Type::Auto:
4130     case Type::DeducedTemplateSpecialization:
4131       T = cast<DeducedType>(Ty)->getDeducedType();
4132       break;
4133     case Type::TypeOfExpr:
4134       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4135       break;
4136     case Type::Atomic:
4137       T = cast<AtomicType>(Ty)->getValueType();
4138       break;
4139     }
4140   } while (!T.isNull() && T->isVariablyModifiedType());
4141 }
4142 
4143 /// Build a sizeof or alignof expression given a type operand.
4144 ExprResult
4145 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4146                                      SourceLocation OpLoc,
4147                                      UnaryExprOrTypeTrait ExprKind,
4148                                      SourceRange R) {
4149   if (!TInfo)
4150     return ExprError();
4151 
4152   QualType T = TInfo->getType();
4153 
4154   if (!T->isDependentType() &&
4155       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4156     return ExprError();
4157 
4158   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4159     if (auto *TT = T->getAs<TypedefType>()) {
4160       for (auto I = FunctionScopes.rbegin(),
4161                 E = std::prev(FunctionScopes.rend());
4162            I != E; ++I) {
4163         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4164         if (CSI == nullptr)
4165           break;
4166         DeclContext *DC = nullptr;
4167         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4168           DC = LSI->CallOperator;
4169         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4170           DC = CRSI->TheCapturedDecl;
4171         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4172           DC = BSI->TheDecl;
4173         if (DC) {
4174           if (DC->containsDecl(TT->getDecl()))
4175             break;
4176           captureVariablyModifiedType(Context, T, CSI);
4177         }
4178       }
4179     }
4180   }
4181 
4182   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4183   return new (Context) UnaryExprOrTypeTraitExpr(
4184       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4185 }
4186 
4187 /// Build a sizeof or alignof expression given an expression
4188 /// operand.
4189 ExprResult
4190 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4191                                      UnaryExprOrTypeTrait ExprKind) {
4192   ExprResult PE = CheckPlaceholderExpr(E);
4193   if (PE.isInvalid())
4194     return ExprError();
4195 
4196   E = PE.get();
4197 
4198   // Verify that the operand is valid.
4199   bool isInvalid = false;
4200   if (E->isTypeDependent()) {
4201     // Delay type-checking for type-dependent expressions.
4202   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4203     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4204   } else if (ExprKind == UETT_VecStep) {
4205     isInvalid = CheckVecStepExpr(E);
4206   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4207       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4208       isInvalid = true;
4209   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4210     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4211     isInvalid = true;
4212   } else {
4213     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4214   }
4215 
4216   if (isInvalid)
4217     return ExprError();
4218 
4219   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4220     PE = TransformToPotentiallyEvaluated(E);
4221     if (PE.isInvalid()) return ExprError();
4222     E = PE.get();
4223   }
4224 
4225   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4226   return new (Context) UnaryExprOrTypeTraitExpr(
4227       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4228 }
4229 
4230 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4231 /// expr and the same for @c alignof and @c __alignof
4232 /// Note that the ArgRange is invalid if isType is false.
4233 ExprResult
4234 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4235                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4236                                     void *TyOrEx, SourceRange ArgRange) {
4237   // If error parsing type, ignore.
4238   if (!TyOrEx) return ExprError();
4239 
4240   if (IsType) {
4241     TypeSourceInfo *TInfo;
4242     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4243     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4244   }
4245 
4246   Expr *ArgEx = (Expr *)TyOrEx;
4247   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4248   return Result;
4249 }
4250 
4251 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4252                                      bool IsReal) {
4253   if (V.get()->isTypeDependent())
4254     return S.Context.DependentTy;
4255 
4256   // _Real and _Imag are only l-values for normal l-values.
4257   if (V.get()->getObjectKind() != OK_Ordinary) {
4258     V = S.DefaultLvalueConversion(V.get());
4259     if (V.isInvalid())
4260       return QualType();
4261   }
4262 
4263   // These operators return the element type of a complex type.
4264   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4265     return CT->getElementType();
4266 
4267   // Otherwise they pass through real integer and floating point types here.
4268   if (V.get()->getType()->isArithmeticType())
4269     return V.get()->getType();
4270 
4271   // Test for placeholders.
4272   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4273   if (PR.isInvalid()) return QualType();
4274   if (PR.get() != V.get()) {
4275     V = PR;
4276     return CheckRealImagOperand(S, V, Loc, IsReal);
4277   }
4278 
4279   // Reject anything else.
4280   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4281     << (IsReal ? "__real" : "__imag");
4282   return QualType();
4283 }
4284 
4285 
4286 
4287 ExprResult
4288 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4289                           tok::TokenKind Kind, Expr *Input) {
4290   UnaryOperatorKind Opc;
4291   switch (Kind) {
4292   default: llvm_unreachable("Unknown unary op!");
4293   case tok::plusplus:   Opc = UO_PostInc; break;
4294   case tok::minusminus: Opc = UO_PostDec; break;
4295   }
4296 
4297   // Since this might is a postfix expression, get rid of ParenListExprs.
4298   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4299   if (Result.isInvalid()) return ExprError();
4300   Input = Result.get();
4301 
4302   return BuildUnaryOp(S, OpLoc, Opc, Input);
4303 }
4304 
4305 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4306 ///
4307 /// \return true on error
4308 static bool checkArithmeticOnObjCPointer(Sema &S,
4309                                          SourceLocation opLoc,
4310                                          Expr *op) {
4311   assert(op->getType()->isObjCObjectPointerType());
4312   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4313       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4314     return false;
4315 
4316   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4317     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4318     << op->getSourceRange();
4319   return true;
4320 }
4321 
4322 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4323   auto *BaseNoParens = Base->IgnoreParens();
4324   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4325     return MSProp->getPropertyDecl()->getType()->isArrayType();
4326   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4327 }
4328 
4329 ExprResult
4330 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4331                               Expr *idx, SourceLocation rbLoc) {
4332   if (base && !base->getType().isNull() &&
4333       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4334     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4335                                     /*Length=*/nullptr, rbLoc);
4336 
4337   // Since this might be a postfix expression, get rid of ParenListExprs.
4338   if (isa<ParenListExpr>(base)) {
4339     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4340     if (result.isInvalid()) return ExprError();
4341     base = result.get();
4342   }
4343 
4344   // A comma-expression as the index is deprecated in C++2a onwards.
4345   if (getLangOpts().CPlusPlus2a &&
4346       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4347        (isa<CXXOperatorCallExpr>(idx) &&
4348         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4349     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4350       << SourceRange(base->getBeginLoc(), rbLoc);
4351   }
4352 
4353   // Handle any non-overload placeholder types in the base and index
4354   // expressions.  We can't handle overloads here because the other
4355   // operand might be an overloadable type, in which case the overload
4356   // resolution for the operator overload should get the first crack
4357   // at the overload.
4358   bool IsMSPropertySubscript = false;
4359   if (base->getType()->isNonOverloadPlaceholderType()) {
4360     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4361     if (!IsMSPropertySubscript) {
4362       ExprResult result = CheckPlaceholderExpr(base);
4363       if (result.isInvalid())
4364         return ExprError();
4365       base = result.get();
4366     }
4367   }
4368   if (idx->getType()->isNonOverloadPlaceholderType()) {
4369     ExprResult result = CheckPlaceholderExpr(idx);
4370     if (result.isInvalid()) return ExprError();
4371     idx = result.get();
4372   }
4373 
4374   // Build an unanalyzed expression if either operand is type-dependent.
4375   if (getLangOpts().CPlusPlus &&
4376       (base->isTypeDependent() || idx->isTypeDependent())) {
4377     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4378                                             VK_LValue, OK_Ordinary, rbLoc);
4379   }
4380 
4381   // MSDN, property (C++)
4382   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4383   // This attribute can also be used in the declaration of an empty array in a
4384   // class or structure definition. For example:
4385   // __declspec(property(get=GetX, put=PutX)) int x[];
4386   // The above statement indicates that x[] can be used with one or more array
4387   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4388   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4389   if (IsMSPropertySubscript) {
4390     // Build MS property subscript expression if base is MS property reference
4391     // or MS property subscript.
4392     return new (Context) MSPropertySubscriptExpr(
4393         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4394   }
4395 
4396   // Use C++ overloaded-operator rules if either operand has record
4397   // type.  The spec says to do this if either type is *overloadable*,
4398   // but enum types can't declare subscript operators or conversion
4399   // operators, so there's nothing interesting for overload resolution
4400   // to do if there aren't any record types involved.
4401   //
4402   // ObjC pointers have their own subscripting logic that is not tied
4403   // to overload resolution and so should not take this path.
4404   if (getLangOpts().CPlusPlus &&
4405       (base->getType()->isRecordType() ||
4406        (!base->getType()->isObjCObjectPointerType() &&
4407         idx->getType()->isRecordType()))) {
4408     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4409   }
4410 
4411   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4412 
4413   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4414     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4415 
4416   return Res;
4417 }
4418 
4419 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4420   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4421   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4422 
4423   // For expressions like `&(*s).b`, the base is recorded and what should be
4424   // checked.
4425   const MemberExpr *Member = nullptr;
4426   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4427     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4428 
4429   LastRecord.PossibleDerefs.erase(StrippedExpr);
4430 }
4431 
4432 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4433   QualType ResultTy = E->getType();
4434   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4435 
4436   // Bail if the element is an array since it is not memory access.
4437   if (isa<ArrayType>(ResultTy))
4438     return;
4439 
4440   if (ResultTy->hasAttr(attr::NoDeref)) {
4441     LastRecord.PossibleDerefs.insert(E);
4442     return;
4443   }
4444 
4445   // Check if the base type is a pointer to a member access of a struct
4446   // marked with noderef.
4447   const Expr *Base = E->getBase();
4448   QualType BaseTy = Base->getType();
4449   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4450     // Not a pointer access
4451     return;
4452 
4453   const MemberExpr *Member = nullptr;
4454   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4455          Member->isArrow())
4456     Base = Member->getBase();
4457 
4458   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4459     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4460       LastRecord.PossibleDerefs.insert(E);
4461   }
4462 }
4463 
4464 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4465                                           Expr *LowerBound,
4466                                           SourceLocation ColonLoc, Expr *Length,
4467                                           SourceLocation RBLoc) {
4468   if (Base->getType()->isPlaceholderType() &&
4469       !Base->getType()->isSpecificPlaceholderType(
4470           BuiltinType::OMPArraySection)) {
4471     ExprResult Result = CheckPlaceholderExpr(Base);
4472     if (Result.isInvalid())
4473       return ExprError();
4474     Base = Result.get();
4475   }
4476   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4477     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4478     if (Result.isInvalid())
4479       return ExprError();
4480     Result = DefaultLvalueConversion(Result.get());
4481     if (Result.isInvalid())
4482       return ExprError();
4483     LowerBound = Result.get();
4484   }
4485   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4486     ExprResult Result = CheckPlaceholderExpr(Length);
4487     if (Result.isInvalid())
4488       return ExprError();
4489     Result = DefaultLvalueConversion(Result.get());
4490     if (Result.isInvalid())
4491       return ExprError();
4492     Length = Result.get();
4493   }
4494 
4495   // Build an unanalyzed expression if either operand is type-dependent.
4496   if (Base->isTypeDependent() ||
4497       (LowerBound &&
4498        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4499       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4500     return new (Context)
4501         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4502                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4503   }
4504 
4505   // Perform default conversions.
4506   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4507   QualType ResultTy;
4508   if (OriginalTy->isAnyPointerType()) {
4509     ResultTy = OriginalTy->getPointeeType();
4510   } else if (OriginalTy->isArrayType()) {
4511     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4512   } else {
4513     return ExprError(
4514         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4515         << Base->getSourceRange());
4516   }
4517   // C99 6.5.2.1p1
4518   if (LowerBound) {
4519     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4520                                                       LowerBound);
4521     if (Res.isInvalid())
4522       return ExprError(Diag(LowerBound->getExprLoc(),
4523                             diag::err_omp_typecheck_section_not_integer)
4524                        << 0 << LowerBound->getSourceRange());
4525     LowerBound = Res.get();
4526 
4527     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4528         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4529       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4530           << 0 << LowerBound->getSourceRange();
4531   }
4532   if (Length) {
4533     auto Res =
4534         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4535     if (Res.isInvalid())
4536       return ExprError(Diag(Length->getExprLoc(),
4537                             diag::err_omp_typecheck_section_not_integer)
4538                        << 1 << Length->getSourceRange());
4539     Length = Res.get();
4540 
4541     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4542         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4543       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4544           << 1 << Length->getSourceRange();
4545   }
4546 
4547   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4548   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4549   // type. Note that functions are not objects, and that (in C99 parlance)
4550   // incomplete types are not object types.
4551   if (ResultTy->isFunctionType()) {
4552     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4553         << ResultTy << Base->getSourceRange();
4554     return ExprError();
4555   }
4556 
4557   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4558                           diag::err_omp_section_incomplete_type, Base))
4559     return ExprError();
4560 
4561   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4562     Expr::EvalResult Result;
4563     if (LowerBound->EvaluateAsInt(Result, Context)) {
4564       // OpenMP 4.5, [2.4 Array Sections]
4565       // The array section must be a subset of the original array.
4566       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4567       if (LowerBoundValue.isNegative()) {
4568         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4569             << LowerBound->getSourceRange();
4570         return ExprError();
4571       }
4572     }
4573   }
4574 
4575   if (Length) {
4576     Expr::EvalResult Result;
4577     if (Length->EvaluateAsInt(Result, Context)) {
4578       // OpenMP 4.5, [2.4 Array Sections]
4579       // The length must evaluate to non-negative integers.
4580       llvm::APSInt LengthValue = Result.Val.getInt();
4581       if (LengthValue.isNegative()) {
4582         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4583             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4584             << Length->getSourceRange();
4585         return ExprError();
4586       }
4587     }
4588   } else if (ColonLoc.isValid() &&
4589              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4590                                       !OriginalTy->isVariableArrayType()))) {
4591     // OpenMP 4.5, [2.4 Array Sections]
4592     // When the size of the array dimension is not known, the length must be
4593     // specified explicitly.
4594     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4595         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4596     return ExprError();
4597   }
4598 
4599   if (!Base->getType()->isSpecificPlaceholderType(
4600           BuiltinType::OMPArraySection)) {
4601     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4602     if (Result.isInvalid())
4603       return ExprError();
4604     Base = Result.get();
4605   }
4606   return new (Context)
4607       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4608                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4609 }
4610 
4611 ExprResult
4612 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4613                                       Expr *Idx, SourceLocation RLoc) {
4614   Expr *LHSExp = Base;
4615   Expr *RHSExp = Idx;
4616 
4617   ExprValueKind VK = VK_LValue;
4618   ExprObjectKind OK = OK_Ordinary;
4619 
4620   // Per C++ core issue 1213, the result is an xvalue if either operand is
4621   // a non-lvalue array, and an lvalue otherwise.
4622   if (getLangOpts().CPlusPlus11) {
4623     for (auto *Op : {LHSExp, RHSExp}) {
4624       Op = Op->IgnoreImplicit();
4625       if (Op->getType()->isArrayType() && !Op->isLValue())
4626         VK = VK_XValue;
4627     }
4628   }
4629 
4630   // Perform default conversions.
4631   if (!LHSExp->getType()->getAs<VectorType>()) {
4632     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4633     if (Result.isInvalid())
4634       return ExprError();
4635     LHSExp = Result.get();
4636   }
4637   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4638   if (Result.isInvalid())
4639     return ExprError();
4640   RHSExp = Result.get();
4641 
4642   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4643 
4644   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4645   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4646   // in the subscript position. As a result, we need to derive the array base
4647   // and index from the expression types.
4648   Expr *BaseExpr, *IndexExpr;
4649   QualType ResultType;
4650   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4651     BaseExpr = LHSExp;
4652     IndexExpr = RHSExp;
4653     ResultType = Context.DependentTy;
4654   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4655     BaseExpr = LHSExp;
4656     IndexExpr = RHSExp;
4657     ResultType = PTy->getPointeeType();
4658   } else if (const ObjCObjectPointerType *PTy =
4659                LHSTy->getAs<ObjCObjectPointerType>()) {
4660     BaseExpr = LHSExp;
4661     IndexExpr = RHSExp;
4662 
4663     // Use custom logic if this should be the pseudo-object subscript
4664     // expression.
4665     if (!LangOpts.isSubscriptPointerArithmetic())
4666       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4667                                           nullptr);
4668 
4669     ResultType = PTy->getPointeeType();
4670   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4671      // Handle the uncommon case of "123[Ptr]".
4672     BaseExpr = RHSExp;
4673     IndexExpr = LHSExp;
4674     ResultType = PTy->getPointeeType();
4675   } else if (const ObjCObjectPointerType *PTy =
4676                RHSTy->getAs<ObjCObjectPointerType>()) {
4677      // Handle the uncommon case of "123[Ptr]".
4678     BaseExpr = RHSExp;
4679     IndexExpr = LHSExp;
4680     ResultType = PTy->getPointeeType();
4681     if (!LangOpts.isSubscriptPointerArithmetic()) {
4682       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4683         << ResultType << BaseExpr->getSourceRange();
4684       return ExprError();
4685     }
4686   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4687     BaseExpr = LHSExp;    // vectors: V[123]
4688     IndexExpr = RHSExp;
4689     // We apply C++ DR1213 to vector subscripting too.
4690     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4691       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4692       if (Materialized.isInvalid())
4693         return ExprError();
4694       LHSExp = Materialized.get();
4695     }
4696     VK = LHSExp->getValueKind();
4697     if (VK != VK_RValue)
4698       OK = OK_VectorComponent;
4699 
4700     ResultType = VTy->getElementType();
4701     QualType BaseType = BaseExpr->getType();
4702     Qualifiers BaseQuals = BaseType.getQualifiers();
4703     Qualifiers MemberQuals = ResultType.getQualifiers();
4704     Qualifiers Combined = BaseQuals + MemberQuals;
4705     if (Combined != MemberQuals)
4706       ResultType = Context.getQualifiedType(ResultType, Combined);
4707   } else if (LHSTy->isArrayType()) {
4708     // If we see an array that wasn't promoted by
4709     // DefaultFunctionArrayLvalueConversion, it must be an array that
4710     // wasn't promoted because of the C90 rule that doesn't
4711     // allow promoting non-lvalue arrays.  Warn, then
4712     // force the promotion here.
4713     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4714         << LHSExp->getSourceRange();
4715     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4716                                CK_ArrayToPointerDecay).get();
4717     LHSTy = LHSExp->getType();
4718 
4719     BaseExpr = LHSExp;
4720     IndexExpr = RHSExp;
4721     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4722   } else if (RHSTy->isArrayType()) {
4723     // Same as previous, except for 123[f().a] case
4724     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4725         << RHSExp->getSourceRange();
4726     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4727                                CK_ArrayToPointerDecay).get();
4728     RHSTy = RHSExp->getType();
4729 
4730     BaseExpr = RHSExp;
4731     IndexExpr = LHSExp;
4732     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4733   } else {
4734     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4735        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4736   }
4737   // C99 6.5.2.1p1
4738   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4739     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4740                      << IndexExpr->getSourceRange());
4741 
4742   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4743        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4744          && !IndexExpr->isTypeDependent())
4745     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4746 
4747   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4748   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4749   // type. Note that Functions are not objects, and that (in C99 parlance)
4750   // incomplete types are not object types.
4751   if (ResultType->isFunctionType()) {
4752     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4753         << ResultType << BaseExpr->getSourceRange();
4754     return ExprError();
4755   }
4756 
4757   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4758     // GNU extension: subscripting on pointer to void
4759     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4760       << BaseExpr->getSourceRange();
4761 
4762     // C forbids expressions of unqualified void type from being l-values.
4763     // See IsCForbiddenLValueType.
4764     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4765   } else if (!ResultType->isDependentType() &&
4766       RequireCompleteType(LLoc, ResultType,
4767                           diag::err_subscript_incomplete_type, BaseExpr))
4768     return ExprError();
4769 
4770   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4771          !ResultType.isCForbiddenLValueType());
4772 
4773   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4774       FunctionScopes.size() > 1) {
4775     if (auto *TT =
4776             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4777       for (auto I = FunctionScopes.rbegin(),
4778                 E = std::prev(FunctionScopes.rend());
4779            I != E; ++I) {
4780         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4781         if (CSI == nullptr)
4782           break;
4783         DeclContext *DC = nullptr;
4784         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4785           DC = LSI->CallOperator;
4786         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4787           DC = CRSI->TheCapturedDecl;
4788         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4789           DC = BSI->TheDecl;
4790         if (DC) {
4791           if (DC->containsDecl(TT->getDecl()))
4792             break;
4793           captureVariablyModifiedType(
4794               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4795         }
4796       }
4797     }
4798   }
4799 
4800   return new (Context)
4801       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4802 }
4803 
4804 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4805                                   ParmVarDecl *Param) {
4806   if (Param->hasUnparsedDefaultArg()) {
4807     Diag(CallLoc,
4808          diag::err_use_of_default_argument_to_function_declared_later) <<
4809       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4810     Diag(UnparsedDefaultArgLocs[Param],
4811          diag::note_default_argument_declared_here);
4812     return true;
4813   }
4814 
4815   if (Param->hasUninstantiatedDefaultArg()) {
4816     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4817 
4818     EnterExpressionEvaluationContext EvalContext(
4819         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4820 
4821     // Instantiate the expression.
4822     //
4823     // FIXME: Pass in a correct Pattern argument, otherwise
4824     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4825     //
4826     // template<typename T>
4827     // struct A {
4828     //   static int FooImpl();
4829     //
4830     //   template<typename Tp>
4831     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4832     //   // template argument list [[T], [Tp]], should be [[Tp]].
4833     //   friend A<Tp> Foo(int a);
4834     // };
4835     //
4836     // template<typename T>
4837     // A<T> Foo(int a = A<T>::FooImpl());
4838     MultiLevelTemplateArgumentList MutiLevelArgList
4839       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4840 
4841     InstantiatingTemplate Inst(*this, CallLoc, Param,
4842                                MutiLevelArgList.getInnermost());
4843     if (Inst.isInvalid())
4844       return true;
4845     if (Inst.isAlreadyInstantiating()) {
4846       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4847       Param->setInvalidDecl();
4848       return true;
4849     }
4850 
4851     ExprResult Result;
4852     {
4853       // C++ [dcl.fct.default]p5:
4854       //   The names in the [default argument] expression are bound, and
4855       //   the semantic constraints are checked, at the point where the
4856       //   default argument expression appears.
4857       ContextRAII SavedContext(*this, FD);
4858       LocalInstantiationScope Local(*this);
4859       runWithSufficientStackSpace(CallLoc, [&] {
4860         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4861                                   /*DirectInit*/false);
4862       });
4863     }
4864     if (Result.isInvalid())
4865       return true;
4866 
4867     // Check the expression as an initializer for the parameter.
4868     InitializedEntity Entity
4869       = InitializedEntity::InitializeParameter(Context, Param);
4870     InitializationKind Kind = InitializationKind::CreateCopy(
4871         Param->getLocation(),
4872         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4873     Expr *ResultE = Result.getAs<Expr>();
4874 
4875     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4876     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4877     if (Result.isInvalid())
4878       return true;
4879 
4880     Result =
4881         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4882                             /*DiscardedValue*/ false);
4883     if (Result.isInvalid())
4884       return true;
4885 
4886     // Remember the instantiated default argument.
4887     Param->setDefaultArg(Result.getAs<Expr>());
4888     if (ASTMutationListener *L = getASTMutationListener()) {
4889       L->DefaultArgumentInstantiated(Param);
4890     }
4891   }
4892 
4893   // If the default argument expression is not set yet, we are building it now.
4894   if (!Param->hasInit()) {
4895     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4896     Param->setInvalidDecl();
4897     return true;
4898   }
4899 
4900   // If the default expression creates temporaries, we need to
4901   // push them to the current stack of expression temporaries so they'll
4902   // be properly destroyed.
4903   // FIXME: We should really be rebuilding the default argument with new
4904   // bound temporaries; see the comment in PR5810.
4905   // We don't need to do that with block decls, though, because
4906   // blocks in default argument expression can never capture anything.
4907   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4908     // Set the "needs cleanups" bit regardless of whether there are
4909     // any explicit objects.
4910     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4911 
4912     // Append all the objects to the cleanup list.  Right now, this
4913     // should always be a no-op, because blocks in default argument
4914     // expressions should never be able to capture anything.
4915     assert(!Init->getNumObjects() &&
4916            "default argument expression has capturing blocks?");
4917   }
4918 
4919   // We already type-checked the argument, so we know it works.
4920   // Just mark all of the declarations in this potentially-evaluated expression
4921   // as being "referenced".
4922   EnterExpressionEvaluationContext EvalContext(
4923       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4924   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4925                                    /*SkipLocalVariables=*/true);
4926   return false;
4927 }
4928 
4929 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4930                                         FunctionDecl *FD, ParmVarDecl *Param) {
4931   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4932     return ExprError();
4933   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4934 }
4935 
4936 Sema::VariadicCallType
4937 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4938                           Expr *Fn) {
4939   if (Proto && Proto->isVariadic()) {
4940     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4941       return VariadicConstructor;
4942     else if (Fn && Fn->getType()->isBlockPointerType())
4943       return VariadicBlock;
4944     else if (FDecl) {
4945       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4946         if (Method->isInstance())
4947           return VariadicMethod;
4948     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4949       return VariadicMethod;
4950     return VariadicFunction;
4951   }
4952   return VariadicDoesNotApply;
4953 }
4954 
4955 namespace {
4956 class FunctionCallCCC final : public FunctionCallFilterCCC {
4957 public:
4958   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4959                   unsigned NumArgs, MemberExpr *ME)
4960       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4961         FunctionName(FuncName) {}
4962 
4963   bool ValidateCandidate(const TypoCorrection &candidate) override {
4964     if (!candidate.getCorrectionSpecifier() ||
4965         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4966       return false;
4967     }
4968 
4969     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4970   }
4971 
4972   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4973     return std::make_unique<FunctionCallCCC>(*this);
4974   }
4975 
4976 private:
4977   const IdentifierInfo *const FunctionName;
4978 };
4979 }
4980 
4981 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4982                                                FunctionDecl *FDecl,
4983                                                ArrayRef<Expr *> Args) {
4984   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4985   DeclarationName FuncName = FDecl->getDeclName();
4986   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4987 
4988   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4989   if (TypoCorrection Corrected = S.CorrectTypo(
4990           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4991           S.getScopeForContext(S.CurContext), nullptr, CCC,
4992           Sema::CTK_ErrorRecovery)) {
4993     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4994       if (Corrected.isOverloaded()) {
4995         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4996         OverloadCandidateSet::iterator Best;
4997         for (NamedDecl *CD : Corrected) {
4998           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4999             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5000                                    OCS);
5001         }
5002         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5003         case OR_Success:
5004           ND = Best->FoundDecl;
5005           Corrected.setCorrectionDecl(ND);
5006           break;
5007         default:
5008           break;
5009         }
5010       }
5011       ND = ND->getUnderlyingDecl();
5012       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5013         return Corrected;
5014     }
5015   }
5016   return TypoCorrection();
5017 }
5018 
5019 /// ConvertArgumentsForCall - Converts the arguments specified in
5020 /// Args/NumArgs to the parameter types of the function FDecl with
5021 /// function prototype Proto. Call is the call expression itself, and
5022 /// Fn is the function expression. For a C++ member function, this
5023 /// routine does not attempt to convert the object argument. Returns
5024 /// true if the call is ill-formed.
5025 bool
5026 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5027                               FunctionDecl *FDecl,
5028                               const FunctionProtoType *Proto,
5029                               ArrayRef<Expr *> Args,
5030                               SourceLocation RParenLoc,
5031                               bool IsExecConfig) {
5032   // Bail out early if calling a builtin with custom typechecking.
5033   if (FDecl)
5034     if (unsigned ID = FDecl->getBuiltinID())
5035       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5036         return false;
5037 
5038   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5039   // assignment, to the types of the corresponding parameter, ...
5040   unsigned NumParams = Proto->getNumParams();
5041   bool Invalid = false;
5042   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5043   unsigned FnKind = Fn->getType()->isBlockPointerType()
5044                        ? 1 /* block */
5045                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5046                                        : 0 /* function */);
5047 
5048   // If too few arguments are available (and we don't have default
5049   // arguments for the remaining parameters), don't make the call.
5050   if (Args.size() < NumParams) {
5051     if (Args.size() < MinArgs) {
5052       TypoCorrection TC;
5053       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5054         unsigned diag_id =
5055             MinArgs == NumParams && !Proto->isVariadic()
5056                 ? diag::err_typecheck_call_too_few_args_suggest
5057                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5058         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5059                                         << static_cast<unsigned>(Args.size())
5060                                         << TC.getCorrectionRange());
5061       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5062         Diag(RParenLoc,
5063              MinArgs == NumParams && !Proto->isVariadic()
5064                  ? diag::err_typecheck_call_too_few_args_one
5065                  : diag::err_typecheck_call_too_few_args_at_least_one)
5066             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5067       else
5068         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5069                             ? diag::err_typecheck_call_too_few_args
5070                             : diag::err_typecheck_call_too_few_args_at_least)
5071             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5072             << Fn->getSourceRange();
5073 
5074       // Emit the location of the prototype.
5075       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5076         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5077 
5078       return true;
5079     }
5080     // We reserve space for the default arguments when we create
5081     // the call expression, before calling ConvertArgumentsForCall.
5082     assert((Call->getNumArgs() == NumParams) &&
5083            "We should have reserved space for the default arguments before!");
5084   }
5085 
5086   // If too many are passed and not variadic, error on the extras and drop
5087   // them.
5088   if (Args.size() > NumParams) {
5089     if (!Proto->isVariadic()) {
5090       TypoCorrection TC;
5091       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5092         unsigned diag_id =
5093             MinArgs == NumParams && !Proto->isVariadic()
5094                 ? diag::err_typecheck_call_too_many_args_suggest
5095                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5096         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5097                                         << static_cast<unsigned>(Args.size())
5098                                         << TC.getCorrectionRange());
5099       } else if (NumParams == 1 && FDecl &&
5100                  FDecl->getParamDecl(0)->getDeclName())
5101         Diag(Args[NumParams]->getBeginLoc(),
5102              MinArgs == NumParams
5103                  ? diag::err_typecheck_call_too_many_args_one
5104                  : diag::err_typecheck_call_too_many_args_at_most_one)
5105             << FnKind << FDecl->getParamDecl(0)
5106             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5107             << SourceRange(Args[NumParams]->getBeginLoc(),
5108                            Args.back()->getEndLoc());
5109       else
5110         Diag(Args[NumParams]->getBeginLoc(),
5111              MinArgs == NumParams
5112                  ? diag::err_typecheck_call_too_many_args
5113                  : diag::err_typecheck_call_too_many_args_at_most)
5114             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5115             << Fn->getSourceRange()
5116             << SourceRange(Args[NumParams]->getBeginLoc(),
5117                            Args.back()->getEndLoc());
5118 
5119       // Emit the location of the prototype.
5120       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5121         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5122 
5123       // This deletes the extra arguments.
5124       Call->shrinkNumArgs(NumParams);
5125       return true;
5126     }
5127   }
5128   SmallVector<Expr *, 8> AllArgs;
5129   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5130 
5131   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5132                                    AllArgs, CallType);
5133   if (Invalid)
5134     return true;
5135   unsigned TotalNumArgs = AllArgs.size();
5136   for (unsigned i = 0; i < TotalNumArgs; ++i)
5137     Call->setArg(i, AllArgs[i]);
5138 
5139   return false;
5140 }
5141 
5142 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5143                                   const FunctionProtoType *Proto,
5144                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5145                                   SmallVectorImpl<Expr *> &AllArgs,
5146                                   VariadicCallType CallType, bool AllowExplicit,
5147                                   bool IsListInitialization) {
5148   unsigned NumParams = Proto->getNumParams();
5149   bool Invalid = false;
5150   size_t ArgIx = 0;
5151   // Continue to check argument types (even if we have too few/many args).
5152   for (unsigned i = FirstParam; i < NumParams; i++) {
5153     QualType ProtoArgType = Proto->getParamType(i);
5154 
5155     Expr *Arg;
5156     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5157     if (ArgIx < Args.size()) {
5158       Arg = Args[ArgIx++];
5159 
5160       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5161                               diag::err_call_incomplete_argument, Arg))
5162         return true;
5163 
5164       // Strip the unbridged-cast placeholder expression off, if applicable.
5165       bool CFAudited = false;
5166       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5167           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5168           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5169         Arg = stripARCUnbridgedCast(Arg);
5170       else if (getLangOpts().ObjCAutoRefCount &&
5171                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5172                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5173         CFAudited = true;
5174 
5175       if (Proto->getExtParameterInfo(i).isNoEscape())
5176         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5177           BE->getBlockDecl()->setDoesNotEscape();
5178 
5179       InitializedEntity Entity =
5180           Param ? InitializedEntity::InitializeParameter(Context, Param,
5181                                                          ProtoArgType)
5182                 : InitializedEntity::InitializeParameter(
5183                       Context, ProtoArgType, Proto->isParamConsumed(i));
5184 
5185       // Remember that parameter belongs to a CF audited API.
5186       if (CFAudited)
5187         Entity.setParameterCFAudited();
5188 
5189       ExprResult ArgE = PerformCopyInitialization(
5190           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5191       if (ArgE.isInvalid())
5192         return true;
5193 
5194       Arg = ArgE.getAs<Expr>();
5195     } else {
5196       assert(Param && "can't use default arguments without a known callee");
5197 
5198       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5199       if (ArgExpr.isInvalid())
5200         return true;
5201 
5202       Arg = ArgExpr.getAs<Expr>();
5203     }
5204 
5205     // Check for array bounds violations for each argument to the call. This
5206     // check only triggers warnings when the argument isn't a more complex Expr
5207     // with its own checking, such as a BinaryOperator.
5208     CheckArrayAccess(Arg);
5209 
5210     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5211     CheckStaticArrayArgument(CallLoc, Param, Arg);
5212 
5213     AllArgs.push_back(Arg);
5214   }
5215 
5216   // If this is a variadic call, handle args passed through "...".
5217   if (CallType != VariadicDoesNotApply) {
5218     // Assume that extern "C" functions with variadic arguments that
5219     // return __unknown_anytype aren't *really* variadic.
5220     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5221         FDecl->isExternC()) {
5222       for (Expr *A : Args.slice(ArgIx)) {
5223         QualType paramType; // ignored
5224         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5225         Invalid |= arg.isInvalid();
5226         AllArgs.push_back(arg.get());
5227       }
5228 
5229     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5230     } else {
5231       for (Expr *A : Args.slice(ArgIx)) {
5232         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5233         Invalid |= Arg.isInvalid();
5234         AllArgs.push_back(Arg.get());
5235       }
5236     }
5237 
5238     // Check for array bounds violations.
5239     for (Expr *A : Args.slice(ArgIx))
5240       CheckArrayAccess(A);
5241   }
5242   return Invalid;
5243 }
5244 
5245 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5246   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5247   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5248     TL = DTL.getOriginalLoc();
5249   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5250     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5251       << ATL.getLocalSourceRange();
5252 }
5253 
5254 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5255 /// array parameter, check that it is non-null, and that if it is formed by
5256 /// array-to-pointer decay, the underlying array is sufficiently large.
5257 ///
5258 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5259 /// array type derivation, then for each call to the function, the value of the
5260 /// corresponding actual argument shall provide access to the first element of
5261 /// an array with at least as many elements as specified by the size expression.
5262 void
5263 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5264                                ParmVarDecl *Param,
5265                                const Expr *ArgExpr) {
5266   // Static array parameters are not supported in C++.
5267   if (!Param || getLangOpts().CPlusPlus)
5268     return;
5269 
5270   QualType OrigTy = Param->getOriginalType();
5271 
5272   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5273   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5274     return;
5275 
5276   if (ArgExpr->isNullPointerConstant(Context,
5277                                      Expr::NPC_NeverValueDependent)) {
5278     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5279     DiagnoseCalleeStaticArrayParam(*this, Param);
5280     return;
5281   }
5282 
5283   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5284   if (!CAT)
5285     return;
5286 
5287   const ConstantArrayType *ArgCAT =
5288     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5289   if (!ArgCAT)
5290     return;
5291 
5292   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5293                                              ArgCAT->getElementType())) {
5294     if (ArgCAT->getSize().ult(CAT->getSize())) {
5295       Diag(CallLoc, diag::warn_static_array_too_small)
5296           << ArgExpr->getSourceRange()
5297           << (unsigned)ArgCAT->getSize().getZExtValue()
5298           << (unsigned)CAT->getSize().getZExtValue() << 0;
5299       DiagnoseCalleeStaticArrayParam(*this, Param);
5300     }
5301     return;
5302   }
5303 
5304   Optional<CharUnits> ArgSize =
5305       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5306   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5307   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5308     Diag(CallLoc, diag::warn_static_array_too_small)
5309         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5310         << (unsigned)ParmSize->getQuantity() << 1;
5311     DiagnoseCalleeStaticArrayParam(*this, Param);
5312   }
5313 }
5314 
5315 /// Given a function expression of unknown-any type, try to rebuild it
5316 /// to have a function type.
5317 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5318 
5319 /// Is the given type a placeholder that we need to lower out
5320 /// immediately during argument processing?
5321 static bool isPlaceholderToRemoveAsArg(QualType type) {
5322   // Placeholders are never sugared.
5323   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5324   if (!placeholder) return false;
5325 
5326   switch (placeholder->getKind()) {
5327   // Ignore all the non-placeholder types.
5328 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5329   case BuiltinType::Id:
5330 #include "clang/Basic/OpenCLImageTypes.def"
5331 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5332   case BuiltinType::Id:
5333 #include "clang/Basic/OpenCLExtensionTypes.def"
5334   // In practice we'll never use this, since all SVE types are sugared
5335   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5336 #define SVE_TYPE(Name, Id, SingletonId) \
5337   case BuiltinType::Id:
5338 #include "clang/Basic/AArch64SVEACLETypes.def"
5339 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5340 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5341 #include "clang/AST/BuiltinTypes.def"
5342     return false;
5343 
5344   // We cannot lower out overload sets; they might validly be resolved
5345   // by the call machinery.
5346   case BuiltinType::Overload:
5347     return false;
5348 
5349   // Unbridged casts in ARC can be handled in some call positions and
5350   // should be left in place.
5351   case BuiltinType::ARCUnbridgedCast:
5352     return false;
5353 
5354   // Pseudo-objects should be converted as soon as possible.
5355   case BuiltinType::PseudoObject:
5356     return true;
5357 
5358   // The debugger mode could theoretically but currently does not try
5359   // to resolve unknown-typed arguments based on known parameter types.
5360   case BuiltinType::UnknownAny:
5361     return true;
5362 
5363   // These are always invalid as call arguments and should be reported.
5364   case BuiltinType::BoundMember:
5365   case BuiltinType::BuiltinFn:
5366   case BuiltinType::OMPArraySection:
5367     return true;
5368 
5369   }
5370   llvm_unreachable("bad builtin type kind");
5371 }
5372 
5373 /// Check an argument list for placeholders that we won't try to
5374 /// handle later.
5375 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5376   // Apply this processing to all the arguments at once instead of
5377   // dying at the first failure.
5378   bool hasInvalid = false;
5379   for (size_t i = 0, e = args.size(); i != e; i++) {
5380     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5381       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5382       if (result.isInvalid()) hasInvalid = true;
5383       else args[i] = result.get();
5384     } else if (hasInvalid) {
5385       (void)S.CorrectDelayedTyposInExpr(args[i]);
5386     }
5387   }
5388   return hasInvalid;
5389 }
5390 
5391 /// If a builtin function has a pointer argument with no explicit address
5392 /// space, then it should be able to accept a pointer to any address
5393 /// space as input.  In order to do this, we need to replace the
5394 /// standard builtin declaration with one that uses the same address space
5395 /// as the call.
5396 ///
5397 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5398 ///                  it does not contain any pointer arguments without
5399 ///                  an address space qualifer.  Otherwise the rewritten
5400 ///                  FunctionDecl is returned.
5401 /// TODO: Handle pointer return types.
5402 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5403                                                 FunctionDecl *FDecl,
5404                                                 MultiExprArg ArgExprs) {
5405 
5406   QualType DeclType = FDecl->getType();
5407   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5408 
5409   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5410       ArgExprs.size() < FT->getNumParams())
5411     return nullptr;
5412 
5413   bool NeedsNewDecl = false;
5414   unsigned i = 0;
5415   SmallVector<QualType, 8> OverloadParams;
5416 
5417   for (QualType ParamType : FT->param_types()) {
5418 
5419     // Convert array arguments to pointer to simplify type lookup.
5420     ExprResult ArgRes =
5421         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5422     if (ArgRes.isInvalid())
5423       return nullptr;
5424     Expr *Arg = ArgRes.get();
5425     QualType ArgType = Arg->getType();
5426     if (!ParamType->isPointerType() ||
5427         ParamType.getQualifiers().hasAddressSpace() ||
5428         !ArgType->isPointerType() ||
5429         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5430       OverloadParams.push_back(ParamType);
5431       continue;
5432     }
5433 
5434     QualType PointeeType = ParamType->getPointeeType();
5435     if (PointeeType.getQualifiers().hasAddressSpace())
5436       continue;
5437 
5438     NeedsNewDecl = true;
5439     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5440 
5441     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5442     OverloadParams.push_back(Context.getPointerType(PointeeType));
5443   }
5444 
5445   if (!NeedsNewDecl)
5446     return nullptr;
5447 
5448   FunctionProtoType::ExtProtoInfo EPI;
5449   EPI.Variadic = FT->isVariadic();
5450   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5451                                                 OverloadParams, EPI);
5452   DeclContext *Parent = FDecl->getParent();
5453   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5454                                                     FDecl->getLocation(),
5455                                                     FDecl->getLocation(),
5456                                                     FDecl->getIdentifier(),
5457                                                     OverloadTy,
5458                                                     /*TInfo=*/nullptr,
5459                                                     SC_Extern, false,
5460                                                     /*hasPrototype=*/true);
5461   SmallVector<ParmVarDecl*, 16> Params;
5462   FT = cast<FunctionProtoType>(OverloadTy);
5463   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5464     QualType ParamType = FT->getParamType(i);
5465     ParmVarDecl *Parm =
5466         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5467                                 SourceLocation(), nullptr, ParamType,
5468                                 /*TInfo=*/nullptr, SC_None, nullptr);
5469     Parm->setScopeInfo(0, i);
5470     Params.push_back(Parm);
5471   }
5472   OverloadDecl->setParams(Params);
5473   return OverloadDecl;
5474 }
5475 
5476 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5477                                     FunctionDecl *Callee,
5478                                     MultiExprArg ArgExprs) {
5479   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5480   // similar attributes) really don't like it when functions are called with an
5481   // invalid number of args.
5482   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5483                          /*PartialOverloading=*/false) &&
5484       !Callee->isVariadic())
5485     return;
5486   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5487     return;
5488 
5489   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5490     S.Diag(Fn->getBeginLoc(),
5491            isa<CXXMethodDecl>(Callee)
5492                ? diag::err_ovl_no_viable_member_function_in_call
5493                : diag::err_ovl_no_viable_function_in_call)
5494         << Callee << Callee->getSourceRange();
5495     S.Diag(Callee->getLocation(),
5496            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5497         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5498     return;
5499   }
5500 }
5501 
5502 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5503     const UnresolvedMemberExpr *const UME, Sema &S) {
5504 
5505   const auto GetFunctionLevelDCIfCXXClass =
5506       [](Sema &S) -> const CXXRecordDecl * {
5507     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5508     if (!DC || !DC->getParent())
5509       return nullptr;
5510 
5511     // If the call to some member function was made from within a member
5512     // function body 'M' return return 'M's parent.
5513     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5514       return MD->getParent()->getCanonicalDecl();
5515     // else the call was made from within a default member initializer of a
5516     // class, so return the class.
5517     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5518       return RD->getCanonicalDecl();
5519     return nullptr;
5520   };
5521   // If our DeclContext is neither a member function nor a class (in the
5522   // case of a lambda in a default member initializer), we can't have an
5523   // enclosing 'this'.
5524 
5525   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5526   if (!CurParentClass)
5527     return false;
5528 
5529   // The naming class for implicit member functions call is the class in which
5530   // name lookup starts.
5531   const CXXRecordDecl *const NamingClass =
5532       UME->getNamingClass()->getCanonicalDecl();
5533   assert(NamingClass && "Must have naming class even for implicit access");
5534 
5535   // If the unresolved member functions were found in a 'naming class' that is
5536   // related (either the same or derived from) to the class that contains the
5537   // member function that itself contained the implicit member access.
5538 
5539   return CurParentClass == NamingClass ||
5540          CurParentClass->isDerivedFrom(NamingClass);
5541 }
5542 
5543 static void
5544 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5545     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5546 
5547   if (!UME)
5548     return;
5549 
5550   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5551   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5552   // already been captured, or if this is an implicit member function call (if
5553   // it isn't, an attempt to capture 'this' should already have been made).
5554   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5555       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5556     return;
5557 
5558   // Check if the naming class in which the unresolved members were found is
5559   // related (same as or is a base of) to the enclosing class.
5560 
5561   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5562     return;
5563 
5564 
5565   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5566   // If the enclosing function is not dependent, then this lambda is
5567   // capture ready, so if we can capture this, do so.
5568   if (!EnclosingFunctionCtx->isDependentContext()) {
5569     // If the current lambda and all enclosing lambdas can capture 'this' -
5570     // then go ahead and capture 'this' (since our unresolved overload set
5571     // contains at least one non-static member function).
5572     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5573       S.CheckCXXThisCapture(CallLoc);
5574   } else if (S.CurContext->isDependentContext()) {
5575     // ... since this is an implicit member reference, that might potentially
5576     // involve a 'this' capture, mark 'this' for potential capture in
5577     // enclosing lambdas.
5578     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5579       CurLSI->addPotentialThisCapture(CallLoc);
5580   }
5581 }
5582 
5583 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5584                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5585                                Expr *ExecConfig) {
5586   ExprResult Call =
5587       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5588   if (Call.isInvalid())
5589     return Call;
5590 
5591   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5592   // language modes.
5593   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5594     if (ULE->hasExplicitTemplateArgs() &&
5595         ULE->decls_begin() == ULE->decls_end()) {
5596       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5597                                  ? diag::warn_cxx17_compat_adl_only_template_id
5598                                  : diag::ext_adl_only_template_id)
5599           << ULE->getName();
5600     }
5601   }
5602 
5603   return Call;
5604 }
5605 
5606 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5607 /// This provides the location of the left/right parens and a list of comma
5608 /// locations.
5609 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5610                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5611                                Expr *ExecConfig, bool IsExecConfig) {
5612   // Since this might be a postfix expression, get rid of ParenListExprs.
5613   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5614   if (Result.isInvalid()) return ExprError();
5615   Fn = Result.get();
5616 
5617   if (checkArgsForPlaceholders(*this, ArgExprs))
5618     return ExprError();
5619 
5620   if (getLangOpts().CPlusPlus) {
5621     // If this is a pseudo-destructor expression, build the call immediately.
5622     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5623       if (!ArgExprs.empty()) {
5624         // Pseudo-destructor calls should not have any arguments.
5625         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5626             << FixItHint::CreateRemoval(
5627                    SourceRange(ArgExprs.front()->getBeginLoc(),
5628                                ArgExprs.back()->getEndLoc()));
5629       }
5630 
5631       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5632                               VK_RValue, RParenLoc);
5633     }
5634     if (Fn->getType() == Context.PseudoObjectTy) {
5635       ExprResult result = CheckPlaceholderExpr(Fn);
5636       if (result.isInvalid()) return ExprError();
5637       Fn = result.get();
5638     }
5639 
5640     // Determine whether this is a dependent call inside a C++ template,
5641     // in which case we won't do any semantic analysis now.
5642     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5643       if (ExecConfig) {
5644         return CUDAKernelCallExpr::Create(
5645             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5646             Context.DependentTy, VK_RValue, RParenLoc);
5647       } else {
5648 
5649         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5650             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5651             Fn->getBeginLoc());
5652 
5653         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5654                                 VK_RValue, RParenLoc);
5655       }
5656     }
5657 
5658     // Determine whether this is a call to an object (C++ [over.call.object]).
5659     if (Fn->getType()->isRecordType())
5660       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5661                                           RParenLoc);
5662 
5663     if (Fn->getType() == Context.UnknownAnyTy) {
5664       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5665       if (result.isInvalid()) return ExprError();
5666       Fn = result.get();
5667     }
5668 
5669     if (Fn->getType() == Context.BoundMemberTy) {
5670       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5671                                        RParenLoc);
5672     }
5673   }
5674 
5675   // Check for overloaded calls.  This can happen even in C due to extensions.
5676   if (Fn->getType() == Context.OverloadTy) {
5677     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5678 
5679     // We aren't supposed to apply this logic if there's an '&' involved.
5680     if (!find.HasFormOfMemberPointer) {
5681       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5682         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5683                                 VK_RValue, RParenLoc);
5684       OverloadExpr *ovl = find.Expression;
5685       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5686         return BuildOverloadedCallExpr(
5687             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5688             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5689       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5690                                        RParenLoc);
5691     }
5692   }
5693 
5694   // If we're directly calling a function, get the appropriate declaration.
5695   if (Fn->getType() == Context.UnknownAnyTy) {
5696     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5697     if (result.isInvalid()) return ExprError();
5698     Fn = result.get();
5699   }
5700 
5701   Expr *NakedFn = Fn->IgnoreParens();
5702 
5703   bool CallingNDeclIndirectly = false;
5704   NamedDecl *NDecl = nullptr;
5705   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5706     if (UnOp->getOpcode() == UO_AddrOf) {
5707       CallingNDeclIndirectly = true;
5708       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5709     }
5710   }
5711 
5712   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5713     NDecl = DRE->getDecl();
5714 
5715     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5716     if (FDecl && FDecl->getBuiltinID()) {
5717       // Rewrite the function decl for this builtin by replacing parameters
5718       // with no explicit address space with the address space of the arguments
5719       // in ArgExprs.
5720       if ((FDecl =
5721                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5722         NDecl = FDecl;
5723         Fn = DeclRefExpr::Create(
5724             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5725             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5726             nullptr, DRE->isNonOdrUse());
5727       }
5728     }
5729   } else if (isa<MemberExpr>(NakedFn))
5730     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5731 
5732   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5733     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5734                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5735       return ExprError();
5736 
5737     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5738       return ExprError();
5739 
5740     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5741   }
5742 
5743   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5744                                ExecConfig, IsExecConfig);
5745 }
5746 
5747 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5748 ///
5749 /// __builtin_astype( value, dst type )
5750 ///
5751 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5752                                  SourceLocation BuiltinLoc,
5753                                  SourceLocation RParenLoc) {
5754   ExprValueKind VK = VK_RValue;
5755   ExprObjectKind OK = OK_Ordinary;
5756   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5757   QualType SrcTy = E->getType();
5758   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5759     return ExprError(Diag(BuiltinLoc,
5760                           diag::err_invalid_astype_of_different_size)
5761                      << DstTy
5762                      << SrcTy
5763                      << E->getSourceRange());
5764   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5765 }
5766 
5767 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5768 /// provided arguments.
5769 ///
5770 /// __builtin_convertvector( value, dst type )
5771 ///
5772 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5773                                         SourceLocation BuiltinLoc,
5774                                         SourceLocation RParenLoc) {
5775   TypeSourceInfo *TInfo;
5776   GetTypeFromParser(ParsedDestTy, &TInfo);
5777   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5778 }
5779 
5780 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5781 /// i.e. an expression not of \p OverloadTy.  The expression should
5782 /// unary-convert to an expression of function-pointer or
5783 /// block-pointer type.
5784 ///
5785 /// \param NDecl the declaration being called, if available
5786 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5787                                        SourceLocation LParenLoc,
5788                                        ArrayRef<Expr *> Args,
5789                                        SourceLocation RParenLoc, Expr *Config,
5790                                        bool IsExecConfig, ADLCallKind UsesADL) {
5791   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5792   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5793 
5794   // Functions with 'interrupt' attribute cannot be called directly.
5795   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5796     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5797     return ExprError();
5798   }
5799 
5800   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5801   // so there's some risk when calling out to non-interrupt handler functions
5802   // that the callee might not preserve them. This is easy to diagnose here,
5803   // but can be very challenging to debug.
5804   if (auto *Caller = getCurFunctionDecl())
5805     if (Caller->hasAttr<ARMInterruptAttr>()) {
5806       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5807       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5808         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5809     }
5810 
5811   // Promote the function operand.
5812   // We special-case function promotion here because we only allow promoting
5813   // builtin functions to function pointers in the callee of a call.
5814   ExprResult Result;
5815   QualType ResultTy;
5816   if (BuiltinID &&
5817       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5818     // Extract the return type from the (builtin) function pointer type.
5819     // FIXME Several builtins still have setType in
5820     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5821     // Builtins.def to ensure they are correct before removing setType calls.
5822     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5823     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5824     ResultTy = FDecl->getCallResultType();
5825   } else {
5826     Result = CallExprUnaryConversions(Fn);
5827     ResultTy = Context.BoolTy;
5828   }
5829   if (Result.isInvalid())
5830     return ExprError();
5831   Fn = Result.get();
5832 
5833   // Check for a valid function type, but only if it is not a builtin which
5834   // requires custom type checking. These will be handled by
5835   // CheckBuiltinFunctionCall below just after creation of the call expression.
5836   const FunctionType *FuncT = nullptr;
5837   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5838   retry:
5839     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5840       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5841       // have type pointer to function".
5842       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5843       if (!FuncT)
5844         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5845                          << Fn->getType() << Fn->getSourceRange());
5846     } else if (const BlockPointerType *BPT =
5847                    Fn->getType()->getAs<BlockPointerType>()) {
5848       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5849     } else {
5850       // Handle calls to expressions of unknown-any type.
5851       if (Fn->getType() == Context.UnknownAnyTy) {
5852         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5853         if (rewrite.isInvalid())
5854           return ExprError();
5855         Fn = rewrite.get();
5856         goto retry;
5857       }
5858 
5859       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5860                        << Fn->getType() << Fn->getSourceRange());
5861     }
5862   }
5863 
5864   // Get the number of parameters in the function prototype, if any.
5865   // We will allocate space for max(Args.size(), NumParams) arguments
5866   // in the call expression.
5867   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5868   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5869 
5870   CallExpr *TheCall;
5871   if (Config) {
5872     assert(UsesADL == ADLCallKind::NotADL &&
5873            "CUDAKernelCallExpr should not use ADL");
5874     TheCall =
5875         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5876                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5877   } else {
5878     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5879                                RParenLoc, NumParams, UsesADL);
5880   }
5881 
5882   if (!getLangOpts().CPlusPlus) {
5883     // Forget about the nulled arguments since typo correction
5884     // do not handle them well.
5885     TheCall->shrinkNumArgs(Args.size());
5886     // C cannot always handle TypoExpr nodes in builtin calls and direct
5887     // function calls as their argument checking don't necessarily handle
5888     // dependent types properly, so make sure any TypoExprs have been
5889     // dealt with.
5890     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5891     if (!Result.isUsable()) return ExprError();
5892     CallExpr *TheOldCall = TheCall;
5893     TheCall = dyn_cast<CallExpr>(Result.get());
5894     bool CorrectedTypos = TheCall != TheOldCall;
5895     if (!TheCall) return Result;
5896     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5897 
5898     // A new call expression node was created if some typos were corrected.
5899     // However it may not have been constructed with enough storage. In this
5900     // case, rebuild the node with enough storage. The waste of space is
5901     // immaterial since this only happens when some typos were corrected.
5902     if (CorrectedTypos && Args.size() < NumParams) {
5903       if (Config)
5904         TheCall = CUDAKernelCallExpr::Create(
5905             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5906             RParenLoc, NumParams);
5907       else
5908         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5909                                    RParenLoc, NumParams, UsesADL);
5910     }
5911     // We can now handle the nulled arguments for the default arguments.
5912     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5913   }
5914 
5915   // Bail out early if calling a builtin with custom type checking.
5916   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5917     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5918 
5919   if (getLangOpts().CUDA) {
5920     if (Config) {
5921       // CUDA: Kernel calls must be to global functions
5922       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5923         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5924             << FDecl << Fn->getSourceRange());
5925 
5926       // CUDA: Kernel function must have 'void' return type
5927       if (!FuncT->getReturnType()->isVoidType() &&
5928           !FuncT->getReturnType()->getAs<AutoType>() &&
5929           !FuncT->getReturnType()->isInstantiationDependentType())
5930         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5931             << Fn->getType() << Fn->getSourceRange());
5932     } else {
5933       // CUDA: Calls to global functions must be configured
5934       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5935         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5936             << FDecl << Fn->getSourceRange());
5937     }
5938   }
5939 
5940   // Check for a valid return type
5941   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5942                           FDecl))
5943     return ExprError();
5944 
5945   // We know the result type of the call, set it.
5946   TheCall->setType(FuncT->getCallResultType(Context));
5947   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5948 
5949   if (Proto) {
5950     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5951                                 IsExecConfig))
5952       return ExprError();
5953   } else {
5954     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5955 
5956     if (FDecl) {
5957       // Check if we have too few/too many template arguments, based
5958       // on our knowledge of the function definition.
5959       const FunctionDecl *Def = nullptr;
5960       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5961         Proto = Def->getType()->getAs<FunctionProtoType>();
5962        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5963           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5964           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5965       }
5966 
5967       // If the function we're calling isn't a function prototype, but we have
5968       // a function prototype from a prior declaratiom, use that prototype.
5969       if (!FDecl->hasPrototype())
5970         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5971     }
5972 
5973     // Promote the arguments (C99 6.5.2.2p6).
5974     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5975       Expr *Arg = Args[i];
5976 
5977       if (Proto && i < Proto->getNumParams()) {
5978         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5979             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5980         ExprResult ArgE =
5981             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5982         if (ArgE.isInvalid())
5983           return true;
5984 
5985         Arg = ArgE.getAs<Expr>();
5986 
5987       } else {
5988         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5989 
5990         if (ArgE.isInvalid())
5991           return true;
5992 
5993         Arg = ArgE.getAs<Expr>();
5994       }
5995 
5996       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5997                               diag::err_call_incomplete_argument, Arg))
5998         return ExprError();
5999 
6000       TheCall->setArg(i, Arg);
6001     }
6002   }
6003 
6004   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6005     if (!Method->isStatic())
6006       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6007         << Fn->getSourceRange());
6008 
6009   // Check for sentinels
6010   if (NDecl)
6011     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6012 
6013   // Do special checking on direct calls to functions.
6014   if (FDecl) {
6015     if (CheckFunctionCall(FDecl, TheCall, Proto))
6016       return ExprError();
6017 
6018     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6019 
6020     if (BuiltinID)
6021       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6022   } else if (NDecl) {
6023     if (CheckPointerCall(NDecl, TheCall, Proto))
6024       return ExprError();
6025   } else {
6026     if (CheckOtherCall(TheCall, Proto))
6027       return ExprError();
6028   }
6029 
6030   return MaybeBindToTemporary(TheCall);
6031 }
6032 
6033 ExprResult
6034 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6035                            SourceLocation RParenLoc, Expr *InitExpr) {
6036   assert(Ty && "ActOnCompoundLiteral(): missing type");
6037   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6038 
6039   TypeSourceInfo *TInfo;
6040   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6041   if (!TInfo)
6042     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6043 
6044   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6045 }
6046 
6047 ExprResult
6048 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6049                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6050   QualType literalType = TInfo->getType();
6051 
6052   if (literalType->isArrayType()) {
6053     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6054           diag::err_illegal_decl_array_incomplete_type,
6055           SourceRange(LParenLoc,
6056                       LiteralExpr->getSourceRange().getEnd())))
6057       return ExprError();
6058     if (literalType->isVariableArrayType())
6059       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6060         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6061   } else if (!literalType->isDependentType() &&
6062              RequireCompleteType(LParenLoc, literalType,
6063                diag::err_typecheck_decl_incomplete_type,
6064                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6065     return ExprError();
6066 
6067   InitializedEntity Entity
6068     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6069   InitializationKind Kind
6070     = InitializationKind::CreateCStyleCast(LParenLoc,
6071                                            SourceRange(LParenLoc, RParenLoc),
6072                                            /*InitList=*/true);
6073   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6074   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6075                                       &literalType);
6076   if (Result.isInvalid())
6077     return ExprError();
6078   LiteralExpr = Result.get();
6079 
6080   bool isFileScope = !CurContext->isFunctionOrMethod();
6081 
6082   // In C, compound literals are l-values for some reason.
6083   // For GCC compatibility, in C++, file-scope array compound literals with
6084   // constant initializers are also l-values, and compound literals are
6085   // otherwise prvalues.
6086   //
6087   // (GCC also treats C++ list-initialized file-scope array prvalues with
6088   // constant initializers as l-values, but that's non-conforming, so we don't
6089   // follow it there.)
6090   //
6091   // FIXME: It would be better to handle the lvalue cases as materializing and
6092   // lifetime-extending a temporary object, but our materialized temporaries
6093   // representation only supports lifetime extension from a variable, not "out
6094   // of thin air".
6095   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6096   // is bound to the result of applying array-to-pointer decay to the compound
6097   // literal.
6098   // FIXME: GCC supports compound literals of reference type, which should
6099   // obviously have a value kind derived from the kind of reference involved.
6100   ExprValueKind VK =
6101       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6102           ? VK_RValue
6103           : VK_LValue;
6104 
6105   if (isFileScope)
6106     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6107       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6108         Expr *Init = ILE->getInit(i);
6109         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6110       }
6111 
6112   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6113                                               VK, LiteralExpr, isFileScope);
6114   if (isFileScope) {
6115     if (!LiteralExpr->isTypeDependent() &&
6116         !LiteralExpr->isValueDependent() &&
6117         !literalType->isDependentType()) // C99 6.5.2.5p3
6118       if (CheckForConstantInitializer(LiteralExpr, literalType))
6119         return ExprError();
6120   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6121              literalType.getAddressSpace() != LangAS::Default) {
6122     // Embedded-C extensions to C99 6.5.2.5:
6123     //   "If the compound literal occurs inside the body of a function, the
6124     //   type name shall not be qualified by an address-space qualifier."
6125     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6126       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6127     return ExprError();
6128   }
6129 
6130   // Compound literals that have automatic storage duration are destroyed at
6131   // the end of the scope. Emit diagnostics if it is or contains a C union type
6132   // that is non-trivial to destruct.
6133   if (!isFileScope)
6134     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6135       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6136                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6137 
6138   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6139       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6140     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6141                                        E->getInitializer()->getExprLoc());
6142 
6143   return MaybeBindToTemporary(E);
6144 }
6145 
6146 ExprResult
6147 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6148                     SourceLocation RBraceLoc) {
6149   // Only produce each kind of designated initialization diagnostic once.
6150   SourceLocation FirstDesignator;
6151   bool DiagnosedArrayDesignator = false;
6152   bool DiagnosedNestedDesignator = false;
6153   bool DiagnosedMixedDesignator = false;
6154 
6155   // Check that any designated initializers are syntactically valid in the
6156   // current language mode.
6157   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6158     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6159       if (FirstDesignator.isInvalid())
6160         FirstDesignator = DIE->getBeginLoc();
6161 
6162       if (!getLangOpts().CPlusPlus)
6163         break;
6164 
6165       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6166         DiagnosedNestedDesignator = true;
6167         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6168           << DIE->getDesignatorsSourceRange();
6169       }
6170 
6171       for (auto &Desig : DIE->designators()) {
6172         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6173           DiagnosedArrayDesignator = true;
6174           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6175             << Desig.getSourceRange();
6176         }
6177       }
6178 
6179       if (!DiagnosedMixedDesignator &&
6180           !isa<DesignatedInitExpr>(InitArgList[0])) {
6181         DiagnosedMixedDesignator = true;
6182         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6183           << DIE->getSourceRange();
6184         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6185           << InitArgList[0]->getSourceRange();
6186       }
6187     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6188                isa<DesignatedInitExpr>(InitArgList[0])) {
6189       DiagnosedMixedDesignator = true;
6190       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6191       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6192         << DIE->getSourceRange();
6193       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6194         << InitArgList[I]->getSourceRange();
6195     }
6196   }
6197 
6198   if (FirstDesignator.isValid()) {
6199     // Only diagnose designated initiaization as a C++20 extension if we didn't
6200     // already diagnose use of (non-C++20) C99 designator syntax.
6201     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6202         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6203       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6204                                 ? diag::warn_cxx17_compat_designated_init
6205                                 : diag::ext_cxx_designated_init);
6206     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6207       Diag(FirstDesignator, diag::ext_designated_init);
6208     }
6209   }
6210 
6211   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6212 }
6213 
6214 ExprResult
6215 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6216                     SourceLocation RBraceLoc) {
6217   // Semantic analysis for initializers is done by ActOnDeclarator() and
6218   // CheckInitializer() - it requires knowledge of the object being initialized.
6219 
6220   // Immediately handle non-overload placeholders.  Overloads can be
6221   // resolved contextually, but everything else here can't.
6222   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6223     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6224       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6225 
6226       // Ignore failures; dropping the entire initializer list because
6227       // of one failure would be terrible for indexing/etc.
6228       if (result.isInvalid()) continue;
6229 
6230       InitArgList[I] = result.get();
6231     }
6232   }
6233 
6234   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6235                                                RBraceLoc);
6236   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6237   return E;
6238 }
6239 
6240 /// Do an explicit extend of the given block pointer if we're in ARC.
6241 void Sema::maybeExtendBlockObject(ExprResult &E) {
6242   assert(E.get()->getType()->isBlockPointerType());
6243   assert(E.get()->isRValue());
6244 
6245   // Only do this in an r-value context.
6246   if (!getLangOpts().ObjCAutoRefCount) return;
6247 
6248   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6249                                CK_ARCExtendBlockObject, E.get(),
6250                                /*base path*/ nullptr, VK_RValue);
6251   Cleanup.setExprNeedsCleanups(true);
6252 }
6253 
6254 /// Prepare a conversion of the given expression to an ObjC object
6255 /// pointer type.
6256 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6257   QualType type = E.get()->getType();
6258   if (type->isObjCObjectPointerType()) {
6259     return CK_BitCast;
6260   } else if (type->isBlockPointerType()) {
6261     maybeExtendBlockObject(E);
6262     return CK_BlockPointerToObjCPointerCast;
6263   } else {
6264     assert(type->isPointerType());
6265     return CK_CPointerToObjCPointerCast;
6266   }
6267 }
6268 
6269 /// Prepares for a scalar cast, performing all the necessary stages
6270 /// except the final cast and returning the kind required.
6271 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6272   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6273   // Also, callers should have filtered out the invalid cases with
6274   // pointers.  Everything else should be possible.
6275 
6276   QualType SrcTy = Src.get()->getType();
6277   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6278     return CK_NoOp;
6279 
6280   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6281   case Type::STK_MemberPointer:
6282     llvm_unreachable("member pointer type in C");
6283 
6284   case Type::STK_CPointer:
6285   case Type::STK_BlockPointer:
6286   case Type::STK_ObjCObjectPointer:
6287     switch (DestTy->getScalarTypeKind()) {
6288     case Type::STK_CPointer: {
6289       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6290       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6291       if (SrcAS != DestAS)
6292         return CK_AddressSpaceConversion;
6293       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6294         return CK_NoOp;
6295       return CK_BitCast;
6296     }
6297     case Type::STK_BlockPointer:
6298       return (SrcKind == Type::STK_BlockPointer
6299                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6300     case Type::STK_ObjCObjectPointer:
6301       if (SrcKind == Type::STK_ObjCObjectPointer)
6302         return CK_BitCast;
6303       if (SrcKind == Type::STK_CPointer)
6304         return CK_CPointerToObjCPointerCast;
6305       maybeExtendBlockObject(Src);
6306       return CK_BlockPointerToObjCPointerCast;
6307     case Type::STK_Bool:
6308       return CK_PointerToBoolean;
6309     case Type::STK_Integral:
6310       return CK_PointerToIntegral;
6311     case Type::STK_Floating:
6312     case Type::STK_FloatingComplex:
6313     case Type::STK_IntegralComplex:
6314     case Type::STK_MemberPointer:
6315     case Type::STK_FixedPoint:
6316       llvm_unreachable("illegal cast from pointer");
6317     }
6318     llvm_unreachable("Should have returned before this");
6319 
6320   case Type::STK_FixedPoint:
6321     switch (DestTy->getScalarTypeKind()) {
6322     case Type::STK_FixedPoint:
6323       return CK_FixedPointCast;
6324     case Type::STK_Bool:
6325       return CK_FixedPointToBoolean;
6326     case Type::STK_Integral:
6327       return CK_FixedPointToIntegral;
6328     case Type::STK_Floating:
6329     case Type::STK_IntegralComplex:
6330     case Type::STK_FloatingComplex:
6331       Diag(Src.get()->getExprLoc(),
6332            diag::err_unimplemented_conversion_with_fixed_point_type)
6333           << DestTy;
6334       return CK_IntegralCast;
6335     case Type::STK_CPointer:
6336     case Type::STK_ObjCObjectPointer:
6337     case Type::STK_BlockPointer:
6338     case Type::STK_MemberPointer:
6339       llvm_unreachable("illegal cast to pointer type");
6340     }
6341     llvm_unreachable("Should have returned before this");
6342 
6343   case Type::STK_Bool: // casting from bool is like casting from an integer
6344   case Type::STK_Integral:
6345     switch (DestTy->getScalarTypeKind()) {
6346     case Type::STK_CPointer:
6347     case Type::STK_ObjCObjectPointer:
6348     case Type::STK_BlockPointer:
6349       if (Src.get()->isNullPointerConstant(Context,
6350                                            Expr::NPC_ValueDependentIsNull))
6351         return CK_NullToPointer;
6352       return CK_IntegralToPointer;
6353     case Type::STK_Bool:
6354       return CK_IntegralToBoolean;
6355     case Type::STK_Integral:
6356       return CK_IntegralCast;
6357     case Type::STK_Floating:
6358       return CK_IntegralToFloating;
6359     case Type::STK_IntegralComplex:
6360       Src = ImpCastExprToType(Src.get(),
6361                       DestTy->castAs<ComplexType>()->getElementType(),
6362                       CK_IntegralCast);
6363       return CK_IntegralRealToComplex;
6364     case Type::STK_FloatingComplex:
6365       Src = ImpCastExprToType(Src.get(),
6366                       DestTy->castAs<ComplexType>()->getElementType(),
6367                       CK_IntegralToFloating);
6368       return CK_FloatingRealToComplex;
6369     case Type::STK_MemberPointer:
6370       llvm_unreachable("member pointer type in C");
6371     case Type::STK_FixedPoint:
6372       return CK_IntegralToFixedPoint;
6373     }
6374     llvm_unreachable("Should have returned before this");
6375 
6376   case Type::STK_Floating:
6377     switch (DestTy->getScalarTypeKind()) {
6378     case Type::STK_Floating:
6379       return CK_FloatingCast;
6380     case Type::STK_Bool:
6381       return CK_FloatingToBoolean;
6382     case Type::STK_Integral:
6383       return CK_FloatingToIntegral;
6384     case Type::STK_FloatingComplex:
6385       Src = ImpCastExprToType(Src.get(),
6386                               DestTy->castAs<ComplexType>()->getElementType(),
6387                               CK_FloatingCast);
6388       return CK_FloatingRealToComplex;
6389     case Type::STK_IntegralComplex:
6390       Src = ImpCastExprToType(Src.get(),
6391                               DestTy->castAs<ComplexType>()->getElementType(),
6392                               CK_FloatingToIntegral);
6393       return CK_IntegralRealToComplex;
6394     case Type::STK_CPointer:
6395     case Type::STK_ObjCObjectPointer:
6396     case Type::STK_BlockPointer:
6397       llvm_unreachable("valid float->pointer cast?");
6398     case Type::STK_MemberPointer:
6399       llvm_unreachable("member pointer type in C");
6400     case Type::STK_FixedPoint:
6401       Diag(Src.get()->getExprLoc(),
6402            diag::err_unimplemented_conversion_with_fixed_point_type)
6403           << SrcTy;
6404       return CK_IntegralCast;
6405     }
6406     llvm_unreachable("Should have returned before this");
6407 
6408   case Type::STK_FloatingComplex:
6409     switch (DestTy->getScalarTypeKind()) {
6410     case Type::STK_FloatingComplex:
6411       return CK_FloatingComplexCast;
6412     case Type::STK_IntegralComplex:
6413       return CK_FloatingComplexToIntegralComplex;
6414     case Type::STK_Floating: {
6415       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6416       if (Context.hasSameType(ET, DestTy))
6417         return CK_FloatingComplexToReal;
6418       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6419       return CK_FloatingCast;
6420     }
6421     case Type::STK_Bool:
6422       return CK_FloatingComplexToBoolean;
6423     case Type::STK_Integral:
6424       Src = ImpCastExprToType(Src.get(),
6425                               SrcTy->castAs<ComplexType>()->getElementType(),
6426                               CK_FloatingComplexToReal);
6427       return CK_FloatingToIntegral;
6428     case Type::STK_CPointer:
6429     case Type::STK_ObjCObjectPointer:
6430     case Type::STK_BlockPointer:
6431       llvm_unreachable("valid complex float->pointer cast?");
6432     case Type::STK_MemberPointer:
6433       llvm_unreachable("member pointer type in C");
6434     case Type::STK_FixedPoint:
6435       Diag(Src.get()->getExprLoc(),
6436            diag::err_unimplemented_conversion_with_fixed_point_type)
6437           << SrcTy;
6438       return CK_IntegralCast;
6439     }
6440     llvm_unreachable("Should have returned before this");
6441 
6442   case Type::STK_IntegralComplex:
6443     switch (DestTy->getScalarTypeKind()) {
6444     case Type::STK_FloatingComplex:
6445       return CK_IntegralComplexToFloatingComplex;
6446     case Type::STK_IntegralComplex:
6447       return CK_IntegralComplexCast;
6448     case Type::STK_Integral: {
6449       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6450       if (Context.hasSameType(ET, DestTy))
6451         return CK_IntegralComplexToReal;
6452       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6453       return CK_IntegralCast;
6454     }
6455     case Type::STK_Bool:
6456       return CK_IntegralComplexToBoolean;
6457     case Type::STK_Floating:
6458       Src = ImpCastExprToType(Src.get(),
6459                               SrcTy->castAs<ComplexType>()->getElementType(),
6460                               CK_IntegralComplexToReal);
6461       return CK_IntegralToFloating;
6462     case Type::STK_CPointer:
6463     case Type::STK_ObjCObjectPointer:
6464     case Type::STK_BlockPointer:
6465       llvm_unreachable("valid complex int->pointer cast?");
6466     case Type::STK_MemberPointer:
6467       llvm_unreachable("member pointer type in C");
6468     case Type::STK_FixedPoint:
6469       Diag(Src.get()->getExprLoc(),
6470            diag::err_unimplemented_conversion_with_fixed_point_type)
6471           << SrcTy;
6472       return CK_IntegralCast;
6473     }
6474     llvm_unreachable("Should have returned before this");
6475   }
6476 
6477   llvm_unreachable("Unhandled scalar cast");
6478 }
6479 
6480 static bool breakDownVectorType(QualType type, uint64_t &len,
6481                                 QualType &eltType) {
6482   // Vectors are simple.
6483   if (const VectorType *vecType = type->getAs<VectorType>()) {
6484     len = vecType->getNumElements();
6485     eltType = vecType->getElementType();
6486     assert(eltType->isScalarType());
6487     return true;
6488   }
6489 
6490   // We allow lax conversion to and from non-vector types, but only if
6491   // they're real types (i.e. non-complex, non-pointer scalar types).
6492   if (!type->isRealType()) return false;
6493 
6494   len = 1;
6495   eltType = type;
6496   return true;
6497 }
6498 
6499 /// Are the two types lax-compatible vector types?  That is, given
6500 /// that one of them is a vector, do they have equal storage sizes,
6501 /// where the storage size is the number of elements times the element
6502 /// size?
6503 ///
6504 /// This will also return false if either of the types is neither a
6505 /// vector nor a real type.
6506 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6507   assert(destTy->isVectorType() || srcTy->isVectorType());
6508 
6509   // Disallow lax conversions between scalars and ExtVectors (these
6510   // conversions are allowed for other vector types because common headers
6511   // depend on them).  Most scalar OP ExtVector cases are handled by the
6512   // splat path anyway, which does what we want (convert, not bitcast).
6513   // What this rules out for ExtVectors is crazy things like char4*float.
6514   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6515   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6516 
6517   uint64_t srcLen, destLen;
6518   QualType srcEltTy, destEltTy;
6519   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6520   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6521 
6522   // ASTContext::getTypeSize will return the size rounded up to a
6523   // power of 2, so instead of using that, we need to use the raw
6524   // element size multiplied by the element count.
6525   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6526   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6527 
6528   return (srcLen * srcEltSize == destLen * destEltSize);
6529 }
6530 
6531 /// Is this a legal conversion between two types, one of which is
6532 /// known to be a vector type?
6533 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6534   assert(destTy->isVectorType() || srcTy->isVectorType());
6535 
6536   switch (Context.getLangOpts().getLaxVectorConversions()) {
6537   case LangOptions::LaxVectorConversionKind::None:
6538     return false;
6539 
6540   case LangOptions::LaxVectorConversionKind::Integer:
6541     if (!srcTy->isIntegralOrEnumerationType()) {
6542       auto *Vec = srcTy->getAs<VectorType>();
6543       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6544         return false;
6545     }
6546     if (!destTy->isIntegralOrEnumerationType()) {
6547       auto *Vec = destTy->getAs<VectorType>();
6548       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6549         return false;
6550     }
6551     // OK, integer (vector) -> integer (vector) bitcast.
6552     break;
6553 
6554     case LangOptions::LaxVectorConversionKind::All:
6555     break;
6556   }
6557 
6558   return areLaxCompatibleVectorTypes(srcTy, destTy);
6559 }
6560 
6561 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6562                            CastKind &Kind) {
6563   assert(VectorTy->isVectorType() && "Not a vector type!");
6564 
6565   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6566     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6567       return Diag(R.getBegin(),
6568                   Ty->isVectorType() ?
6569                   diag::err_invalid_conversion_between_vectors :
6570                   diag::err_invalid_conversion_between_vector_and_integer)
6571         << VectorTy << Ty << R;
6572   } else
6573     return Diag(R.getBegin(),
6574                 diag::err_invalid_conversion_between_vector_and_scalar)
6575       << VectorTy << Ty << R;
6576 
6577   Kind = CK_BitCast;
6578   return false;
6579 }
6580 
6581 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6582   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6583 
6584   if (DestElemTy == SplattedExpr->getType())
6585     return SplattedExpr;
6586 
6587   assert(DestElemTy->isFloatingType() ||
6588          DestElemTy->isIntegralOrEnumerationType());
6589 
6590   CastKind CK;
6591   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6592     // OpenCL requires that we convert `true` boolean expressions to -1, but
6593     // only when splatting vectors.
6594     if (DestElemTy->isFloatingType()) {
6595       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6596       // in two steps: boolean to signed integral, then to floating.
6597       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6598                                                  CK_BooleanToSignedIntegral);
6599       SplattedExpr = CastExprRes.get();
6600       CK = CK_IntegralToFloating;
6601     } else {
6602       CK = CK_BooleanToSignedIntegral;
6603     }
6604   } else {
6605     ExprResult CastExprRes = SplattedExpr;
6606     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6607     if (CastExprRes.isInvalid())
6608       return ExprError();
6609     SplattedExpr = CastExprRes.get();
6610   }
6611   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6612 }
6613 
6614 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6615                                     Expr *CastExpr, CastKind &Kind) {
6616   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6617 
6618   QualType SrcTy = CastExpr->getType();
6619 
6620   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6621   // an ExtVectorType.
6622   // In OpenCL, casts between vectors of different types are not allowed.
6623   // (See OpenCL 6.2).
6624   if (SrcTy->isVectorType()) {
6625     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6626         (getLangOpts().OpenCL &&
6627          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6628       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6629         << DestTy << SrcTy << R;
6630       return ExprError();
6631     }
6632     Kind = CK_BitCast;
6633     return CastExpr;
6634   }
6635 
6636   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6637   // conversion will take place first from scalar to elt type, and then
6638   // splat from elt type to vector.
6639   if (SrcTy->isPointerType())
6640     return Diag(R.getBegin(),
6641                 diag::err_invalid_conversion_between_vector_and_scalar)
6642       << DestTy << SrcTy << R;
6643 
6644   Kind = CK_VectorSplat;
6645   return prepareVectorSplat(DestTy, CastExpr);
6646 }
6647 
6648 ExprResult
6649 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6650                     Declarator &D, ParsedType &Ty,
6651                     SourceLocation RParenLoc, Expr *CastExpr) {
6652   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6653          "ActOnCastExpr(): missing type or expr");
6654 
6655   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6656   if (D.isInvalidType())
6657     return ExprError();
6658 
6659   if (getLangOpts().CPlusPlus) {
6660     // Check that there are no default arguments (C++ only).
6661     CheckExtraCXXDefaultArguments(D);
6662   } else {
6663     // Make sure any TypoExprs have been dealt with.
6664     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6665     if (!Res.isUsable())
6666       return ExprError();
6667     CastExpr = Res.get();
6668   }
6669 
6670   checkUnusedDeclAttributes(D);
6671 
6672   QualType castType = castTInfo->getType();
6673   Ty = CreateParsedType(castType, castTInfo);
6674 
6675   bool isVectorLiteral = false;
6676 
6677   // Check for an altivec or OpenCL literal,
6678   // i.e. all the elements are integer constants.
6679   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6680   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6681   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6682        && castType->isVectorType() && (PE || PLE)) {
6683     if (PLE && PLE->getNumExprs() == 0) {
6684       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6685       return ExprError();
6686     }
6687     if (PE || PLE->getNumExprs() == 1) {
6688       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6689       if (!E->getType()->isVectorType())
6690         isVectorLiteral = true;
6691     }
6692     else
6693       isVectorLiteral = true;
6694   }
6695 
6696   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6697   // then handle it as such.
6698   if (isVectorLiteral)
6699     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6700 
6701   // If the Expr being casted is a ParenListExpr, handle it specially.
6702   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6703   // sequence of BinOp comma operators.
6704   if (isa<ParenListExpr>(CastExpr)) {
6705     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6706     if (Result.isInvalid()) return ExprError();
6707     CastExpr = Result.get();
6708   }
6709 
6710   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6711       !getSourceManager().isInSystemMacro(LParenLoc))
6712     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6713 
6714   CheckTollFreeBridgeCast(castType, CastExpr);
6715 
6716   CheckObjCBridgeRelatedCast(castType, CastExpr);
6717 
6718   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6719 
6720   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6721 }
6722 
6723 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6724                                     SourceLocation RParenLoc, Expr *E,
6725                                     TypeSourceInfo *TInfo) {
6726   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6727          "Expected paren or paren list expression");
6728 
6729   Expr **exprs;
6730   unsigned numExprs;
6731   Expr *subExpr;
6732   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6733   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6734     LiteralLParenLoc = PE->getLParenLoc();
6735     LiteralRParenLoc = PE->getRParenLoc();
6736     exprs = PE->getExprs();
6737     numExprs = PE->getNumExprs();
6738   } else { // isa<ParenExpr> by assertion at function entrance
6739     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6740     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6741     subExpr = cast<ParenExpr>(E)->getSubExpr();
6742     exprs = &subExpr;
6743     numExprs = 1;
6744   }
6745 
6746   QualType Ty = TInfo->getType();
6747   assert(Ty->isVectorType() && "Expected vector type");
6748 
6749   SmallVector<Expr *, 8> initExprs;
6750   const VectorType *VTy = Ty->castAs<VectorType>();
6751   unsigned numElems = VTy->getNumElements();
6752 
6753   // '(...)' form of vector initialization in AltiVec: the number of
6754   // initializers must be one or must match the size of the vector.
6755   // If a single value is specified in the initializer then it will be
6756   // replicated to all the components of the vector
6757   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6758     // The number of initializers must be one or must match the size of the
6759     // vector. If a single value is specified in the initializer then it will
6760     // be replicated to all the components of the vector
6761     if (numExprs == 1) {
6762       QualType ElemTy = VTy->getElementType();
6763       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6764       if (Literal.isInvalid())
6765         return ExprError();
6766       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6767                                   PrepareScalarCast(Literal, ElemTy));
6768       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6769     }
6770     else if (numExprs < numElems) {
6771       Diag(E->getExprLoc(),
6772            diag::err_incorrect_number_of_vector_initializers);
6773       return ExprError();
6774     }
6775     else
6776       initExprs.append(exprs, exprs + numExprs);
6777   }
6778   else {
6779     // For OpenCL, when the number of initializers is a single value,
6780     // it will be replicated to all components of the vector.
6781     if (getLangOpts().OpenCL &&
6782         VTy->getVectorKind() == VectorType::GenericVector &&
6783         numExprs == 1) {
6784         QualType ElemTy = VTy->getElementType();
6785         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6786         if (Literal.isInvalid())
6787           return ExprError();
6788         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6789                                     PrepareScalarCast(Literal, ElemTy));
6790         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6791     }
6792 
6793     initExprs.append(exprs, exprs + numExprs);
6794   }
6795   // FIXME: This means that pretty-printing the final AST will produce curly
6796   // braces instead of the original commas.
6797   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6798                                                    initExprs, LiteralRParenLoc);
6799   initE->setType(Ty);
6800   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6801 }
6802 
6803 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6804 /// the ParenListExpr into a sequence of comma binary operators.
6805 ExprResult
6806 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6807   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6808   if (!E)
6809     return OrigExpr;
6810 
6811   ExprResult Result(E->getExpr(0));
6812 
6813   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6814     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6815                         E->getExpr(i));
6816 
6817   if (Result.isInvalid()) return ExprError();
6818 
6819   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6820 }
6821 
6822 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6823                                     SourceLocation R,
6824                                     MultiExprArg Val) {
6825   return ParenListExpr::Create(Context, L, Val, R);
6826 }
6827 
6828 /// Emit a specialized diagnostic when one expression is a null pointer
6829 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6830 /// emitted.
6831 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6832                                       SourceLocation QuestionLoc) {
6833   Expr *NullExpr = LHSExpr;
6834   Expr *NonPointerExpr = RHSExpr;
6835   Expr::NullPointerConstantKind NullKind =
6836       NullExpr->isNullPointerConstant(Context,
6837                                       Expr::NPC_ValueDependentIsNotNull);
6838 
6839   if (NullKind == Expr::NPCK_NotNull) {
6840     NullExpr = RHSExpr;
6841     NonPointerExpr = LHSExpr;
6842     NullKind =
6843         NullExpr->isNullPointerConstant(Context,
6844                                         Expr::NPC_ValueDependentIsNotNull);
6845   }
6846 
6847   if (NullKind == Expr::NPCK_NotNull)
6848     return false;
6849 
6850   if (NullKind == Expr::NPCK_ZeroExpression)
6851     return false;
6852 
6853   if (NullKind == Expr::NPCK_ZeroLiteral) {
6854     // In this case, check to make sure that we got here from a "NULL"
6855     // string in the source code.
6856     NullExpr = NullExpr->IgnoreParenImpCasts();
6857     SourceLocation loc = NullExpr->getExprLoc();
6858     if (!findMacroSpelling(loc, "NULL"))
6859       return false;
6860   }
6861 
6862   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6863   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6864       << NonPointerExpr->getType() << DiagType
6865       << NonPointerExpr->getSourceRange();
6866   return true;
6867 }
6868 
6869 /// Return false if the condition expression is valid, true otherwise.
6870 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6871   QualType CondTy = Cond->getType();
6872 
6873   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6874   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6875     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6876       << CondTy << Cond->getSourceRange();
6877     return true;
6878   }
6879 
6880   // C99 6.5.15p2
6881   if (CondTy->isScalarType()) return false;
6882 
6883   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6884     << CondTy << Cond->getSourceRange();
6885   return true;
6886 }
6887 
6888 /// Handle when one or both operands are void type.
6889 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6890                                          ExprResult &RHS) {
6891     Expr *LHSExpr = LHS.get();
6892     Expr *RHSExpr = RHS.get();
6893 
6894     if (!LHSExpr->getType()->isVoidType())
6895       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6896           << RHSExpr->getSourceRange();
6897     if (!RHSExpr->getType()->isVoidType())
6898       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6899           << LHSExpr->getSourceRange();
6900     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6901     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6902     return S.Context.VoidTy;
6903 }
6904 
6905 /// Return false if the NullExpr can be promoted to PointerTy,
6906 /// true otherwise.
6907 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6908                                         QualType PointerTy) {
6909   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6910       !NullExpr.get()->isNullPointerConstant(S.Context,
6911                                             Expr::NPC_ValueDependentIsNull))
6912     return true;
6913 
6914   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6915   return false;
6916 }
6917 
6918 /// Checks compatibility between two pointers and return the resulting
6919 /// type.
6920 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6921                                                      ExprResult &RHS,
6922                                                      SourceLocation Loc) {
6923   QualType LHSTy = LHS.get()->getType();
6924   QualType RHSTy = RHS.get()->getType();
6925 
6926   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6927     // Two identical pointers types are always compatible.
6928     return LHSTy;
6929   }
6930 
6931   QualType lhptee, rhptee;
6932 
6933   // Get the pointee types.
6934   bool IsBlockPointer = false;
6935   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6936     lhptee = LHSBTy->getPointeeType();
6937     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6938     IsBlockPointer = true;
6939   } else {
6940     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6941     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6942   }
6943 
6944   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6945   // differently qualified versions of compatible types, the result type is
6946   // a pointer to an appropriately qualified version of the composite
6947   // type.
6948 
6949   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6950   // clause doesn't make sense for our extensions. E.g. address space 2 should
6951   // be incompatible with address space 3: they may live on different devices or
6952   // anything.
6953   Qualifiers lhQual = lhptee.getQualifiers();
6954   Qualifiers rhQual = rhptee.getQualifiers();
6955 
6956   LangAS ResultAddrSpace = LangAS::Default;
6957   LangAS LAddrSpace = lhQual.getAddressSpace();
6958   LangAS RAddrSpace = rhQual.getAddressSpace();
6959 
6960   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6961   // spaces is disallowed.
6962   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6963     ResultAddrSpace = LAddrSpace;
6964   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6965     ResultAddrSpace = RAddrSpace;
6966   else {
6967     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6968         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6969         << RHS.get()->getSourceRange();
6970     return QualType();
6971   }
6972 
6973   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6974   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6975   lhQual.removeCVRQualifiers();
6976   rhQual.removeCVRQualifiers();
6977 
6978   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6979   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6980   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6981   // qual types are compatible iff
6982   //  * corresponded types are compatible
6983   //  * CVR qualifiers are equal
6984   //  * address spaces are equal
6985   // Thus for conditional operator we merge CVR and address space unqualified
6986   // pointees and if there is a composite type we return a pointer to it with
6987   // merged qualifiers.
6988   LHSCastKind =
6989       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6990   RHSCastKind =
6991       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6992   lhQual.removeAddressSpace();
6993   rhQual.removeAddressSpace();
6994 
6995   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6996   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6997 
6998   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6999 
7000   if (CompositeTy.isNull()) {
7001     // In this situation, we assume void* type. No especially good
7002     // reason, but this is what gcc does, and we do have to pick
7003     // to get a consistent AST.
7004     QualType incompatTy;
7005     incompatTy = S.Context.getPointerType(
7006         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7007     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7008     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7009 
7010     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7011     // for casts between types with incompatible address space qualifiers.
7012     // For the following code the compiler produces casts between global and
7013     // local address spaces of the corresponded innermost pointees:
7014     // local int *global *a;
7015     // global int *global *b;
7016     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7017     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7018         << LHSTy << RHSTy << LHS.get()->getSourceRange()
7019         << RHS.get()->getSourceRange();
7020 
7021     return incompatTy;
7022   }
7023 
7024   // The pointer types are compatible.
7025   // In case of OpenCL ResultTy should have the address space qualifier
7026   // which is a superset of address spaces of both the 2nd and the 3rd
7027   // operands of the conditional operator.
7028   QualType ResultTy = [&, ResultAddrSpace]() {
7029     if (S.getLangOpts().OpenCL) {
7030       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7031       CompositeQuals.setAddressSpace(ResultAddrSpace);
7032       return S.Context
7033           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7034           .withCVRQualifiers(MergedCVRQual);
7035     }
7036     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7037   }();
7038   if (IsBlockPointer)
7039     ResultTy = S.Context.getBlockPointerType(ResultTy);
7040   else
7041     ResultTy = S.Context.getPointerType(ResultTy);
7042 
7043   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7044   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7045   return ResultTy;
7046 }
7047 
7048 /// Return the resulting type when the operands are both block pointers.
7049 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7050                                                           ExprResult &LHS,
7051                                                           ExprResult &RHS,
7052                                                           SourceLocation Loc) {
7053   QualType LHSTy = LHS.get()->getType();
7054   QualType RHSTy = RHS.get()->getType();
7055 
7056   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7057     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7058       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7059       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7060       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7061       return destType;
7062     }
7063     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7064       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7065       << RHS.get()->getSourceRange();
7066     return QualType();
7067   }
7068 
7069   // We have 2 block pointer types.
7070   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7071 }
7072 
7073 /// Return the resulting type when the operands are both pointers.
7074 static QualType
7075 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7076                                             ExprResult &RHS,
7077                                             SourceLocation Loc) {
7078   // get the pointer types
7079   QualType LHSTy = LHS.get()->getType();
7080   QualType RHSTy = RHS.get()->getType();
7081 
7082   // get the "pointed to" types
7083   QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7084   QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7085 
7086   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7087   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7088     // Figure out necessary qualifiers (C99 6.5.15p6)
7089     QualType destPointee
7090       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7091     QualType destType = S.Context.getPointerType(destPointee);
7092     // Add qualifiers if necessary.
7093     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7094     // Promote to void*.
7095     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7096     return destType;
7097   }
7098   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7099     QualType destPointee
7100       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7101     QualType destType = S.Context.getPointerType(destPointee);
7102     // Add qualifiers if necessary.
7103     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7104     // Promote to void*.
7105     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7106     return destType;
7107   }
7108 
7109   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7110 }
7111 
7112 /// Return false if the first expression is not an integer and the second
7113 /// expression is not a pointer, true otherwise.
7114 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7115                                         Expr* PointerExpr, SourceLocation Loc,
7116                                         bool IsIntFirstExpr) {
7117   if (!PointerExpr->getType()->isPointerType() ||
7118       !Int.get()->getType()->isIntegerType())
7119     return false;
7120 
7121   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7122   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7123 
7124   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7125     << Expr1->getType() << Expr2->getType()
7126     << Expr1->getSourceRange() << Expr2->getSourceRange();
7127   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7128                             CK_IntegralToPointer);
7129   return true;
7130 }
7131 
7132 /// Simple conversion between integer and floating point types.
7133 ///
7134 /// Used when handling the OpenCL conditional operator where the
7135 /// condition is a vector while the other operands are scalar.
7136 ///
7137 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7138 /// types are either integer or floating type. Between the two
7139 /// operands, the type with the higher rank is defined as the "result
7140 /// type". The other operand needs to be promoted to the same type. No
7141 /// other type promotion is allowed. We cannot use
7142 /// UsualArithmeticConversions() for this purpose, since it always
7143 /// promotes promotable types.
7144 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7145                                             ExprResult &RHS,
7146                                             SourceLocation QuestionLoc) {
7147   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7148   if (LHS.isInvalid())
7149     return QualType();
7150   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7151   if (RHS.isInvalid())
7152     return QualType();
7153 
7154   // For conversion purposes, we ignore any qualifiers.
7155   // For example, "const float" and "float" are equivalent.
7156   QualType LHSType =
7157     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7158   QualType RHSType =
7159     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7160 
7161   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7162     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7163       << LHSType << LHS.get()->getSourceRange();
7164     return QualType();
7165   }
7166 
7167   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7168     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7169       << RHSType << RHS.get()->getSourceRange();
7170     return QualType();
7171   }
7172 
7173   // If both types are identical, no conversion is needed.
7174   if (LHSType == RHSType)
7175     return LHSType;
7176 
7177   // Now handle "real" floating types (i.e. float, double, long double).
7178   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7179     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7180                                  /*IsCompAssign = */ false);
7181 
7182   // Finally, we have two differing integer types.
7183   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7184   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7185 }
7186 
7187 /// Convert scalar operands to a vector that matches the
7188 ///        condition in length.
7189 ///
7190 /// Used when handling the OpenCL conditional operator where the
7191 /// condition is a vector while the other operands are scalar.
7192 ///
7193 /// We first compute the "result type" for the scalar operands
7194 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7195 /// into a vector of that type where the length matches the condition
7196 /// vector type. s6.11.6 requires that the element types of the result
7197 /// and the condition must have the same number of bits.
7198 static QualType
7199 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7200                               QualType CondTy, SourceLocation QuestionLoc) {
7201   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7202   if (ResTy.isNull()) return QualType();
7203 
7204   const VectorType *CV = CondTy->getAs<VectorType>();
7205   assert(CV);
7206 
7207   // Determine the vector result type
7208   unsigned NumElements = CV->getNumElements();
7209   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7210 
7211   // Ensure that all types have the same number of bits
7212   if (S.Context.getTypeSize(CV->getElementType())
7213       != S.Context.getTypeSize(ResTy)) {
7214     // Since VectorTy is created internally, it does not pretty print
7215     // with an OpenCL name. Instead, we just print a description.
7216     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7217     SmallString<64> Str;
7218     llvm::raw_svector_ostream OS(Str);
7219     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7220     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7221       << CondTy << OS.str();
7222     return QualType();
7223   }
7224 
7225   // Convert operands to the vector result type
7226   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7227   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7228 
7229   return VectorTy;
7230 }
7231 
7232 /// Return false if this is a valid OpenCL condition vector
7233 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7234                                        SourceLocation QuestionLoc) {
7235   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7236   // integral type.
7237   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7238   assert(CondTy);
7239   QualType EleTy = CondTy->getElementType();
7240   if (EleTy->isIntegerType()) return false;
7241 
7242   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7243     << Cond->getType() << Cond->getSourceRange();
7244   return true;
7245 }
7246 
7247 /// Return false if the vector condition type and the vector
7248 ///        result type are compatible.
7249 ///
7250 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7251 /// number of elements, and their element types have the same number
7252 /// of bits.
7253 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7254                               SourceLocation QuestionLoc) {
7255   const VectorType *CV = CondTy->getAs<VectorType>();
7256   const VectorType *RV = VecResTy->getAs<VectorType>();
7257   assert(CV && RV);
7258 
7259   if (CV->getNumElements() != RV->getNumElements()) {
7260     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7261       << CondTy << VecResTy;
7262     return true;
7263   }
7264 
7265   QualType CVE = CV->getElementType();
7266   QualType RVE = RV->getElementType();
7267 
7268   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7269     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7270       << CondTy << VecResTy;
7271     return true;
7272   }
7273 
7274   return false;
7275 }
7276 
7277 /// Return the resulting type for the conditional operator in
7278 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7279 ///        s6.3.i) when the condition is a vector type.
7280 static QualType
7281 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7282                              ExprResult &LHS, ExprResult &RHS,
7283                              SourceLocation QuestionLoc) {
7284   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7285   if (Cond.isInvalid())
7286     return QualType();
7287   QualType CondTy = Cond.get()->getType();
7288 
7289   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7290     return QualType();
7291 
7292   // If either operand is a vector then find the vector type of the
7293   // result as specified in OpenCL v1.1 s6.3.i.
7294   if (LHS.get()->getType()->isVectorType() ||
7295       RHS.get()->getType()->isVectorType()) {
7296     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7297                                               /*isCompAssign*/false,
7298                                               /*AllowBothBool*/true,
7299                                               /*AllowBoolConversions*/false);
7300     if (VecResTy.isNull()) return QualType();
7301     // The result type must match the condition type as specified in
7302     // OpenCL v1.1 s6.11.6.
7303     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7304       return QualType();
7305     return VecResTy;
7306   }
7307 
7308   // Both operands are scalar.
7309   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7310 }
7311 
7312 /// Return true if the Expr is block type
7313 static bool checkBlockType(Sema &S, const Expr *E) {
7314   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7315     QualType Ty = CE->getCallee()->getType();
7316     if (Ty->isBlockPointerType()) {
7317       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7318       return true;
7319     }
7320   }
7321   return false;
7322 }
7323 
7324 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7325 /// In that case, LHS = cond.
7326 /// C99 6.5.15
7327 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7328                                         ExprResult &RHS, ExprValueKind &VK,
7329                                         ExprObjectKind &OK,
7330                                         SourceLocation QuestionLoc) {
7331 
7332   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7333   if (!LHSResult.isUsable()) return QualType();
7334   LHS = LHSResult;
7335 
7336   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7337   if (!RHSResult.isUsable()) return QualType();
7338   RHS = RHSResult;
7339 
7340   // C++ is sufficiently different to merit its own checker.
7341   if (getLangOpts().CPlusPlus)
7342     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7343 
7344   VK = VK_RValue;
7345   OK = OK_Ordinary;
7346 
7347   // The OpenCL operator with a vector condition is sufficiently
7348   // different to merit its own checker.
7349   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7350     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7351 
7352   // First, check the condition.
7353   Cond = UsualUnaryConversions(Cond.get());
7354   if (Cond.isInvalid())
7355     return QualType();
7356   if (checkCondition(*this, Cond.get(), QuestionLoc))
7357     return QualType();
7358 
7359   // Now check the two expressions.
7360   if (LHS.get()->getType()->isVectorType() ||
7361       RHS.get()->getType()->isVectorType())
7362     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7363                                /*AllowBothBool*/true,
7364                                /*AllowBoolConversions*/false);
7365 
7366   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7367   if (LHS.isInvalid() || RHS.isInvalid())
7368     return QualType();
7369 
7370   QualType LHSTy = LHS.get()->getType();
7371   QualType RHSTy = RHS.get()->getType();
7372 
7373   // Diagnose attempts to convert between __float128 and long double where
7374   // such conversions currently can't be handled.
7375   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7376     Diag(QuestionLoc,
7377          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7378       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7379     return QualType();
7380   }
7381 
7382   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7383   // selection operator (?:).
7384   if (getLangOpts().OpenCL &&
7385       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7386     return QualType();
7387   }
7388 
7389   // If both operands have arithmetic type, do the usual arithmetic conversions
7390   // to find a common type: C99 6.5.15p3,5.
7391   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7392     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7393     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7394 
7395     return ResTy;
7396   }
7397 
7398   // If both operands are the same structure or union type, the result is that
7399   // type.
7400   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7401     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7402       if (LHSRT->getDecl() == RHSRT->getDecl())
7403         // "If both the operands have structure or union type, the result has
7404         // that type."  This implies that CV qualifiers are dropped.
7405         return LHSTy.getUnqualifiedType();
7406     // FIXME: Type of conditional expression must be complete in C mode.
7407   }
7408 
7409   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7410   // The following || allows only one side to be void (a GCC-ism).
7411   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7412     return checkConditionalVoidType(*this, LHS, RHS);
7413   }
7414 
7415   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7416   // the type of the other operand."
7417   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7418   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7419 
7420   // All objective-c pointer type analysis is done here.
7421   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7422                                                         QuestionLoc);
7423   if (LHS.isInvalid() || RHS.isInvalid())
7424     return QualType();
7425   if (!compositeType.isNull())
7426     return compositeType;
7427 
7428 
7429   // Handle block pointer types.
7430   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7431     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7432                                                      QuestionLoc);
7433 
7434   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7435   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7436     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7437                                                        QuestionLoc);
7438 
7439   // GCC compatibility: soften pointer/integer mismatch.  Note that
7440   // null pointers have been filtered out by this point.
7441   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7442       /*IsIntFirstExpr=*/true))
7443     return RHSTy;
7444   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7445       /*IsIntFirstExpr=*/false))
7446     return LHSTy;
7447 
7448   // Emit a better diagnostic if one of the expressions is a null pointer
7449   // constant and the other is not a pointer type. In this case, the user most
7450   // likely forgot to take the address of the other expression.
7451   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7452     return QualType();
7453 
7454   // Otherwise, the operands are not compatible.
7455   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7456     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7457     << RHS.get()->getSourceRange();
7458   return QualType();
7459 }
7460 
7461 /// FindCompositeObjCPointerType - Helper method to find composite type of
7462 /// two objective-c pointer types of the two input expressions.
7463 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7464                                             SourceLocation QuestionLoc) {
7465   QualType LHSTy = LHS.get()->getType();
7466   QualType RHSTy = RHS.get()->getType();
7467 
7468   // Handle things like Class and struct objc_class*.  Here we case the result
7469   // to the pseudo-builtin, because that will be implicitly cast back to the
7470   // redefinition type if an attempt is made to access its fields.
7471   if (LHSTy->isObjCClassType() &&
7472       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7473     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7474     return LHSTy;
7475   }
7476   if (RHSTy->isObjCClassType() &&
7477       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7478     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7479     return RHSTy;
7480   }
7481   // And the same for struct objc_object* / id
7482   if (LHSTy->isObjCIdType() &&
7483       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7484     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7485     return LHSTy;
7486   }
7487   if (RHSTy->isObjCIdType() &&
7488       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7489     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7490     return RHSTy;
7491   }
7492   // And the same for struct objc_selector* / SEL
7493   if (Context.isObjCSelType(LHSTy) &&
7494       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7495     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7496     return LHSTy;
7497   }
7498   if (Context.isObjCSelType(RHSTy) &&
7499       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7500     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7501     return RHSTy;
7502   }
7503   // Check constraints for Objective-C object pointers types.
7504   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7505 
7506     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7507       // Two identical object pointer types are always compatible.
7508       return LHSTy;
7509     }
7510     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7511     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7512     QualType compositeType = LHSTy;
7513 
7514     // If both operands are interfaces and either operand can be
7515     // assigned to the other, use that type as the composite
7516     // type. This allows
7517     //   xxx ? (A*) a : (B*) b
7518     // where B is a subclass of A.
7519     //
7520     // Additionally, as for assignment, if either type is 'id'
7521     // allow silent coercion. Finally, if the types are
7522     // incompatible then make sure to use 'id' as the composite
7523     // type so the result is acceptable for sending messages to.
7524 
7525     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7526     // It could return the composite type.
7527     if (!(compositeType =
7528           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7529       // Nothing more to do.
7530     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7531       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7532     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7533       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7534     } else if ((LHSOPT->isObjCQualifiedIdType() ||
7535                 RHSOPT->isObjCQualifiedIdType()) &&
7536                Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7537                                                          true)) {
7538       // Need to handle "id<xx>" explicitly.
7539       // GCC allows qualified id and any Objective-C type to devolve to
7540       // id. Currently localizing to here until clear this should be
7541       // part of ObjCQualifiedIdTypesAreCompatible.
7542       compositeType = Context.getObjCIdType();
7543     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7544       compositeType = Context.getObjCIdType();
7545     } else {
7546       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7547       << LHSTy << RHSTy
7548       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7549       QualType incompatTy = Context.getObjCIdType();
7550       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7551       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7552       return incompatTy;
7553     }
7554     // The object pointer types are compatible.
7555     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7556     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7557     return compositeType;
7558   }
7559   // Check Objective-C object pointer types and 'void *'
7560   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7561     if (getLangOpts().ObjCAutoRefCount) {
7562       // ARC forbids the implicit conversion of object pointers to 'void *',
7563       // so these types are not compatible.
7564       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7565           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7566       LHS = RHS = true;
7567       return QualType();
7568     }
7569     QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7570     QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7571     QualType destPointee
7572     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7573     QualType destType = Context.getPointerType(destPointee);
7574     // Add qualifiers if necessary.
7575     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7576     // Promote to void*.
7577     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7578     return destType;
7579   }
7580   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7581     if (getLangOpts().ObjCAutoRefCount) {
7582       // ARC forbids the implicit conversion of object pointers to 'void *',
7583       // so these types are not compatible.
7584       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7585           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7586       LHS = RHS = true;
7587       return QualType();
7588     }
7589     QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7590     QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7591     QualType destPointee
7592     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7593     QualType destType = Context.getPointerType(destPointee);
7594     // Add qualifiers if necessary.
7595     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7596     // Promote to void*.
7597     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7598     return destType;
7599   }
7600   return QualType();
7601 }
7602 
7603 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7604 /// ParenRange in parentheses.
7605 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7606                                const PartialDiagnostic &Note,
7607                                SourceRange ParenRange) {
7608   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7609   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7610       EndLoc.isValid()) {
7611     Self.Diag(Loc, Note)
7612       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7613       << FixItHint::CreateInsertion(EndLoc, ")");
7614   } else {
7615     // We can't display the parentheses, so just show the bare note.
7616     Self.Diag(Loc, Note) << ParenRange;
7617   }
7618 }
7619 
7620 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7621   return BinaryOperator::isAdditiveOp(Opc) ||
7622          BinaryOperator::isMultiplicativeOp(Opc) ||
7623          BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
7624   // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
7625   // not any of the logical operators.  Bitwise-xor is commonly used as a
7626   // logical-xor because there is no logical-xor operator.  The logical
7627   // operators, including uses of xor, have a high false positive rate for
7628   // precedence warnings.
7629 }
7630 
7631 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7632 /// expression, either using a built-in or overloaded operator,
7633 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7634 /// expression.
7635 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7636                                    Expr **RHSExprs) {
7637   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7638   E = E->IgnoreImpCasts();
7639   E = E->IgnoreConversionOperator();
7640   E = E->IgnoreImpCasts();
7641   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7642     E = MTE->GetTemporaryExpr();
7643     E = E->IgnoreImpCasts();
7644   }
7645 
7646   // Built-in binary operator.
7647   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7648     if (IsArithmeticOp(OP->getOpcode())) {
7649       *Opcode = OP->getOpcode();
7650       *RHSExprs = OP->getRHS();
7651       return true;
7652     }
7653   }
7654 
7655   // Overloaded operator.
7656   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7657     if (Call->getNumArgs() != 2)
7658       return false;
7659 
7660     // Make sure this is really a binary operator that is safe to pass into
7661     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7662     OverloadedOperatorKind OO = Call->getOperator();
7663     if (OO < OO_Plus || OO > OO_Arrow ||
7664         OO == OO_PlusPlus || OO == OO_MinusMinus)
7665       return false;
7666 
7667     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7668     if (IsArithmeticOp(OpKind)) {
7669       *Opcode = OpKind;
7670       *RHSExprs = Call->getArg(1);
7671       return true;
7672     }
7673   }
7674 
7675   return false;
7676 }
7677 
7678 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7679 /// or is a logical expression such as (x==y) which has int type, but is
7680 /// commonly interpreted as boolean.
7681 static bool ExprLooksBoolean(Expr *E) {
7682   E = E->IgnoreParenImpCasts();
7683 
7684   if (E->getType()->isBooleanType())
7685     return true;
7686   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7687     return OP->isComparisonOp() || OP->isLogicalOp();
7688   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7689     return OP->getOpcode() == UO_LNot;
7690   if (E->getType()->isPointerType())
7691     return true;
7692   // FIXME: What about overloaded operator calls returning "unspecified boolean
7693   // type"s (commonly pointer-to-members)?
7694 
7695   return false;
7696 }
7697 
7698 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7699 /// and binary operator are mixed in a way that suggests the programmer assumed
7700 /// the conditional operator has higher precedence, for example:
7701 /// "int x = a + someBinaryCondition ? 1 : 2".
7702 static void DiagnoseConditionalPrecedence(Sema &Self,
7703                                           SourceLocation OpLoc,
7704                                           Expr *Condition,
7705                                           Expr *LHSExpr,
7706                                           Expr *RHSExpr) {
7707   BinaryOperatorKind CondOpcode;
7708   Expr *CondRHS;
7709 
7710   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7711     return;
7712   if (!ExprLooksBoolean(CondRHS))
7713     return;
7714 
7715   // The condition is an arithmetic binary expression, with a right-
7716   // hand side that looks boolean, so warn.
7717 
7718   unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
7719                         ? diag::warn_precedence_bitwise_conditional
7720                         : diag::warn_precedence_conditional;
7721 
7722   Self.Diag(OpLoc, DiagID)
7723       << Condition->getSourceRange()
7724       << BinaryOperator::getOpcodeStr(CondOpcode);
7725 
7726   SuggestParentheses(
7727       Self, OpLoc,
7728       Self.PDiag(diag::note_precedence_silence)
7729           << BinaryOperator::getOpcodeStr(CondOpcode),
7730       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7731 
7732   SuggestParentheses(Self, OpLoc,
7733                      Self.PDiag(diag::note_precedence_conditional_first),
7734                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7735 }
7736 
7737 /// Compute the nullability of a conditional expression.
7738 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7739                                               QualType LHSTy, QualType RHSTy,
7740                                               ASTContext &Ctx) {
7741   if (!ResTy->isAnyPointerType())
7742     return ResTy;
7743 
7744   auto GetNullability = [&Ctx](QualType Ty) {
7745     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7746     if (Kind)
7747       return *Kind;
7748     return NullabilityKind::Unspecified;
7749   };
7750 
7751   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7752   NullabilityKind MergedKind;
7753 
7754   // Compute nullability of a binary conditional expression.
7755   if (IsBin) {
7756     if (LHSKind == NullabilityKind::NonNull)
7757       MergedKind = NullabilityKind::NonNull;
7758     else
7759       MergedKind = RHSKind;
7760   // Compute nullability of a normal conditional expression.
7761   } else {
7762     if (LHSKind == NullabilityKind::Nullable ||
7763         RHSKind == NullabilityKind::Nullable)
7764       MergedKind = NullabilityKind::Nullable;
7765     else if (LHSKind == NullabilityKind::NonNull)
7766       MergedKind = RHSKind;
7767     else if (RHSKind == NullabilityKind::NonNull)
7768       MergedKind = LHSKind;
7769     else
7770       MergedKind = NullabilityKind::Unspecified;
7771   }
7772 
7773   // Return if ResTy already has the correct nullability.
7774   if (GetNullability(ResTy) == MergedKind)
7775     return ResTy;
7776 
7777   // Strip all nullability from ResTy.
7778   while (ResTy->getNullability(Ctx))
7779     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7780 
7781   // Create a new AttributedType with the new nullability kind.
7782   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7783   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7784 }
7785 
7786 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7787 /// in the case of a the GNU conditional expr extension.
7788 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7789                                     SourceLocation ColonLoc,
7790                                     Expr *CondExpr, Expr *LHSExpr,
7791                                     Expr *RHSExpr) {
7792   if (!getLangOpts().CPlusPlus) {
7793     // C cannot handle TypoExpr nodes in the condition because it
7794     // doesn't handle dependent types properly, so make sure any TypoExprs have
7795     // been dealt with before checking the operands.
7796     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7797     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7798     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7799 
7800     if (!CondResult.isUsable())
7801       return ExprError();
7802 
7803     if (LHSExpr) {
7804       if (!LHSResult.isUsable())
7805         return ExprError();
7806     }
7807 
7808     if (!RHSResult.isUsable())
7809       return ExprError();
7810 
7811     CondExpr = CondResult.get();
7812     LHSExpr = LHSResult.get();
7813     RHSExpr = RHSResult.get();
7814   }
7815 
7816   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7817   // was the condition.
7818   OpaqueValueExpr *opaqueValue = nullptr;
7819   Expr *commonExpr = nullptr;
7820   if (!LHSExpr) {
7821     commonExpr = CondExpr;
7822     // Lower out placeholder types first.  This is important so that we don't
7823     // try to capture a placeholder. This happens in few cases in C++; such
7824     // as Objective-C++'s dictionary subscripting syntax.
7825     if (commonExpr->hasPlaceholderType()) {
7826       ExprResult result = CheckPlaceholderExpr(commonExpr);
7827       if (!result.isUsable()) return ExprError();
7828       commonExpr = result.get();
7829     }
7830     // We usually want to apply unary conversions *before* saving, except
7831     // in the special case of a C++ l-value conditional.
7832     if (!(getLangOpts().CPlusPlus
7833           && !commonExpr->isTypeDependent()
7834           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7835           && commonExpr->isGLValue()
7836           && commonExpr->isOrdinaryOrBitFieldObject()
7837           && RHSExpr->isOrdinaryOrBitFieldObject()
7838           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7839       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7840       if (commonRes.isInvalid())
7841         return ExprError();
7842       commonExpr = commonRes.get();
7843     }
7844 
7845     // If the common expression is a class or array prvalue, materialize it
7846     // so that we can safely refer to it multiple times.
7847     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7848                                    commonExpr->getType()->isArrayType())) {
7849       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7850       if (MatExpr.isInvalid())
7851         return ExprError();
7852       commonExpr = MatExpr.get();
7853     }
7854 
7855     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7856                                                 commonExpr->getType(),
7857                                                 commonExpr->getValueKind(),
7858                                                 commonExpr->getObjectKind(),
7859                                                 commonExpr);
7860     LHSExpr = CondExpr = opaqueValue;
7861   }
7862 
7863   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7864   ExprValueKind VK = VK_RValue;
7865   ExprObjectKind OK = OK_Ordinary;
7866   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7867   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7868                                              VK, OK, QuestionLoc);
7869   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7870       RHS.isInvalid())
7871     return ExprError();
7872 
7873   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7874                                 RHS.get());
7875 
7876   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7877 
7878   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7879                                          Context);
7880 
7881   if (!commonExpr)
7882     return new (Context)
7883         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7884                             RHS.get(), result, VK, OK);
7885 
7886   return new (Context) BinaryConditionalOperator(
7887       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7888       ColonLoc, result, VK, OK);
7889 }
7890 
7891 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7892 // being closely modeled after the C99 spec:-). The odd characteristic of this
7893 // routine is it effectively iqnores the qualifiers on the top level pointee.
7894 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7895 // FIXME: add a couple examples in this comment.
7896 static Sema::AssignConvertType
7897 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7898   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7899   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7900 
7901   // get the "pointed to" type (ignoring qualifiers at the top level)
7902   const Type *lhptee, *rhptee;
7903   Qualifiers lhq, rhq;
7904   std::tie(lhptee, lhq) =
7905       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7906   std::tie(rhptee, rhq) =
7907       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7908 
7909   Sema::AssignConvertType ConvTy = Sema::Compatible;
7910 
7911   // C99 6.5.16.1p1: This following citation is common to constraints
7912   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7913   // qualifiers of the type *pointed to* by the right;
7914 
7915   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7916   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7917       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7918     // Ignore lifetime for further calculation.
7919     lhq.removeObjCLifetime();
7920     rhq.removeObjCLifetime();
7921   }
7922 
7923   if (!lhq.compatiblyIncludes(rhq)) {
7924     // Treat address-space mismatches as fatal.
7925     if (!lhq.isAddressSpaceSupersetOf(rhq))
7926       return Sema::IncompatiblePointerDiscardsQualifiers;
7927 
7928     // It's okay to add or remove GC or lifetime qualifiers when converting to
7929     // and from void*.
7930     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7931                         .compatiblyIncludes(
7932                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7933              && (lhptee->isVoidType() || rhptee->isVoidType()))
7934       ; // keep old
7935 
7936     // Treat lifetime mismatches as fatal.
7937     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7938       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7939 
7940     // For GCC/MS compatibility, other qualifier mismatches are treated
7941     // as still compatible in C.
7942     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7943   }
7944 
7945   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7946   // incomplete type and the other is a pointer to a qualified or unqualified
7947   // version of void...
7948   if (lhptee->isVoidType()) {
7949     if (rhptee->isIncompleteOrObjectType())
7950       return ConvTy;
7951 
7952     // As an extension, we allow cast to/from void* to function pointer.
7953     assert(rhptee->isFunctionType());
7954     return Sema::FunctionVoidPointer;
7955   }
7956 
7957   if (rhptee->isVoidType()) {
7958     if (lhptee->isIncompleteOrObjectType())
7959       return ConvTy;
7960 
7961     // As an extension, we allow cast to/from void* to function pointer.
7962     assert(lhptee->isFunctionType());
7963     return Sema::FunctionVoidPointer;
7964   }
7965 
7966   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7967   // unqualified versions of compatible types, ...
7968   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7969   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7970     // Check if the pointee types are compatible ignoring the sign.
7971     // We explicitly check for char so that we catch "char" vs
7972     // "unsigned char" on systems where "char" is unsigned.
7973     if (lhptee->isCharType())
7974       ltrans = S.Context.UnsignedCharTy;
7975     else if (lhptee->hasSignedIntegerRepresentation())
7976       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7977 
7978     if (rhptee->isCharType())
7979       rtrans = S.Context.UnsignedCharTy;
7980     else if (rhptee->hasSignedIntegerRepresentation())
7981       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7982 
7983     if (ltrans == rtrans) {
7984       // Types are compatible ignoring the sign. Qualifier incompatibility
7985       // takes priority over sign incompatibility because the sign
7986       // warning can be disabled.
7987       if (ConvTy != Sema::Compatible)
7988         return ConvTy;
7989 
7990       return Sema::IncompatiblePointerSign;
7991     }
7992 
7993     // If we are a multi-level pointer, it's possible that our issue is simply
7994     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7995     // the eventual target type is the same and the pointers have the same
7996     // level of indirection, this must be the issue.
7997     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7998       do {
7999         std::tie(lhptee, lhq) =
8000           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8001         std::tie(rhptee, rhq) =
8002           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8003 
8004         // Inconsistent address spaces at this point is invalid, even if the
8005         // address spaces would be compatible.
8006         // FIXME: This doesn't catch address space mismatches for pointers of
8007         // different nesting levels, like:
8008         //   __local int *** a;
8009         //   int ** b = a;
8010         // It's not clear how to actually determine when such pointers are
8011         // invalidly incompatible.
8012         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8013           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8014 
8015       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8016 
8017       if (lhptee == rhptee)
8018         return Sema::IncompatibleNestedPointerQualifiers;
8019     }
8020 
8021     // General pointer incompatibility takes priority over qualifiers.
8022     return Sema::IncompatiblePointer;
8023   }
8024   if (!S.getLangOpts().CPlusPlus &&
8025       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8026     return Sema::IncompatiblePointer;
8027   return ConvTy;
8028 }
8029 
8030 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8031 /// block pointer types are compatible or whether a block and normal pointer
8032 /// are compatible. It is more restrict than comparing two function pointer
8033 // types.
8034 static Sema::AssignConvertType
8035 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8036                                     QualType RHSType) {
8037   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8038   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8039 
8040   QualType lhptee, rhptee;
8041 
8042   // get the "pointed to" type (ignoring qualifiers at the top level)
8043   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8044   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8045 
8046   // In C++, the types have to match exactly.
8047   if (S.getLangOpts().CPlusPlus)
8048     return Sema::IncompatibleBlockPointer;
8049 
8050   Sema::AssignConvertType ConvTy = Sema::Compatible;
8051 
8052   // For blocks we enforce that qualifiers are identical.
8053   Qualifiers LQuals = lhptee.getLocalQualifiers();
8054   Qualifiers RQuals = rhptee.getLocalQualifiers();
8055   if (S.getLangOpts().OpenCL) {
8056     LQuals.removeAddressSpace();
8057     RQuals.removeAddressSpace();
8058   }
8059   if (LQuals != RQuals)
8060     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8061 
8062   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8063   // assignment.
8064   // The current behavior is similar to C++ lambdas. A block might be
8065   // assigned to a variable iff its return type and parameters are compatible
8066   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8067   // an assignment. Presumably it should behave in way that a function pointer
8068   // assignment does in C, so for each parameter and return type:
8069   //  * CVR and address space of LHS should be a superset of CVR and address
8070   //  space of RHS.
8071   //  * unqualified types should be compatible.
8072   if (S.getLangOpts().OpenCL) {
8073     if (!S.Context.typesAreBlockPointerCompatible(
8074             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8075             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8076       return Sema::IncompatibleBlockPointer;
8077   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8078     return Sema::IncompatibleBlockPointer;
8079 
8080   return ConvTy;
8081 }
8082 
8083 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8084 /// for assignment compatibility.
8085 static Sema::AssignConvertType
8086 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8087                                    QualType RHSType) {
8088   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8089   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8090 
8091   if (LHSType->isObjCBuiltinType()) {
8092     // Class is not compatible with ObjC object pointers.
8093     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8094         !RHSType->isObjCQualifiedClassType())
8095       return Sema::IncompatiblePointer;
8096     return Sema::Compatible;
8097   }
8098   if (RHSType->isObjCBuiltinType()) {
8099     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8100         !LHSType->isObjCQualifiedClassType())
8101       return Sema::IncompatiblePointer;
8102     return Sema::Compatible;
8103   }
8104   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8105   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8106 
8107   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8108       // make an exception for id<P>
8109       !LHSType->isObjCQualifiedIdType())
8110     return Sema::CompatiblePointerDiscardsQualifiers;
8111 
8112   if (S.Context.typesAreCompatible(LHSType, RHSType))
8113     return Sema::Compatible;
8114   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8115     return Sema::IncompatibleObjCQualifiedId;
8116   return Sema::IncompatiblePointer;
8117 }
8118 
8119 Sema::AssignConvertType
8120 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8121                                  QualType LHSType, QualType RHSType) {
8122   // Fake up an opaque expression.  We don't actually care about what
8123   // cast operations are required, so if CheckAssignmentConstraints
8124   // adds casts to this they'll be wasted, but fortunately that doesn't
8125   // usually happen on valid code.
8126   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8127   ExprResult RHSPtr = &RHSExpr;
8128   CastKind K;
8129 
8130   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8131 }
8132 
8133 /// This helper function returns true if QT is a vector type that has element
8134 /// type ElementType.
8135 static bool isVector(QualType QT, QualType ElementType) {
8136   if (const VectorType *VT = QT->getAs<VectorType>())
8137     return VT->getElementType() == ElementType;
8138   return false;
8139 }
8140 
8141 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8142 /// has code to accommodate several GCC extensions when type checking
8143 /// pointers. Here are some objectionable examples that GCC considers warnings:
8144 ///
8145 ///  int a, *pint;
8146 ///  short *pshort;
8147 ///  struct foo *pfoo;
8148 ///
8149 ///  pint = pshort; // warning: assignment from incompatible pointer type
8150 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8151 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8152 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8153 ///
8154 /// As a result, the code for dealing with pointers is more complex than the
8155 /// C99 spec dictates.
8156 ///
8157 /// Sets 'Kind' for any result kind except Incompatible.
8158 Sema::AssignConvertType
8159 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8160                                  CastKind &Kind, bool ConvertRHS) {
8161   QualType RHSType = RHS.get()->getType();
8162   QualType OrigLHSType = LHSType;
8163 
8164   // Get canonical types.  We're not formatting these types, just comparing
8165   // them.
8166   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8167   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8168 
8169   // Common case: no conversion required.
8170   if (LHSType == RHSType) {
8171     Kind = CK_NoOp;
8172     return Compatible;
8173   }
8174 
8175   // If we have an atomic type, try a non-atomic assignment, then just add an
8176   // atomic qualification step.
8177   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8178     Sema::AssignConvertType result =
8179       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8180     if (result != Compatible)
8181       return result;
8182     if (Kind != CK_NoOp && ConvertRHS)
8183       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8184     Kind = CK_NonAtomicToAtomic;
8185     return Compatible;
8186   }
8187 
8188   // If the left-hand side is a reference type, then we are in a
8189   // (rare!) case where we've allowed the use of references in C,
8190   // e.g., as a parameter type in a built-in function. In this case,
8191   // just make sure that the type referenced is compatible with the
8192   // right-hand side type. The caller is responsible for adjusting
8193   // LHSType so that the resulting expression does not have reference
8194   // type.
8195   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8196     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8197       Kind = CK_LValueBitCast;
8198       return Compatible;
8199     }
8200     return Incompatible;
8201   }
8202 
8203   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8204   // to the same ExtVector type.
8205   if (LHSType->isExtVectorType()) {
8206     if (RHSType->isExtVectorType())
8207       return Incompatible;
8208     if (RHSType->isArithmeticType()) {
8209       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8210       if (ConvertRHS)
8211         RHS = prepareVectorSplat(LHSType, RHS.get());
8212       Kind = CK_VectorSplat;
8213       return Compatible;
8214     }
8215   }
8216 
8217   // Conversions to or from vector type.
8218   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8219     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8220       // Allow assignments of an AltiVec vector type to an equivalent GCC
8221       // vector type and vice versa
8222       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8223         Kind = CK_BitCast;
8224         return Compatible;
8225       }
8226 
8227       // If we are allowing lax vector conversions, and LHS and RHS are both
8228       // vectors, the total size only needs to be the same. This is a bitcast;
8229       // no bits are changed but the result type is different.
8230       if (isLaxVectorConversion(RHSType, LHSType)) {
8231         Kind = CK_BitCast;
8232         return IncompatibleVectors;
8233       }
8234     }
8235 
8236     // When the RHS comes from another lax conversion (e.g. binops between
8237     // scalars and vectors) the result is canonicalized as a vector. When the
8238     // LHS is also a vector, the lax is allowed by the condition above. Handle
8239     // the case where LHS is a scalar.
8240     if (LHSType->isScalarType()) {
8241       const VectorType *VecType = RHSType->getAs<VectorType>();
8242       if (VecType && VecType->getNumElements() == 1 &&
8243           isLaxVectorConversion(RHSType, LHSType)) {
8244         ExprResult *VecExpr = &RHS;
8245         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8246         Kind = CK_BitCast;
8247         return Compatible;
8248       }
8249     }
8250 
8251     return Incompatible;
8252   }
8253 
8254   // Diagnose attempts to convert between __float128 and long double where
8255   // such conversions currently can't be handled.
8256   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8257     return Incompatible;
8258 
8259   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8260   // discards the imaginary part.
8261   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8262       !LHSType->getAs<ComplexType>())
8263     return Incompatible;
8264 
8265   // Arithmetic conversions.
8266   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8267       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8268     if (ConvertRHS)
8269       Kind = PrepareScalarCast(RHS, LHSType);
8270     return Compatible;
8271   }
8272 
8273   // Conversions to normal pointers.
8274   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8275     // U* -> T*
8276     if (isa<PointerType>(RHSType)) {
8277       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8278       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8279       if (AddrSpaceL != AddrSpaceR)
8280         Kind = CK_AddressSpaceConversion;
8281       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8282         Kind = CK_NoOp;
8283       else
8284         Kind = CK_BitCast;
8285       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8286     }
8287 
8288     // int -> T*
8289     if (RHSType->isIntegerType()) {
8290       Kind = CK_IntegralToPointer; // FIXME: null?
8291       return IntToPointer;
8292     }
8293 
8294     // C pointers are not compatible with ObjC object pointers,
8295     // with two exceptions:
8296     if (isa<ObjCObjectPointerType>(RHSType)) {
8297       //  - conversions to void*
8298       if (LHSPointer->getPointeeType()->isVoidType()) {
8299         Kind = CK_BitCast;
8300         return Compatible;
8301       }
8302 
8303       //  - conversions from 'Class' to the redefinition type
8304       if (RHSType->isObjCClassType() &&
8305           Context.hasSameType(LHSType,
8306                               Context.getObjCClassRedefinitionType())) {
8307         Kind = CK_BitCast;
8308         return Compatible;
8309       }
8310 
8311       Kind = CK_BitCast;
8312       return IncompatiblePointer;
8313     }
8314 
8315     // U^ -> void*
8316     if (RHSType->getAs<BlockPointerType>()) {
8317       if (LHSPointer->getPointeeType()->isVoidType()) {
8318         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8319         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8320                                 ->getPointeeType()
8321                                 .getAddressSpace();
8322         Kind =
8323             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8324         return Compatible;
8325       }
8326     }
8327 
8328     return Incompatible;
8329   }
8330 
8331   // Conversions to block pointers.
8332   if (isa<BlockPointerType>(LHSType)) {
8333     // U^ -> T^
8334     if (RHSType->isBlockPointerType()) {
8335       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8336                               ->getPointeeType()
8337                               .getAddressSpace();
8338       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8339                               ->getPointeeType()
8340                               .getAddressSpace();
8341       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8342       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8343     }
8344 
8345     // int or null -> T^
8346     if (RHSType->isIntegerType()) {
8347       Kind = CK_IntegralToPointer; // FIXME: null
8348       return IntToBlockPointer;
8349     }
8350 
8351     // id -> T^
8352     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8353       Kind = CK_AnyPointerToBlockPointerCast;
8354       return Compatible;
8355     }
8356 
8357     // void* -> T^
8358     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8359       if (RHSPT->getPointeeType()->isVoidType()) {
8360         Kind = CK_AnyPointerToBlockPointerCast;
8361         return Compatible;
8362       }
8363 
8364     return Incompatible;
8365   }
8366 
8367   // Conversions to Objective-C pointers.
8368   if (isa<ObjCObjectPointerType>(LHSType)) {
8369     // A* -> B*
8370     if (RHSType->isObjCObjectPointerType()) {
8371       Kind = CK_BitCast;
8372       Sema::AssignConvertType result =
8373         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8374       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8375           result == Compatible &&
8376           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8377         result = IncompatibleObjCWeakRef;
8378       return result;
8379     }
8380 
8381     // int or null -> A*
8382     if (RHSType->isIntegerType()) {
8383       Kind = CK_IntegralToPointer; // FIXME: null
8384       return IntToPointer;
8385     }
8386 
8387     // In general, C pointers are not compatible with ObjC object pointers,
8388     // with two exceptions:
8389     if (isa<PointerType>(RHSType)) {
8390       Kind = CK_CPointerToObjCPointerCast;
8391 
8392       //  - conversions from 'void*'
8393       if (RHSType->isVoidPointerType()) {
8394         return Compatible;
8395       }
8396 
8397       //  - conversions to 'Class' from its redefinition type
8398       if (LHSType->isObjCClassType() &&
8399           Context.hasSameType(RHSType,
8400                               Context.getObjCClassRedefinitionType())) {
8401         return Compatible;
8402       }
8403 
8404       return IncompatiblePointer;
8405     }
8406 
8407     // Only under strict condition T^ is compatible with an Objective-C pointer.
8408     if (RHSType->isBlockPointerType() &&
8409         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8410       if (ConvertRHS)
8411         maybeExtendBlockObject(RHS);
8412       Kind = CK_BlockPointerToObjCPointerCast;
8413       return Compatible;
8414     }
8415 
8416     return Incompatible;
8417   }
8418 
8419   // Conversions from pointers that are not covered by the above.
8420   if (isa<PointerType>(RHSType)) {
8421     // T* -> _Bool
8422     if (LHSType == Context.BoolTy) {
8423       Kind = CK_PointerToBoolean;
8424       return Compatible;
8425     }
8426 
8427     // T* -> int
8428     if (LHSType->isIntegerType()) {
8429       Kind = CK_PointerToIntegral;
8430       return PointerToInt;
8431     }
8432 
8433     return Incompatible;
8434   }
8435 
8436   // Conversions from Objective-C pointers that are not covered by the above.
8437   if (isa<ObjCObjectPointerType>(RHSType)) {
8438     // T* -> _Bool
8439     if (LHSType == Context.BoolTy) {
8440       Kind = CK_PointerToBoolean;
8441       return Compatible;
8442     }
8443 
8444     // T* -> int
8445     if (LHSType->isIntegerType()) {
8446       Kind = CK_PointerToIntegral;
8447       return PointerToInt;
8448     }
8449 
8450     return Incompatible;
8451   }
8452 
8453   // struct A -> struct B
8454   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8455     if (Context.typesAreCompatible(LHSType, RHSType)) {
8456       Kind = CK_NoOp;
8457       return Compatible;
8458     }
8459   }
8460 
8461   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8462     Kind = CK_IntToOCLSampler;
8463     return Compatible;
8464   }
8465 
8466   return Incompatible;
8467 }
8468 
8469 /// Constructs a transparent union from an expression that is
8470 /// used to initialize the transparent union.
8471 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8472                                       ExprResult &EResult, QualType UnionType,
8473                                       FieldDecl *Field) {
8474   // Build an initializer list that designates the appropriate member
8475   // of the transparent union.
8476   Expr *E = EResult.get();
8477   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8478                                                    E, SourceLocation());
8479   Initializer->setType(UnionType);
8480   Initializer->setInitializedFieldInUnion(Field);
8481 
8482   // Build a compound literal constructing a value of the transparent
8483   // union type from this initializer list.
8484   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8485   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8486                                         VK_RValue, Initializer, false);
8487 }
8488 
8489 Sema::AssignConvertType
8490 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8491                                                ExprResult &RHS) {
8492   QualType RHSType = RHS.get()->getType();
8493 
8494   // If the ArgType is a Union type, we want to handle a potential
8495   // transparent_union GCC extension.
8496   const RecordType *UT = ArgType->getAsUnionType();
8497   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8498     return Incompatible;
8499 
8500   // The field to initialize within the transparent union.
8501   RecordDecl *UD = UT->getDecl();
8502   FieldDecl *InitField = nullptr;
8503   // It's compatible if the expression matches any of the fields.
8504   for (auto *it : UD->fields()) {
8505     if (it->getType()->isPointerType()) {
8506       // If the transparent union contains a pointer type, we allow:
8507       // 1) void pointer
8508       // 2) null pointer constant
8509       if (RHSType->isPointerType())
8510         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8511           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8512           InitField = it;
8513           break;
8514         }
8515 
8516       if (RHS.get()->isNullPointerConstant(Context,
8517                                            Expr::NPC_ValueDependentIsNull)) {
8518         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8519                                 CK_NullToPointer);
8520         InitField = it;
8521         break;
8522       }
8523     }
8524 
8525     CastKind Kind;
8526     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8527           == Compatible) {
8528       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8529       InitField = it;
8530       break;
8531     }
8532   }
8533 
8534   if (!InitField)
8535     return Incompatible;
8536 
8537   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8538   return Compatible;
8539 }
8540 
8541 Sema::AssignConvertType
8542 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8543                                        bool Diagnose,
8544                                        bool DiagnoseCFAudited,
8545                                        bool ConvertRHS) {
8546   // We need to be able to tell the caller whether we diagnosed a problem, if
8547   // they ask us to issue diagnostics.
8548   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8549 
8550   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8551   // we can't avoid *all* modifications at the moment, so we need some somewhere
8552   // to put the updated value.
8553   ExprResult LocalRHS = CallerRHS;
8554   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8555 
8556   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8557     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8558       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8559           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8560         Diag(RHS.get()->getExprLoc(),
8561              diag::warn_noderef_to_dereferenceable_pointer)
8562             << RHS.get()->getSourceRange();
8563       }
8564     }
8565   }
8566 
8567   if (getLangOpts().CPlusPlus) {
8568     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8569       // C++ 5.17p3: If the left operand is not of class type, the
8570       // expression is implicitly converted (C++ 4) to the
8571       // cv-unqualified type of the left operand.
8572       QualType RHSType = RHS.get()->getType();
8573       if (Diagnose) {
8574         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8575                                         AA_Assigning);
8576       } else {
8577         ImplicitConversionSequence ICS =
8578             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8579                                   /*SuppressUserConversions=*/false,
8580                                   /*AllowExplicit=*/false,
8581                                   /*InOverloadResolution=*/false,
8582                                   /*CStyle=*/false,
8583                                   /*AllowObjCWritebackConversion=*/false);
8584         if (ICS.isFailure())
8585           return Incompatible;
8586         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8587                                         ICS, AA_Assigning);
8588       }
8589       if (RHS.isInvalid())
8590         return Incompatible;
8591       Sema::AssignConvertType result = Compatible;
8592       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8593           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8594         result = IncompatibleObjCWeakRef;
8595       return result;
8596     }
8597 
8598     // FIXME: Currently, we fall through and treat C++ classes like C
8599     // structures.
8600     // FIXME: We also fall through for atomics; not sure what should
8601     // happen there, though.
8602   } else if (RHS.get()->getType() == Context.OverloadTy) {
8603     // As a set of extensions to C, we support overloading on functions. These
8604     // functions need to be resolved here.
8605     DeclAccessPair DAP;
8606     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8607             RHS.get(), LHSType, /*Complain=*/false, DAP))
8608       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8609     else
8610       return Incompatible;
8611   }
8612 
8613   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8614   // a null pointer constant.
8615   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8616        LHSType->isBlockPointerType()) &&
8617       RHS.get()->isNullPointerConstant(Context,
8618                                        Expr::NPC_ValueDependentIsNull)) {
8619     if (Diagnose || ConvertRHS) {
8620       CastKind Kind;
8621       CXXCastPath Path;
8622       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8623                              /*IgnoreBaseAccess=*/false, Diagnose);
8624       if (ConvertRHS)
8625         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8626     }
8627     return Compatible;
8628   }
8629 
8630   // OpenCL queue_t type assignment.
8631   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8632                                  Context, Expr::NPC_ValueDependentIsNull)) {
8633     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8634     return Compatible;
8635   }
8636 
8637   // This check seems unnatural, however it is necessary to ensure the proper
8638   // conversion of functions/arrays. If the conversion were done for all
8639   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8640   // expressions that suppress this implicit conversion (&, sizeof).
8641   //
8642   // Suppress this for references: C++ 8.5.3p5.
8643   if (!LHSType->isReferenceType()) {
8644     // FIXME: We potentially allocate here even if ConvertRHS is false.
8645     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8646     if (RHS.isInvalid())
8647       return Incompatible;
8648   }
8649   CastKind Kind;
8650   Sema::AssignConvertType result =
8651     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8652 
8653   // C99 6.5.16.1p2: The value of the right operand is converted to the
8654   // type of the assignment expression.
8655   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8656   // so that we can use references in built-in functions even in C.
8657   // The getNonReferenceType() call makes sure that the resulting expression
8658   // does not have reference type.
8659   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8660     QualType Ty = LHSType.getNonLValueExprType(Context);
8661     Expr *E = RHS.get();
8662 
8663     // Check for various Objective-C errors. If we are not reporting
8664     // diagnostics and just checking for errors, e.g., during overload
8665     // resolution, return Incompatible to indicate the failure.
8666     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8667         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8668                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8669       if (!Diagnose)
8670         return Incompatible;
8671     }
8672     if (getLangOpts().ObjC &&
8673         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8674                                            E->getType(), E, Diagnose) ||
8675          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8676       if (!Diagnose)
8677         return Incompatible;
8678       // Replace the expression with a corrected version and continue so we
8679       // can find further errors.
8680       RHS = E;
8681       return Compatible;
8682     }
8683 
8684     if (ConvertRHS)
8685       RHS = ImpCastExprToType(E, Ty, Kind);
8686   }
8687 
8688   return result;
8689 }
8690 
8691 namespace {
8692 /// The original operand to an operator, prior to the application of the usual
8693 /// arithmetic conversions and converting the arguments of a builtin operator
8694 /// candidate.
8695 struct OriginalOperand {
8696   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8697     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8698       Op = MTE->GetTemporaryExpr();
8699     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8700       Op = BTE->getSubExpr();
8701     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8702       Orig = ICE->getSubExprAsWritten();
8703       Conversion = ICE->getConversionFunction();
8704     }
8705   }
8706 
8707   QualType getType() const { return Orig->getType(); }
8708 
8709   Expr *Orig;
8710   NamedDecl *Conversion;
8711 };
8712 }
8713 
8714 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8715                                ExprResult &RHS) {
8716   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8717 
8718   Diag(Loc, diag::err_typecheck_invalid_operands)
8719     << OrigLHS.getType() << OrigRHS.getType()
8720     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8721 
8722   // If a user-defined conversion was applied to either of the operands prior
8723   // to applying the built-in operator rules, tell the user about it.
8724   if (OrigLHS.Conversion) {
8725     Diag(OrigLHS.Conversion->getLocation(),
8726          diag::note_typecheck_invalid_operands_converted)
8727       << 0 << LHS.get()->getType();
8728   }
8729   if (OrigRHS.Conversion) {
8730     Diag(OrigRHS.Conversion->getLocation(),
8731          diag::note_typecheck_invalid_operands_converted)
8732       << 1 << RHS.get()->getType();
8733   }
8734 
8735   return QualType();
8736 }
8737 
8738 // Diagnose cases where a scalar was implicitly converted to a vector and
8739 // diagnose the underlying types. Otherwise, diagnose the error
8740 // as invalid vector logical operands for non-C++ cases.
8741 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8742                                             ExprResult &RHS) {
8743   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8744   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8745 
8746   bool LHSNatVec = LHSType->isVectorType();
8747   bool RHSNatVec = RHSType->isVectorType();
8748 
8749   if (!(LHSNatVec && RHSNatVec)) {
8750     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8751     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8752     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8753         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8754         << Vector->getSourceRange();
8755     return QualType();
8756   }
8757 
8758   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8759       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8760       << RHS.get()->getSourceRange();
8761 
8762   return QualType();
8763 }
8764 
8765 /// Try to convert a value of non-vector type to a vector type by converting
8766 /// the type to the element type of the vector and then performing a splat.
8767 /// If the language is OpenCL, we only use conversions that promote scalar
8768 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8769 /// for float->int.
8770 ///
8771 /// OpenCL V2.0 6.2.6.p2:
8772 /// An error shall occur if any scalar operand type has greater rank
8773 /// than the type of the vector element.
8774 ///
8775 /// \param scalar - if non-null, actually perform the conversions
8776 /// \return true if the operation fails (but without diagnosing the failure)
8777 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8778                                      QualType scalarTy,
8779                                      QualType vectorEltTy,
8780                                      QualType vectorTy,
8781                                      unsigned &DiagID) {
8782   // The conversion to apply to the scalar before splatting it,
8783   // if necessary.
8784   CastKind scalarCast = CK_NoOp;
8785 
8786   if (vectorEltTy->isIntegralType(S.Context)) {
8787     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8788         (scalarTy->isIntegerType() &&
8789          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8790       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8791       return true;
8792     }
8793     if (!scalarTy->isIntegralType(S.Context))
8794       return true;
8795     scalarCast = CK_IntegralCast;
8796   } else if (vectorEltTy->isRealFloatingType()) {
8797     if (scalarTy->isRealFloatingType()) {
8798       if (S.getLangOpts().OpenCL &&
8799           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8800         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8801         return true;
8802       }
8803       scalarCast = CK_FloatingCast;
8804     }
8805     else if (scalarTy->isIntegralType(S.Context))
8806       scalarCast = CK_IntegralToFloating;
8807     else
8808       return true;
8809   } else {
8810     return true;
8811   }
8812 
8813   // Adjust scalar if desired.
8814   if (scalar) {
8815     if (scalarCast != CK_NoOp)
8816       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8817     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8818   }
8819   return false;
8820 }
8821 
8822 /// Convert vector E to a vector with the same number of elements but different
8823 /// element type.
8824 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8825   const auto *VecTy = E->getType()->getAs<VectorType>();
8826   assert(VecTy && "Expression E must be a vector");
8827   QualType NewVecTy = S.Context.getVectorType(ElementType,
8828                                               VecTy->getNumElements(),
8829                                               VecTy->getVectorKind());
8830 
8831   // Look through the implicit cast. Return the subexpression if its type is
8832   // NewVecTy.
8833   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8834     if (ICE->getSubExpr()->getType() == NewVecTy)
8835       return ICE->getSubExpr();
8836 
8837   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8838   return S.ImpCastExprToType(E, NewVecTy, Cast);
8839 }
8840 
8841 /// Test if a (constant) integer Int can be casted to another integer type
8842 /// IntTy without losing precision.
8843 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8844                                       QualType OtherIntTy) {
8845   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8846 
8847   // Reject cases where the value of the Int is unknown as that would
8848   // possibly cause truncation, but accept cases where the scalar can be
8849   // demoted without loss of precision.
8850   Expr::EvalResult EVResult;
8851   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8852   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8853   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8854   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8855 
8856   if (CstInt) {
8857     // If the scalar is constant and is of a higher order and has more active
8858     // bits that the vector element type, reject it.
8859     llvm::APSInt Result = EVResult.Val.getInt();
8860     unsigned NumBits = IntSigned
8861                            ? (Result.isNegative() ? Result.getMinSignedBits()
8862                                                   : Result.getActiveBits())
8863                            : Result.getActiveBits();
8864     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8865       return true;
8866 
8867     // If the signedness of the scalar type and the vector element type
8868     // differs and the number of bits is greater than that of the vector
8869     // element reject it.
8870     return (IntSigned != OtherIntSigned &&
8871             NumBits > S.Context.getIntWidth(OtherIntTy));
8872   }
8873 
8874   // Reject cases where the value of the scalar is not constant and it's
8875   // order is greater than that of the vector element type.
8876   return (Order < 0);
8877 }
8878 
8879 /// Test if a (constant) integer Int can be casted to floating point type
8880 /// FloatTy without losing precision.
8881 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8882                                      QualType FloatTy) {
8883   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8884 
8885   // Determine if the integer constant can be expressed as a floating point
8886   // number of the appropriate type.
8887   Expr::EvalResult EVResult;
8888   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8889 
8890   uint64_t Bits = 0;
8891   if (CstInt) {
8892     // Reject constants that would be truncated if they were converted to
8893     // the floating point type. Test by simple to/from conversion.
8894     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8895     //        could be avoided if there was a convertFromAPInt method
8896     //        which could signal back if implicit truncation occurred.
8897     llvm::APSInt Result = EVResult.Val.getInt();
8898     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8899     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8900                            llvm::APFloat::rmTowardZero);
8901     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8902                              !IntTy->hasSignedIntegerRepresentation());
8903     bool Ignored = false;
8904     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8905                            &Ignored);
8906     if (Result != ConvertBack)
8907       return true;
8908   } else {
8909     // Reject types that cannot be fully encoded into the mantissa of
8910     // the float.
8911     Bits = S.Context.getTypeSize(IntTy);
8912     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8913         S.Context.getFloatTypeSemantics(FloatTy));
8914     if (Bits > FloatPrec)
8915       return true;
8916   }
8917 
8918   return false;
8919 }
8920 
8921 /// Attempt to convert and splat Scalar into a vector whose types matches
8922 /// Vector following GCC conversion rules. The rule is that implicit
8923 /// conversion can occur when Scalar can be casted to match Vector's element
8924 /// type without causing truncation of Scalar.
8925 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8926                                         ExprResult *Vector) {
8927   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8928   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8929   const VectorType *VT = VectorTy->getAs<VectorType>();
8930 
8931   assert(!isa<ExtVectorType>(VT) &&
8932          "ExtVectorTypes should not be handled here!");
8933 
8934   QualType VectorEltTy = VT->getElementType();
8935 
8936   // Reject cases where the vector element type or the scalar element type are
8937   // not integral or floating point types.
8938   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8939     return true;
8940 
8941   // The conversion to apply to the scalar before splatting it,
8942   // if necessary.
8943   CastKind ScalarCast = CK_NoOp;
8944 
8945   // Accept cases where the vector elements are integers and the scalar is
8946   // an integer.
8947   // FIXME: Notionally if the scalar was a floating point value with a precise
8948   //        integral representation, we could cast it to an appropriate integer
8949   //        type and then perform the rest of the checks here. GCC will perform
8950   //        this conversion in some cases as determined by the input language.
8951   //        We should accept it on a language independent basis.
8952   if (VectorEltTy->isIntegralType(S.Context) &&
8953       ScalarTy->isIntegralType(S.Context) &&
8954       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8955 
8956     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8957       return true;
8958 
8959     ScalarCast = CK_IntegralCast;
8960   } else if (VectorEltTy->isRealFloatingType()) {
8961     if (ScalarTy->isRealFloatingType()) {
8962 
8963       // Reject cases where the scalar type is not a constant and has a higher
8964       // Order than the vector element type.
8965       llvm::APFloat Result(0.0);
8966       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8967       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8968       if (!CstScalar && Order < 0)
8969         return true;
8970 
8971       // If the scalar cannot be safely casted to the vector element type,
8972       // reject it.
8973       if (CstScalar) {
8974         bool Truncated = false;
8975         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8976                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8977         if (Truncated)
8978           return true;
8979       }
8980 
8981       ScalarCast = CK_FloatingCast;
8982     } else if (ScalarTy->isIntegralType(S.Context)) {
8983       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8984         return true;
8985 
8986       ScalarCast = CK_IntegralToFloating;
8987     } else
8988       return true;
8989   }
8990 
8991   // Adjust scalar if desired.
8992   if (Scalar) {
8993     if (ScalarCast != CK_NoOp)
8994       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8995     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8996   }
8997   return false;
8998 }
8999 
9000 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9001                                    SourceLocation Loc, bool IsCompAssign,
9002                                    bool AllowBothBool,
9003                                    bool AllowBoolConversions) {
9004   if (!IsCompAssign) {
9005     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9006     if (LHS.isInvalid())
9007       return QualType();
9008   }
9009   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9010   if (RHS.isInvalid())
9011     return QualType();
9012 
9013   // For conversion purposes, we ignore any qualifiers.
9014   // For example, "const float" and "float" are equivalent.
9015   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9016   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9017 
9018   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9019   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9020   assert(LHSVecType || RHSVecType);
9021 
9022   // AltiVec-style "vector bool op vector bool" combinations are allowed
9023   // for some operators but not others.
9024   if (!AllowBothBool &&
9025       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9026       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9027     return InvalidOperands(Loc, LHS, RHS);
9028 
9029   // If the vector types are identical, return.
9030   if (Context.hasSameType(LHSType, RHSType))
9031     return LHSType;
9032 
9033   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9034   if (LHSVecType && RHSVecType &&
9035       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9036     if (isa<ExtVectorType>(LHSVecType)) {
9037       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9038       return LHSType;
9039     }
9040 
9041     if (!IsCompAssign)
9042       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9043     return RHSType;
9044   }
9045 
9046   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9047   // can be mixed, with the result being the non-bool type.  The non-bool
9048   // operand must have integer element type.
9049   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9050       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9051       (Context.getTypeSize(LHSVecType->getElementType()) ==
9052        Context.getTypeSize(RHSVecType->getElementType()))) {
9053     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9054         LHSVecType->getElementType()->isIntegerType() &&
9055         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9056       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9057       return LHSType;
9058     }
9059     if (!IsCompAssign &&
9060         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9061         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9062         RHSVecType->getElementType()->isIntegerType()) {
9063       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9064       return RHSType;
9065     }
9066   }
9067 
9068   // If there's a vector type and a scalar, try to convert the scalar to
9069   // the vector element type and splat.
9070   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9071   if (!RHSVecType) {
9072     if (isa<ExtVectorType>(LHSVecType)) {
9073       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9074                                     LHSVecType->getElementType(), LHSType,
9075                                     DiagID))
9076         return LHSType;
9077     } else {
9078       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9079         return LHSType;
9080     }
9081   }
9082   if (!LHSVecType) {
9083     if (isa<ExtVectorType>(RHSVecType)) {
9084       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9085                                     LHSType, RHSVecType->getElementType(),
9086                                     RHSType, DiagID))
9087         return RHSType;
9088     } else {
9089       if (LHS.get()->getValueKind() == VK_LValue ||
9090           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9091         return RHSType;
9092     }
9093   }
9094 
9095   // FIXME: The code below also handles conversion between vectors and
9096   // non-scalars, we should break this down into fine grained specific checks
9097   // and emit proper diagnostics.
9098   QualType VecType = LHSVecType ? LHSType : RHSType;
9099   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9100   QualType OtherType = LHSVecType ? RHSType : LHSType;
9101   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9102   if (isLaxVectorConversion(OtherType, VecType)) {
9103     // If we're allowing lax vector conversions, only the total (data) size
9104     // needs to be the same. For non compound assignment, if one of the types is
9105     // scalar, the result is always the vector type.
9106     if (!IsCompAssign) {
9107       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9108       return VecType;
9109     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9110     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9111     // type. Note that this is already done by non-compound assignments in
9112     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9113     // <1 x T> -> T. The result is also a vector type.
9114     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9115                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9116       ExprResult *RHSExpr = &RHS;
9117       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9118       return VecType;
9119     }
9120   }
9121 
9122   // Okay, the expression is invalid.
9123 
9124   // If there's a non-vector, non-real operand, diagnose that.
9125   if ((!RHSVecType && !RHSType->isRealType()) ||
9126       (!LHSVecType && !LHSType->isRealType())) {
9127     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9128       << LHSType << RHSType
9129       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9130     return QualType();
9131   }
9132 
9133   // OpenCL V1.1 6.2.6.p1:
9134   // If the operands are of more than one vector type, then an error shall
9135   // occur. Implicit conversions between vector types are not permitted, per
9136   // section 6.2.1.
9137   if (getLangOpts().OpenCL &&
9138       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9139       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9140     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9141                                                            << RHSType;
9142     return QualType();
9143   }
9144 
9145 
9146   // If there is a vector type that is not a ExtVector and a scalar, we reach
9147   // this point if scalar could not be converted to the vector's element type
9148   // without truncation.
9149   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9150       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9151     QualType Scalar = LHSVecType ? RHSType : LHSType;
9152     QualType Vector = LHSVecType ? LHSType : RHSType;
9153     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9154     Diag(Loc,
9155          diag::err_typecheck_vector_not_convertable_implict_truncation)
9156         << ScalarOrVector << Scalar << Vector;
9157 
9158     return QualType();
9159   }
9160 
9161   // Otherwise, use the generic diagnostic.
9162   Diag(Loc, DiagID)
9163     << LHSType << RHSType
9164     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9165   return QualType();
9166 }
9167 
9168 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9169 // expression.  These are mainly cases where the null pointer is used as an
9170 // integer instead of a pointer.
9171 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9172                                 SourceLocation Loc, bool IsCompare) {
9173   // The canonical way to check for a GNU null is with isNullPointerConstant,
9174   // but we use a bit of a hack here for speed; this is a relatively
9175   // hot path, and isNullPointerConstant is slow.
9176   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9177   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9178 
9179   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9180 
9181   // Avoid analyzing cases where the result will either be invalid (and
9182   // diagnosed as such) or entirely valid and not something to warn about.
9183   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9184       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9185     return;
9186 
9187   // Comparison operations would not make sense with a null pointer no matter
9188   // what the other expression is.
9189   if (!IsCompare) {
9190     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9191         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9192         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9193     return;
9194   }
9195 
9196   // The rest of the operations only make sense with a null pointer
9197   // if the other expression is a pointer.
9198   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9199       NonNullType->canDecayToPointerType())
9200     return;
9201 
9202   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9203       << LHSNull /* LHS is NULL */ << NonNullType
9204       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9205 }
9206 
9207 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9208                                           SourceLocation Loc) {
9209   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9210   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9211   if (!LUE || !RUE)
9212     return;
9213   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9214       RUE->getKind() != UETT_SizeOf)
9215     return;
9216 
9217   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9218   QualType LHSTy = LHSArg->getType();
9219   QualType RHSTy;
9220 
9221   if (RUE->isArgumentType())
9222     RHSTy = RUE->getArgumentType();
9223   else
9224     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9225 
9226   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9227     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9228       return;
9229 
9230     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9231     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9232       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9233         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9234             << LHSArgDecl;
9235     }
9236   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9237     QualType ArrayElemTy = ArrayTy->getElementType();
9238     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9239         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9240         ArrayElemTy->isCharType() ||
9241         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9242       return;
9243     S.Diag(Loc, diag::warn_division_sizeof_array)
9244         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9245     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9246       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9247         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9248             << LHSArgDecl;
9249     }
9250 
9251     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9252   }
9253 }
9254 
9255 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9256                                                ExprResult &RHS,
9257                                                SourceLocation Loc, bool IsDiv) {
9258   // Check for division/remainder by zero.
9259   Expr::EvalResult RHSValue;
9260   if (!RHS.get()->isValueDependent() &&
9261       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9262       RHSValue.Val.getInt() == 0)
9263     S.DiagRuntimeBehavior(Loc, RHS.get(),
9264                           S.PDiag(diag::warn_remainder_division_by_zero)
9265                             << IsDiv << RHS.get()->getSourceRange());
9266 }
9267 
9268 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9269                                            SourceLocation Loc,
9270                                            bool IsCompAssign, bool IsDiv) {
9271   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9272 
9273   if (LHS.get()->getType()->isVectorType() ||
9274       RHS.get()->getType()->isVectorType())
9275     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9276                                /*AllowBothBool*/getLangOpts().AltiVec,
9277                                /*AllowBoolConversions*/false);
9278 
9279   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9280   if (LHS.isInvalid() || RHS.isInvalid())
9281     return QualType();
9282 
9283 
9284   if (compType.isNull() || !compType->isArithmeticType())
9285     return InvalidOperands(Loc, LHS, RHS);
9286   if (IsDiv) {
9287     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9288     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9289   }
9290   return compType;
9291 }
9292 
9293 QualType Sema::CheckRemainderOperands(
9294   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9295   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9296 
9297   if (LHS.get()->getType()->isVectorType() ||
9298       RHS.get()->getType()->isVectorType()) {
9299     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9300         RHS.get()->getType()->hasIntegerRepresentation())
9301       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9302                                  /*AllowBothBool*/getLangOpts().AltiVec,
9303                                  /*AllowBoolConversions*/false);
9304     return InvalidOperands(Loc, LHS, RHS);
9305   }
9306 
9307   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9308   if (LHS.isInvalid() || RHS.isInvalid())
9309     return QualType();
9310 
9311   if (compType.isNull() || !compType->isIntegerType())
9312     return InvalidOperands(Loc, LHS, RHS);
9313   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9314   return compType;
9315 }
9316 
9317 /// Diagnose invalid arithmetic on two void pointers.
9318 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9319                                                 Expr *LHSExpr, Expr *RHSExpr) {
9320   S.Diag(Loc, S.getLangOpts().CPlusPlus
9321                 ? diag::err_typecheck_pointer_arith_void_type
9322                 : diag::ext_gnu_void_ptr)
9323     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9324                             << RHSExpr->getSourceRange();
9325 }
9326 
9327 /// Diagnose invalid arithmetic on a void pointer.
9328 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9329                                             Expr *Pointer) {
9330   S.Diag(Loc, S.getLangOpts().CPlusPlus
9331                 ? diag::err_typecheck_pointer_arith_void_type
9332                 : diag::ext_gnu_void_ptr)
9333     << 0 /* one pointer */ << Pointer->getSourceRange();
9334 }
9335 
9336 /// Diagnose invalid arithmetic on a null pointer.
9337 ///
9338 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9339 /// idiom, which we recognize as a GNU extension.
9340 ///
9341 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9342                                             Expr *Pointer, bool IsGNUIdiom) {
9343   if (IsGNUIdiom)
9344     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9345       << Pointer->getSourceRange();
9346   else
9347     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9348       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9349 }
9350 
9351 /// Diagnose invalid arithmetic on two function pointers.
9352 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9353                                                     Expr *LHS, Expr *RHS) {
9354   assert(LHS->getType()->isAnyPointerType());
9355   assert(RHS->getType()->isAnyPointerType());
9356   S.Diag(Loc, S.getLangOpts().CPlusPlus
9357                 ? diag::err_typecheck_pointer_arith_function_type
9358                 : diag::ext_gnu_ptr_func_arith)
9359     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9360     // We only show the second type if it differs from the first.
9361     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9362                                                    RHS->getType())
9363     << RHS->getType()->getPointeeType()
9364     << LHS->getSourceRange() << RHS->getSourceRange();
9365 }
9366 
9367 /// Diagnose invalid arithmetic on a function pointer.
9368 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9369                                                 Expr *Pointer) {
9370   assert(Pointer->getType()->isAnyPointerType());
9371   S.Diag(Loc, S.getLangOpts().CPlusPlus
9372                 ? diag::err_typecheck_pointer_arith_function_type
9373                 : diag::ext_gnu_ptr_func_arith)
9374     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9375     << 0 /* one pointer, so only one type */
9376     << Pointer->getSourceRange();
9377 }
9378 
9379 /// Emit error if Operand is incomplete pointer type
9380 ///
9381 /// \returns True if pointer has incomplete type
9382 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9383                                                  Expr *Operand) {
9384   QualType ResType = Operand->getType();
9385   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9386     ResType = ResAtomicType->getValueType();
9387 
9388   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9389   QualType PointeeTy = ResType->getPointeeType();
9390   return S.RequireCompleteType(Loc, PointeeTy,
9391                                diag::err_typecheck_arithmetic_incomplete_type,
9392                                PointeeTy, Operand->getSourceRange());
9393 }
9394 
9395 /// Check the validity of an arithmetic pointer operand.
9396 ///
9397 /// If the operand has pointer type, this code will check for pointer types
9398 /// which are invalid in arithmetic operations. These will be diagnosed
9399 /// appropriately, including whether or not the use is supported as an
9400 /// extension.
9401 ///
9402 /// \returns True when the operand is valid to use (even if as an extension).
9403 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9404                                             Expr *Operand) {
9405   QualType ResType = Operand->getType();
9406   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9407     ResType = ResAtomicType->getValueType();
9408 
9409   if (!ResType->isAnyPointerType()) return true;
9410 
9411   QualType PointeeTy = ResType->getPointeeType();
9412   if (PointeeTy->isVoidType()) {
9413     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9414     return !S.getLangOpts().CPlusPlus;
9415   }
9416   if (PointeeTy->isFunctionType()) {
9417     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9418     return !S.getLangOpts().CPlusPlus;
9419   }
9420 
9421   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9422 
9423   return true;
9424 }
9425 
9426 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9427 /// operands.
9428 ///
9429 /// This routine will diagnose any invalid arithmetic on pointer operands much
9430 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9431 /// for emitting a single diagnostic even for operations where both LHS and RHS
9432 /// are (potentially problematic) pointers.
9433 ///
9434 /// \returns True when the operand is valid to use (even if as an extension).
9435 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9436                                                 Expr *LHSExpr, Expr *RHSExpr) {
9437   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9438   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9439   if (!isLHSPointer && !isRHSPointer) return true;
9440 
9441   QualType LHSPointeeTy, RHSPointeeTy;
9442   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9443   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9444 
9445   // if both are pointers check if operation is valid wrt address spaces
9446   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9447     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9448     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9449     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9450       S.Diag(Loc,
9451              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9452           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9453           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9454       return false;
9455     }
9456   }
9457 
9458   // Check for arithmetic on pointers to incomplete types.
9459   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9460   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9461   if (isLHSVoidPtr || isRHSVoidPtr) {
9462     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9463     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9464     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9465 
9466     return !S.getLangOpts().CPlusPlus;
9467   }
9468 
9469   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9470   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9471   if (isLHSFuncPtr || isRHSFuncPtr) {
9472     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9473     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9474                                                                 RHSExpr);
9475     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9476 
9477     return !S.getLangOpts().CPlusPlus;
9478   }
9479 
9480   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9481     return false;
9482   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9483     return false;
9484 
9485   return true;
9486 }
9487 
9488 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9489 /// literal.
9490 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9491                                   Expr *LHSExpr, Expr *RHSExpr) {
9492   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9493   Expr* IndexExpr = RHSExpr;
9494   if (!StrExpr) {
9495     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9496     IndexExpr = LHSExpr;
9497   }
9498 
9499   bool IsStringPlusInt = StrExpr &&
9500       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9501   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9502     return;
9503 
9504   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9505   Self.Diag(OpLoc, diag::warn_string_plus_int)
9506       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9507 
9508   // Only print a fixit for "str" + int, not for int + "str".
9509   if (IndexExpr == RHSExpr) {
9510     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9511     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9512         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9513         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9514         << FixItHint::CreateInsertion(EndLoc, "]");
9515   } else
9516     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9517 }
9518 
9519 /// Emit a warning when adding a char literal to a string.
9520 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9521                                    Expr *LHSExpr, Expr *RHSExpr) {
9522   const Expr *StringRefExpr = LHSExpr;
9523   const CharacterLiteral *CharExpr =
9524       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9525 
9526   if (!CharExpr) {
9527     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9528     StringRefExpr = RHSExpr;
9529   }
9530 
9531   if (!CharExpr || !StringRefExpr)
9532     return;
9533 
9534   const QualType StringType = StringRefExpr->getType();
9535 
9536   // Return if not a PointerType.
9537   if (!StringType->isAnyPointerType())
9538     return;
9539 
9540   // Return if not a CharacterType.
9541   if (!StringType->getPointeeType()->isAnyCharacterType())
9542     return;
9543 
9544   ASTContext &Ctx = Self.getASTContext();
9545   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9546 
9547   const QualType CharType = CharExpr->getType();
9548   if (!CharType->isAnyCharacterType() &&
9549       CharType->isIntegerType() &&
9550       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9551     Self.Diag(OpLoc, diag::warn_string_plus_char)
9552         << DiagRange << Ctx.CharTy;
9553   } else {
9554     Self.Diag(OpLoc, diag::warn_string_plus_char)
9555         << DiagRange << CharExpr->getType();
9556   }
9557 
9558   // Only print a fixit for str + char, not for char + str.
9559   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9560     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9561     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9562         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9563         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9564         << FixItHint::CreateInsertion(EndLoc, "]");
9565   } else {
9566     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9567   }
9568 }
9569 
9570 /// Emit error when two pointers are incompatible.
9571 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9572                                            Expr *LHSExpr, Expr *RHSExpr) {
9573   assert(LHSExpr->getType()->isAnyPointerType());
9574   assert(RHSExpr->getType()->isAnyPointerType());
9575   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9576     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9577     << RHSExpr->getSourceRange();
9578 }
9579 
9580 // C99 6.5.6
9581 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9582                                      SourceLocation Loc, BinaryOperatorKind Opc,
9583                                      QualType* CompLHSTy) {
9584   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9585 
9586   if (LHS.get()->getType()->isVectorType() ||
9587       RHS.get()->getType()->isVectorType()) {
9588     QualType compType = CheckVectorOperands(
9589         LHS, RHS, Loc, CompLHSTy,
9590         /*AllowBothBool*/getLangOpts().AltiVec,
9591         /*AllowBoolConversions*/getLangOpts().ZVector);
9592     if (CompLHSTy) *CompLHSTy = compType;
9593     return compType;
9594   }
9595 
9596   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9597   if (LHS.isInvalid() || RHS.isInvalid())
9598     return QualType();
9599 
9600   // Diagnose "string literal" '+' int and string '+' "char literal".
9601   if (Opc == BO_Add) {
9602     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9603     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9604   }
9605 
9606   // handle the common case first (both operands are arithmetic).
9607   if (!compType.isNull() && compType->isArithmeticType()) {
9608     if (CompLHSTy) *CompLHSTy = compType;
9609     return compType;
9610   }
9611 
9612   // Type-checking.  Ultimately the pointer's going to be in PExp;
9613   // note that we bias towards the LHS being the pointer.
9614   Expr *PExp = LHS.get(), *IExp = RHS.get();
9615 
9616   bool isObjCPointer;
9617   if (PExp->getType()->isPointerType()) {
9618     isObjCPointer = false;
9619   } else if (PExp->getType()->isObjCObjectPointerType()) {
9620     isObjCPointer = true;
9621   } else {
9622     std::swap(PExp, IExp);
9623     if (PExp->getType()->isPointerType()) {
9624       isObjCPointer = false;
9625     } else if (PExp->getType()->isObjCObjectPointerType()) {
9626       isObjCPointer = true;
9627     } else {
9628       return InvalidOperands(Loc, LHS, RHS);
9629     }
9630   }
9631   assert(PExp->getType()->isAnyPointerType());
9632 
9633   if (!IExp->getType()->isIntegerType())
9634     return InvalidOperands(Loc, LHS, RHS);
9635 
9636   // Adding to a null pointer results in undefined behavior.
9637   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9638           Context, Expr::NPC_ValueDependentIsNotNull)) {
9639     // In C++ adding zero to a null pointer is defined.
9640     Expr::EvalResult KnownVal;
9641     if (!getLangOpts().CPlusPlus ||
9642         (!IExp->isValueDependent() &&
9643          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9644           KnownVal.Val.getInt() != 0))) {
9645       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9646       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9647           Context, BO_Add, PExp, IExp);
9648       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9649     }
9650   }
9651 
9652   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9653     return QualType();
9654 
9655   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9656     return QualType();
9657 
9658   // Check array bounds for pointer arithemtic
9659   CheckArrayAccess(PExp, IExp);
9660 
9661   if (CompLHSTy) {
9662     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9663     if (LHSTy.isNull()) {
9664       LHSTy = LHS.get()->getType();
9665       if (LHSTy->isPromotableIntegerType())
9666         LHSTy = Context.getPromotedIntegerType(LHSTy);
9667     }
9668     *CompLHSTy = LHSTy;
9669   }
9670 
9671   return PExp->getType();
9672 }
9673 
9674 // C99 6.5.6
9675 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9676                                         SourceLocation Loc,
9677                                         QualType* CompLHSTy) {
9678   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9679 
9680   if (LHS.get()->getType()->isVectorType() ||
9681       RHS.get()->getType()->isVectorType()) {
9682     QualType compType = CheckVectorOperands(
9683         LHS, RHS, Loc, CompLHSTy,
9684         /*AllowBothBool*/getLangOpts().AltiVec,
9685         /*AllowBoolConversions*/getLangOpts().ZVector);
9686     if (CompLHSTy) *CompLHSTy = compType;
9687     return compType;
9688   }
9689 
9690   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9691   if (LHS.isInvalid() || RHS.isInvalid())
9692     return QualType();
9693 
9694   // Enforce type constraints: C99 6.5.6p3.
9695 
9696   // Handle the common case first (both operands are arithmetic).
9697   if (!compType.isNull() && compType->isArithmeticType()) {
9698     if (CompLHSTy) *CompLHSTy = compType;
9699     return compType;
9700   }
9701 
9702   // Either ptr - int   or   ptr - ptr.
9703   if (LHS.get()->getType()->isAnyPointerType()) {
9704     QualType lpointee = LHS.get()->getType()->getPointeeType();
9705 
9706     // Diagnose bad cases where we step over interface counts.
9707     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9708         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9709       return QualType();
9710 
9711     // The result type of a pointer-int computation is the pointer type.
9712     if (RHS.get()->getType()->isIntegerType()) {
9713       // Subtracting from a null pointer should produce a warning.
9714       // The last argument to the diagnose call says this doesn't match the
9715       // GNU int-to-pointer idiom.
9716       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9717                                            Expr::NPC_ValueDependentIsNotNull)) {
9718         // In C++ adding zero to a null pointer is defined.
9719         Expr::EvalResult KnownVal;
9720         if (!getLangOpts().CPlusPlus ||
9721             (!RHS.get()->isValueDependent() &&
9722              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9723               KnownVal.Val.getInt() != 0))) {
9724           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9725         }
9726       }
9727 
9728       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9729         return QualType();
9730 
9731       // Check array bounds for pointer arithemtic
9732       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9733                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9734 
9735       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9736       return LHS.get()->getType();
9737     }
9738 
9739     // Handle pointer-pointer subtractions.
9740     if (const PointerType *RHSPTy
9741           = RHS.get()->getType()->getAs<PointerType>()) {
9742       QualType rpointee = RHSPTy->getPointeeType();
9743 
9744       if (getLangOpts().CPlusPlus) {
9745         // Pointee types must be the same: C++ [expr.add]
9746         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9747           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9748         }
9749       } else {
9750         // Pointee types must be compatible C99 6.5.6p3
9751         if (!Context.typesAreCompatible(
9752                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9753                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9754           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9755           return QualType();
9756         }
9757       }
9758 
9759       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9760                                                LHS.get(), RHS.get()))
9761         return QualType();
9762 
9763       // FIXME: Add warnings for nullptr - ptr.
9764 
9765       // The pointee type may have zero size.  As an extension, a structure or
9766       // union may have zero size or an array may have zero length.  In this
9767       // case subtraction does not make sense.
9768       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9769         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9770         if (ElementSize.isZero()) {
9771           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9772             << rpointee.getUnqualifiedType()
9773             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9774         }
9775       }
9776 
9777       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9778       return Context.getPointerDiffType();
9779     }
9780   }
9781 
9782   return InvalidOperands(Loc, LHS, RHS);
9783 }
9784 
9785 static bool isScopedEnumerationType(QualType T) {
9786   if (const EnumType *ET = T->getAs<EnumType>())
9787     return ET->getDecl()->isScoped();
9788   return false;
9789 }
9790 
9791 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9792                                    SourceLocation Loc, BinaryOperatorKind Opc,
9793                                    QualType LHSType) {
9794   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9795   // so skip remaining warnings as we don't want to modify values within Sema.
9796   if (S.getLangOpts().OpenCL)
9797     return;
9798 
9799   // Check right/shifter operand
9800   Expr::EvalResult RHSResult;
9801   if (RHS.get()->isValueDependent() ||
9802       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9803     return;
9804   llvm::APSInt Right = RHSResult.Val.getInt();
9805 
9806   if (Right.isNegative()) {
9807     S.DiagRuntimeBehavior(Loc, RHS.get(),
9808                           S.PDiag(diag::warn_shift_negative)
9809                             << RHS.get()->getSourceRange());
9810     return;
9811   }
9812   llvm::APInt LeftBits(Right.getBitWidth(),
9813                        S.Context.getTypeSize(LHS.get()->getType()));
9814   if (Right.uge(LeftBits)) {
9815     S.DiagRuntimeBehavior(Loc, RHS.get(),
9816                           S.PDiag(diag::warn_shift_gt_typewidth)
9817                             << RHS.get()->getSourceRange());
9818     return;
9819   }
9820   if (Opc != BO_Shl)
9821     return;
9822 
9823   // When left shifting an ICE which is signed, we can check for overflow which
9824   // according to C++ standards prior to C++2a has undefined behavior
9825   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9826   // more than the maximum value representable in the result type, so never
9827   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9828   // expression is still probably a bug.)
9829   Expr::EvalResult LHSResult;
9830   if (LHS.get()->isValueDependent() ||
9831       LHSType->hasUnsignedIntegerRepresentation() ||
9832       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9833     return;
9834   llvm::APSInt Left = LHSResult.Val.getInt();
9835 
9836   // If LHS does not have a signed type and non-negative value
9837   // then, the behavior is undefined before C++2a. Warn about it.
9838   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9839       !S.getLangOpts().CPlusPlus2a) {
9840     S.DiagRuntimeBehavior(Loc, LHS.get(),
9841                           S.PDiag(diag::warn_shift_lhs_negative)
9842                             << LHS.get()->getSourceRange());
9843     return;
9844   }
9845 
9846   llvm::APInt ResultBits =
9847       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9848   if (LeftBits.uge(ResultBits))
9849     return;
9850   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9851   Result = Result.shl(Right);
9852 
9853   // Print the bit representation of the signed integer as an unsigned
9854   // hexadecimal number.
9855   SmallString<40> HexResult;
9856   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9857 
9858   // If we are only missing a sign bit, this is less likely to result in actual
9859   // bugs -- if the result is cast back to an unsigned type, it will have the
9860   // expected value. Thus we place this behind a different warning that can be
9861   // turned off separately if needed.
9862   if (LeftBits == ResultBits - 1) {
9863     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9864         << HexResult << LHSType
9865         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9866     return;
9867   }
9868 
9869   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9870     << HexResult.str() << Result.getMinSignedBits() << LHSType
9871     << Left.getBitWidth() << LHS.get()->getSourceRange()
9872     << RHS.get()->getSourceRange();
9873 }
9874 
9875 /// Return the resulting type when a vector is shifted
9876 ///        by a scalar or vector shift amount.
9877 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9878                                  SourceLocation Loc, bool IsCompAssign) {
9879   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9880   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9881       !LHS.get()->getType()->isVectorType()) {
9882     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9883       << RHS.get()->getType() << LHS.get()->getType()
9884       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9885     return QualType();
9886   }
9887 
9888   if (!IsCompAssign) {
9889     LHS = S.UsualUnaryConversions(LHS.get());
9890     if (LHS.isInvalid()) return QualType();
9891   }
9892 
9893   RHS = S.UsualUnaryConversions(RHS.get());
9894   if (RHS.isInvalid()) return QualType();
9895 
9896   QualType LHSType = LHS.get()->getType();
9897   // Note that LHS might be a scalar because the routine calls not only in
9898   // OpenCL case.
9899   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9900   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9901 
9902   // Note that RHS might not be a vector.
9903   QualType RHSType = RHS.get()->getType();
9904   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9905   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9906 
9907   // The operands need to be integers.
9908   if (!LHSEleType->isIntegerType()) {
9909     S.Diag(Loc, diag::err_typecheck_expect_int)
9910       << LHS.get()->getType() << LHS.get()->getSourceRange();
9911     return QualType();
9912   }
9913 
9914   if (!RHSEleType->isIntegerType()) {
9915     S.Diag(Loc, diag::err_typecheck_expect_int)
9916       << RHS.get()->getType() << RHS.get()->getSourceRange();
9917     return QualType();
9918   }
9919 
9920   if (!LHSVecTy) {
9921     assert(RHSVecTy);
9922     if (IsCompAssign)
9923       return RHSType;
9924     if (LHSEleType != RHSEleType) {
9925       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9926       LHSEleType = RHSEleType;
9927     }
9928     QualType VecTy =
9929         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9930     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9931     LHSType = VecTy;
9932   } else if (RHSVecTy) {
9933     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9934     // are applied component-wise. So if RHS is a vector, then ensure
9935     // that the number of elements is the same as LHS...
9936     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9937       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9938         << LHS.get()->getType() << RHS.get()->getType()
9939         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9940       return QualType();
9941     }
9942     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9943       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9944       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9945       if (LHSBT != RHSBT &&
9946           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9947         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9948             << LHS.get()->getType() << RHS.get()->getType()
9949             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9950       }
9951     }
9952   } else {
9953     // ...else expand RHS to match the number of elements in LHS.
9954     QualType VecTy =
9955       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9956     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9957   }
9958 
9959   return LHSType;
9960 }
9961 
9962 // C99 6.5.7
9963 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9964                                   SourceLocation Loc, BinaryOperatorKind Opc,
9965                                   bool IsCompAssign) {
9966   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9967 
9968   // Vector shifts promote their scalar inputs to vector type.
9969   if (LHS.get()->getType()->isVectorType() ||
9970       RHS.get()->getType()->isVectorType()) {
9971     if (LangOpts.ZVector) {
9972       // The shift operators for the z vector extensions work basically
9973       // like general shifts, except that neither the LHS nor the RHS is
9974       // allowed to be a "vector bool".
9975       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9976         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9977           return InvalidOperands(Loc, LHS, RHS);
9978       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9979         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9980           return InvalidOperands(Loc, LHS, RHS);
9981     }
9982     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9983   }
9984 
9985   // Shifts don't perform usual arithmetic conversions, they just do integer
9986   // promotions on each operand. C99 6.5.7p3
9987 
9988   // For the LHS, do usual unary conversions, but then reset them away
9989   // if this is a compound assignment.
9990   ExprResult OldLHS = LHS;
9991   LHS = UsualUnaryConversions(LHS.get());
9992   if (LHS.isInvalid())
9993     return QualType();
9994   QualType LHSType = LHS.get()->getType();
9995   if (IsCompAssign) LHS = OldLHS;
9996 
9997   // The RHS is simpler.
9998   RHS = UsualUnaryConversions(RHS.get());
9999   if (RHS.isInvalid())
10000     return QualType();
10001   QualType RHSType = RHS.get()->getType();
10002 
10003   // C99 6.5.7p2: Each of the operands shall have integer type.
10004   if (!LHSType->hasIntegerRepresentation() ||
10005       !RHSType->hasIntegerRepresentation())
10006     return InvalidOperands(Loc, LHS, RHS);
10007 
10008   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10009   // hasIntegerRepresentation() above instead of this.
10010   if (isScopedEnumerationType(LHSType) ||
10011       isScopedEnumerationType(RHSType)) {
10012     return InvalidOperands(Loc, LHS, RHS);
10013   }
10014   // Sanity-check shift operands
10015   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10016 
10017   // "The type of the result is that of the promoted left operand."
10018   return LHSType;
10019 }
10020 
10021 /// If two different enums are compared, raise a warning.
10022 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
10023                                 Expr *RHS) {
10024   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
10025   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
10026 
10027   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
10028   if (!LHSEnumType)
10029     return;
10030   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
10031   if (!RHSEnumType)
10032     return;
10033 
10034   // Ignore anonymous enums.
10035   if (!LHSEnumType->getDecl()->getIdentifier() &&
10036       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
10037     return;
10038   if (!RHSEnumType->getDecl()->getIdentifier() &&
10039       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
10040     return;
10041 
10042   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
10043     return;
10044 
10045   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
10046       << LHSStrippedType << RHSStrippedType
10047       << LHS->getSourceRange() << RHS->getSourceRange();
10048 }
10049 
10050 /// Diagnose bad pointer comparisons.
10051 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10052                                               ExprResult &LHS, ExprResult &RHS,
10053                                               bool IsError) {
10054   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10055                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10056     << LHS.get()->getType() << RHS.get()->getType()
10057     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10058 }
10059 
10060 /// Returns false if the pointers are converted to a composite type,
10061 /// true otherwise.
10062 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10063                                            ExprResult &LHS, ExprResult &RHS) {
10064   // C++ [expr.rel]p2:
10065   //   [...] Pointer conversions (4.10) and qualification
10066   //   conversions (4.4) are performed on pointer operands (or on
10067   //   a pointer operand and a null pointer constant) to bring
10068   //   them to their composite pointer type. [...]
10069   //
10070   // C++ [expr.eq]p1 uses the same notion for (in)equality
10071   // comparisons of pointers.
10072 
10073   QualType LHSType = LHS.get()->getType();
10074   QualType RHSType = RHS.get()->getType();
10075   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10076          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10077 
10078   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10079   if (T.isNull()) {
10080     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10081         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10082       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10083     else
10084       S.InvalidOperands(Loc, LHS, RHS);
10085     return true;
10086   }
10087 
10088   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
10089   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
10090   return false;
10091 }
10092 
10093 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10094                                                     ExprResult &LHS,
10095                                                     ExprResult &RHS,
10096                                                     bool IsError) {
10097   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10098                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10099     << LHS.get()->getType() << RHS.get()->getType()
10100     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10101 }
10102 
10103 static bool isObjCObjectLiteral(ExprResult &E) {
10104   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10105   case Stmt::ObjCArrayLiteralClass:
10106   case Stmt::ObjCDictionaryLiteralClass:
10107   case Stmt::ObjCStringLiteralClass:
10108   case Stmt::ObjCBoxedExprClass:
10109     return true;
10110   default:
10111     // Note that ObjCBoolLiteral is NOT an object literal!
10112     return false;
10113   }
10114 }
10115 
10116 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10117   const ObjCObjectPointerType *Type =
10118     LHS->getType()->getAs<ObjCObjectPointerType>();
10119 
10120   // If this is not actually an Objective-C object, bail out.
10121   if (!Type)
10122     return false;
10123 
10124   // Get the LHS object's interface type.
10125   QualType InterfaceType = Type->getPointeeType();
10126 
10127   // If the RHS isn't an Objective-C object, bail out.
10128   if (!RHS->getType()->isObjCObjectPointerType())
10129     return false;
10130 
10131   // Try to find the -isEqual: method.
10132   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10133   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10134                                                       InterfaceType,
10135                                                       /*IsInstance=*/true);
10136   if (!Method) {
10137     if (Type->isObjCIdType()) {
10138       // For 'id', just check the global pool.
10139       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10140                                                   /*receiverId=*/true);
10141     } else {
10142       // Check protocols.
10143       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10144                                              /*IsInstance=*/true);
10145     }
10146   }
10147 
10148   if (!Method)
10149     return false;
10150 
10151   QualType T = Method->parameters()[0]->getType();
10152   if (!T->isObjCObjectPointerType())
10153     return false;
10154 
10155   QualType R = Method->getReturnType();
10156   if (!R->isScalarType())
10157     return false;
10158 
10159   return true;
10160 }
10161 
10162 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10163   FromE = FromE->IgnoreParenImpCasts();
10164   switch (FromE->getStmtClass()) {
10165     default:
10166       break;
10167     case Stmt::ObjCStringLiteralClass:
10168       // "string literal"
10169       return LK_String;
10170     case Stmt::ObjCArrayLiteralClass:
10171       // "array literal"
10172       return LK_Array;
10173     case Stmt::ObjCDictionaryLiteralClass:
10174       // "dictionary literal"
10175       return LK_Dictionary;
10176     case Stmt::BlockExprClass:
10177       return LK_Block;
10178     case Stmt::ObjCBoxedExprClass: {
10179       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10180       switch (Inner->getStmtClass()) {
10181         case Stmt::IntegerLiteralClass:
10182         case Stmt::FloatingLiteralClass:
10183         case Stmt::CharacterLiteralClass:
10184         case Stmt::ObjCBoolLiteralExprClass:
10185         case Stmt::CXXBoolLiteralExprClass:
10186           // "numeric literal"
10187           return LK_Numeric;
10188         case Stmt::ImplicitCastExprClass: {
10189           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10190           // Boolean literals can be represented by implicit casts.
10191           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10192             return LK_Numeric;
10193           break;
10194         }
10195         default:
10196           break;
10197       }
10198       return LK_Boxed;
10199     }
10200   }
10201   return LK_None;
10202 }
10203 
10204 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10205                                           ExprResult &LHS, ExprResult &RHS,
10206                                           BinaryOperator::Opcode Opc){
10207   Expr *Literal;
10208   Expr *Other;
10209   if (isObjCObjectLiteral(LHS)) {
10210     Literal = LHS.get();
10211     Other = RHS.get();
10212   } else {
10213     Literal = RHS.get();
10214     Other = LHS.get();
10215   }
10216 
10217   // Don't warn on comparisons against nil.
10218   Other = Other->IgnoreParenCasts();
10219   if (Other->isNullPointerConstant(S.getASTContext(),
10220                                    Expr::NPC_ValueDependentIsNotNull))
10221     return;
10222 
10223   // This should be kept in sync with warn_objc_literal_comparison.
10224   // LK_String should always be after the other literals, since it has its own
10225   // warning flag.
10226   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10227   assert(LiteralKind != Sema::LK_Block);
10228   if (LiteralKind == Sema::LK_None) {
10229     llvm_unreachable("Unknown Objective-C object literal kind");
10230   }
10231 
10232   if (LiteralKind == Sema::LK_String)
10233     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10234       << Literal->getSourceRange();
10235   else
10236     S.Diag(Loc, diag::warn_objc_literal_comparison)
10237       << LiteralKind << Literal->getSourceRange();
10238 
10239   if (BinaryOperator::isEqualityOp(Opc) &&
10240       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10241     SourceLocation Start = LHS.get()->getBeginLoc();
10242     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10243     CharSourceRange OpRange =
10244       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10245 
10246     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10247       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10248       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10249       << FixItHint::CreateInsertion(End, "]");
10250   }
10251 }
10252 
10253 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10254 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10255                                            ExprResult &RHS, SourceLocation Loc,
10256                                            BinaryOperatorKind Opc) {
10257   // Check that left hand side is !something.
10258   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10259   if (!UO || UO->getOpcode() != UO_LNot) return;
10260 
10261   // Only check if the right hand side is non-bool arithmetic type.
10262   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10263 
10264   // Make sure that the something in !something is not bool.
10265   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10266   if (SubExpr->isKnownToHaveBooleanValue()) return;
10267 
10268   // Emit warning.
10269   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10270   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10271       << Loc << IsBitwiseOp;
10272 
10273   // First note suggest !(x < y)
10274   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10275   SourceLocation FirstClose = RHS.get()->getEndLoc();
10276   FirstClose = S.getLocForEndOfToken(FirstClose);
10277   if (FirstClose.isInvalid())
10278     FirstOpen = SourceLocation();
10279   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10280       << IsBitwiseOp
10281       << FixItHint::CreateInsertion(FirstOpen, "(")
10282       << FixItHint::CreateInsertion(FirstClose, ")");
10283 
10284   // Second note suggests (!x) < y
10285   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10286   SourceLocation SecondClose = LHS.get()->getEndLoc();
10287   SecondClose = S.getLocForEndOfToken(SecondClose);
10288   if (SecondClose.isInvalid())
10289     SecondOpen = SourceLocation();
10290   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10291       << FixItHint::CreateInsertion(SecondOpen, "(")
10292       << FixItHint::CreateInsertion(SecondClose, ")");
10293 }
10294 
10295 // Returns true if E refers to a non-weak array.
10296 static bool checkForArray(const Expr *E) {
10297   const ValueDecl *D = nullptr;
10298   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10299     D = DR->getDecl();
10300   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10301     if (Mem->isImplicitAccess())
10302       D = Mem->getMemberDecl();
10303   }
10304   if (!D)
10305     return false;
10306   return D->getType()->isArrayType() && !D->isWeak();
10307 }
10308 
10309 /// Diagnose some forms of syntactically-obvious tautological comparison.
10310 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10311                                            Expr *LHS, Expr *RHS,
10312                                            BinaryOperatorKind Opc) {
10313   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10314   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10315 
10316   QualType LHSType = LHS->getType();
10317   QualType RHSType = RHS->getType();
10318   if (LHSType->hasFloatingRepresentation() ||
10319       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10320       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10321       S.inTemplateInstantiation())
10322     return;
10323 
10324   // Comparisons between two array types are ill-formed for operator<=>, so
10325   // we shouldn't emit any additional warnings about it.
10326   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10327     return;
10328 
10329   // For non-floating point types, check for self-comparisons of the form
10330   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10331   // often indicate logic errors in the program.
10332   //
10333   // NOTE: Don't warn about comparison expressions resulting from macro
10334   // expansion. Also don't warn about comparisons which are only self
10335   // comparisons within a template instantiation. The warnings should catch
10336   // obvious cases in the definition of the template anyways. The idea is to
10337   // warn when the typed comparison operator will always evaluate to the same
10338   // result.
10339 
10340   // Used for indexing into %select in warn_comparison_always
10341   enum {
10342     AlwaysConstant,
10343     AlwaysTrue,
10344     AlwaysFalse,
10345     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10346   };
10347 
10348   if (Expr::isSameComparisonOperand(LHS, RHS)) {
10349     unsigned Result;
10350     switch (Opc) {
10351     case BO_EQ: case BO_LE: case BO_GE:
10352       Result = AlwaysTrue;
10353       break;
10354     case BO_NE: case BO_LT: case BO_GT:
10355       Result = AlwaysFalse;
10356       break;
10357     case BO_Cmp:
10358       Result = AlwaysEqual;
10359       break;
10360     default:
10361       Result = AlwaysConstant;
10362       break;
10363     }
10364     S.DiagRuntimeBehavior(Loc, nullptr,
10365                           S.PDiag(diag::warn_comparison_always)
10366                               << 0 /*self-comparison*/
10367                               << Result);
10368   } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10369     // What is it always going to evaluate to?
10370     unsigned Result;
10371     switch(Opc) {
10372     case BO_EQ: // e.g. array1 == array2
10373       Result = AlwaysFalse;
10374       break;
10375     case BO_NE: // e.g. array1 != array2
10376       Result = AlwaysTrue;
10377       break;
10378     default: // e.g. array1 <= array2
10379       // The best we can say is 'a constant'
10380       Result = AlwaysConstant;
10381       break;
10382     }
10383     S.DiagRuntimeBehavior(Loc, nullptr,
10384                           S.PDiag(diag::warn_comparison_always)
10385                               << 1 /*array comparison*/
10386                               << Result);
10387   }
10388 
10389   if (isa<CastExpr>(LHSStripped))
10390     LHSStripped = LHSStripped->IgnoreParenCasts();
10391   if (isa<CastExpr>(RHSStripped))
10392     RHSStripped = RHSStripped->IgnoreParenCasts();
10393 
10394   // Warn about comparisons against a string constant (unless the other
10395   // operand is null); the user probably wants strcmp.
10396   Expr *LiteralString = nullptr;
10397   Expr *LiteralStringStripped = nullptr;
10398   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10399       !RHSStripped->isNullPointerConstant(S.Context,
10400                                           Expr::NPC_ValueDependentIsNull)) {
10401     LiteralString = LHS;
10402     LiteralStringStripped = LHSStripped;
10403   } else if ((isa<StringLiteral>(RHSStripped) ||
10404               isa<ObjCEncodeExpr>(RHSStripped)) &&
10405              !LHSStripped->isNullPointerConstant(S.Context,
10406                                           Expr::NPC_ValueDependentIsNull)) {
10407     LiteralString = RHS;
10408     LiteralStringStripped = RHSStripped;
10409   }
10410 
10411   if (LiteralString) {
10412     S.DiagRuntimeBehavior(Loc, nullptr,
10413                           S.PDiag(diag::warn_stringcompare)
10414                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10415                               << LiteralString->getSourceRange());
10416   }
10417 }
10418 
10419 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10420   switch (CK) {
10421   default: {
10422 #ifndef NDEBUG
10423     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10424                  << "\n";
10425 #endif
10426     llvm_unreachable("unhandled cast kind");
10427   }
10428   case CK_UserDefinedConversion:
10429     return ICK_Identity;
10430   case CK_LValueToRValue:
10431     return ICK_Lvalue_To_Rvalue;
10432   case CK_ArrayToPointerDecay:
10433     return ICK_Array_To_Pointer;
10434   case CK_FunctionToPointerDecay:
10435     return ICK_Function_To_Pointer;
10436   case CK_IntegralCast:
10437     return ICK_Integral_Conversion;
10438   case CK_FloatingCast:
10439     return ICK_Floating_Conversion;
10440   case CK_IntegralToFloating:
10441   case CK_FloatingToIntegral:
10442     return ICK_Floating_Integral;
10443   case CK_IntegralComplexCast:
10444   case CK_FloatingComplexCast:
10445   case CK_FloatingComplexToIntegralComplex:
10446   case CK_IntegralComplexToFloatingComplex:
10447     return ICK_Complex_Conversion;
10448   case CK_FloatingComplexToReal:
10449   case CK_FloatingRealToComplex:
10450   case CK_IntegralComplexToReal:
10451   case CK_IntegralRealToComplex:
10452     return ICK_Complex_Real;
10453   }
10454 }
10455 
10456 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10457                                              QualType FromType,
10458                                              SourceLocation Loc) {
10459   // Check for a narrowing implicit conversion.
10460   StandardConversionSequence SCS;
10461   SCS.setAsIdentityConversion();
10462   SCS.setToType(0, FromType);
10463   SCS.setToType(1, ToType);
10464   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10465     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10466 
10467   APValue PreNarrowingValue;
10468   QualType PreNarrowingType;
10469   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10470                                PreNarrowingType,
10471                                /*IgnoreFloatToIntegralConversion*/ true)) {
10472   case NK_Dependent_Narrowing:
10473     // Implicit conversion to a narrower type, but the expression is
10474     // value-dependent so we can't tell whether it's actually narrowing.
10475   case NK_Not_Narrowing:
10476     return false;
10477 
10478   case NK_Constant_Narrowing:
10479     // Implicit conversion to a narrower type, and the value is not a constant
10480     // expression.
10481     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10482         << /*Constant*/ 1
10483         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10484     return true;
10485 
10486   case NK_Variable_Narrowing:
10487     // Implicit conversion to a narrower type, and the value is not a constant
10488     // expression.
10489   case NK_Type_Narrowing:
10490     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10491         << /*Constant*/ 0 << FromType << ToType;
10492     // TODO: It's not a constant expression, but what if the user intended it
10493     // to be? Can we produce notes to help them figure out why it isn't?
10494     return true;
10495   }
10496   llvm_unreachable("unhandled case in switch");
10497 }
10498 
10499 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10500                                                          ExprResult &LHS,
10501                                                          ExprResult &RHS,
10502                                                          SourceLocation Loc) {
10503   using CCT = ComparisonCategoryType;
10504 
10505   QualType LHSType = LHS.get()->getType();
10506   QualType RHSType = RHS.get()->getType();
10507   // Dig out the original argument type and expression before implicit casts
10508   // were applied. These are the types/expressions we need to check the
10509   // [expr.spaceship] requirements against.
10510   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10511   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10512   QualType LHSStrippedType = LHSStripped.get()->getType();
10513   QualType RHSStrippedType = RHSStripped.get()->getType();
10514 
10515   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10516   // other is not, the program is ill-formed.
10517   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10518     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10519     return QualType();
10520   }
10521 
10522   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10523                     RHSStrippedType->isEnumeralType();
10524   if (NumEnumArgs == 1) {
10525     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10526     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10527     if (OtherTy->hasFloatingRepresentation()) {
10528       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10529       return QualType();
10530     }
10531   }
10532   if (NumEnumArgs == 2) {
10533     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10534     // type E, the operator yields the result of converting the operands
10535     // to the underlying type of E and applying <=> to the converted operands.
10536     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10537       S.InvalidOperands(Loc, LHS, RHS);
10538       return QualType();
10539     }
10540     QualType IntType =
10541         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10542     assert(IntType->isArithmeticType());
10543 
10544     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10545     // promote the boolean type, and all other promotable integer types, to
10546     // avoid this.
10547     if (IntType->isPromotableIntegerType())
10548       IntType = S.Context.getPromotedIntegerType(IntType);
10549 
10550     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10551     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10552     LHSType = RHSType = IntType;
10553   }
10554 
10555   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10556   // usual arithmetic conversions are applied to the operands.
10557   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10558   if (LHS.isInvalid() || RHS.isInvalid())
10559     return QualType();
10560   if (Type.isNull())
10561     return S.InvalidOperands(Loc, LHS, RHS);
10562   assert(Type->isArithmeticType() || Type->isEnumeralType());
10563 
10564   bool HasNarrowing = checkThreeWayNarrowingConversion(
10565       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10566   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10567                                                    RHS.get()->getBeginLoc());
10568   if (HasNarrowing)
10569     return QualType();
10570 
10571   assert(!Type.isNull() && "composite type for <=> has not been set");
10572 
10573   auto TypeKind = [&]() {
10574     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10575       if (CT->getElementType()->hasFloatingRepresentation())
10576         return CCT::WeakEquality;
10577       return CCT::StrongEquality;
10578     }
10579     if (Type->isIntegralOrEnumerationType())
10580       return CCT::StrongOrdering;
10581     if (Type->hasFloatingRepresentation())
10582       return CCT::PartialOrdering;
10583     llvm_unreachable("other types are unimplemented");
10584   }();
10585 
10586   return S.CheckComparisonCategoryType(TypeKind, Loc);
10587 }
10588 
10589 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10590                                                  ExprResult &RHS,
10591                                                  SourceLocation Loc,
10592                                                  BinaryOperatorKind Opc) {
10593   if (Opc == BO_Cmp)
10594     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10595 
10596   // C99 6.5.8p3 / C99 6.5.9p4
10597   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10598   if (LHS.isInvalid() || RHS.isInvalid())
10599     return QualType();
10600   if (Type.isNull())
10601     return S.InvalidOperands(Loc, LHS, RHS);
10602   assert(Type->isArithmeticType() || Type->isEnumeralType());
10603 
10604   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10605 
10606   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10607     return S.InvalidOperands(Loc, LHS, RHS);
10608 
10609   // Check for comparisons of floating point operands using != and ==.
10610   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10611     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10612 
10613   // The result of comparisons is 'bool' in C++, 'int' in C.
10614   return S.Context.getLogicalOperationType();
10615 }
10616 
10617 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10618   if (!NullE.get()->getType()->isAnyPointerType())
10619     return;
10620   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10621   if (!E.get()->getType()->isAnyPointerType() &&
10622       E.get()->isNullPointerConstant(Context,
10623                                      Expr::NPC_ValueDependentIsNotNull) ==
10624         Expr::NPCK_ZeroExpression) {
10625     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10626       if (CL->getValue() == 0)
10627         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10628             << NullValue
10629             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10630                                             NullValue ? "NULL" : "(void *)0");
10631     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10632         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10633         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10634         if (T == Context.CharTy)
10635           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10636               << NullValue
10637               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10638                                               NullValue ? "NULL" : "(void *)0");
10639       }
10640   }
10641 }
10642 
10643 // C99 6.5.8, C++ [expr.rel]
10644 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10645                                     SourceLocation Loc,
10646                                     BinaryOperatorKind Opc) {
10647   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10648   bool IsThreeWay = Opc == BO_Cmp;
10649   auto IsAnyPointerType = [](ExprResult E) {
10650     QualType Ty = E.get()->getType();
10651     return Ty->isPointerType() || Ty->isMemberPointerType();
10652   };
10653 
10654   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10655   // type, array-to-pointer, ..., conversions are performed on both operands to
10656   // bring them to their composite type.
10657   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10658   // any type-related checks.
10659   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10660     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10661     if (LHS.isInvalid())
10662       return QualType();
10663     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10664     if (RHS.isInvalid())
10665       return QualType();
10666   } else {
10667     LHS = DefaultLvalueConversion(LHS.get());
10668     if (LHS.isInvalid())
10669       return QualType();
10670     RHS = DefaultLvalueConversion(RHS.get());
10671     if (RHS.isInvalid())
10672       return QualType();
10673   }
10674 
10675   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10676   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10677     CheckPtrComparisonWithNullChar(LHS, RHS);
10678     CheckPtrComparisonWithNullChar(RHS, LHS);
10679   }
10680 
10681   // Handle vector comparisons separately.
10682   if (LHS.get()->getType()->isVectorType() ||
10683       RHS.get()->getType()->isVectorType())
10684     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10685 
10686   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10687   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10688 
10689   QualType LHSType = LHS.get()->getType();
10690   QualType RHSType = RHS.get()->getType();
10691   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10692       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10693     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10694 
10695   const Expr::NullPointerConstantKind LHSNullKind =
10696       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10697   const Expr::NullPointerConstantKind RHSNullKind =
10698       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10699   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10700   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10701 
10702   auto computeResultTy = [&]() {
10703     if (Opc != BO_Cmp)
10704       return Context.getLogicalOperationType();
10705     assert(getLangOpts().CPlusPlus);
10706     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10707 
10708     QualType CompositeTy = LHS.get()->getType();
10709     assert(!CompositeTy->isReferenceType());
10710 
10711     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10712       return CheckComparisonCategoryType(Kind, Loc);
10713     };
10714 
10715     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10716     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10717     // result is of type std::strong_equality
10718     if (CompositeTy->isFunctionPointerType() ||
10719         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10720       // FIXME: consider making the function pointer case produce
10721       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10722       // and direction polls
10723       return buildResultTy(ComparisonCategoryType::StrongEquality);
10724 
10725     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10726     // pointer type, p <=> q is of type std::strong_ordering.
10727     if (CompositeTy->isPointerType()) {
10728       // P0946R0: Comparisons between a null pointer constant and an object
10729       // pointer result in std::strong_equality
10730       if (LHSIsNull != RHSIsNull)
10731         return buildResultTy(ComparisonCategoryType::StrongEquality);
10732       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10733     }
10734     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10735     // TODO: Extend support for operator<=> to ObjC types.
10736     return InvalidOperands(Loc, LHS, RHS);
10737   };
10738 
10739 
10740   if (!IsRelational && LHSIsNull != RHSIsNull) {
10741     bool IsEquality = Opc == BO_EQ;
10742     if (RHSIsNull)
10743       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10744                                    RHS.get()->getSourceRange());
10745     else
10746       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10747                                    LHS.get()->getSourceRange());
10748   }
10749 
10750   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10751       (RHSType->isIntegerType() && !RHSIsNull)) {
10752     // Skip normal pointer conversion checks in this case; we have better
10753     // diagnostics for this below.
10754   } else if (getLangOpts().CPlusPlus) {
10755     // Equality comparison of a function pointer to a void pointer is invalid,
10756     // but we allow it as an extension.
10757     // FIXME: If we really want to allow this, should it be part of composite
10758     // pointer type computation so it works in conditionals too?
10759     if (!IsRelational &&
10760         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10761          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10762       // This is a gcc extension compatibility comparison.
10763       // In a SFINAE context, we treat this as a hard error to maintain
10764       // conformance with the C++ standard.
10765       diagnoseFunctionPointerToVoidComparison(
10766           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10767 
10768       if (isSFINAEContext())
10769         return QualType();
10770 
10771       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10772       return computeResultTy();
10773     }
10774 
10775     // C++ [expr.eq]p2:
10776     //   If at least one operand is a pointer [...] bring them to their
10777     //   composite pointer type.
10778     // C++ [expr.spaceship]p6
10779     //  If at least one of the operands is of pointer type, [...] bring them
10780     //  to their composite pointer type.
10781     // C++ [expr.rel]p2:
10782     //   If both operands are pointers, [...] bring them to their composite
10783     //   pointer type.
10784     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10785             (IsRelational ? 2 : 1) &&
10786         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10787                                          RHSType->isObjCObjectPointerType()))) {
10788       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10789         return QualType();
10790       return computeResultTy();
10791     }
10792   } else if (LHSType->isPointerType() &&
10793              RHSType->isPointerType()) { // C99 6.5.8p2
10794     // All of the following pointer-related warnings are GCC extensions, except
10795     // when handling null pointer constants.
10796     QualType LCanPointeeTy =
10797       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10798     QualType RCanPointeeTy =
10799       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10800 
10801     // C99 6.5.9p2 and C99 6.5.8p2
10802     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10803                                    RCanPointeeTy.getUnqualifiedType())) {
10804       // Valid unless a relational comparison of function pointers
10805       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10806         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10807           << LHSType << RHSType << LHS.get()->getSourceRange()
10808           << RHS.get()->getSourceRange();
10809       }
10810     } else if (!IsRelational &&
10811                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10812       // Valid unless comparison between non-null pointer and function pointer
10813       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10814           && !LHSIsNull && !RHSIsNull)
10815         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10816                                                 /*isError*/false);
10817     } else {
10818       // Invalid
10819       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10820     }
10821     if (LCanPointeeTy != RCanPointeeTy) {
10822       // Treat NULL constant as a special case in OpenCL.
10823       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10824         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10825         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10826           Diag(Loc,
10827                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10828               << LHSType << RHSType << 0 /* comparison */
10829               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10830         }
10831       }
10832       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10833       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10834       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10835                                                : CK_BitCast;
10836       if (LHSIsNull && !RHSIsNull)
10837         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10838       else
10839         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10840     }
10841     return computeResultTy();
10842   }
10843 
10844   if (getLangOpts().CPlusPlus) {
10845     // C++ [expr.eq]p4:
10846     //   Two operands of type std::nullptr_t or one operand of type
10847     //   std::nullptr_t and the other a null pointer constant compare equal.
10848     if (!IsRelational && LHSIsNull && RHSIsNull) {
10849       if (LHSType->isNullPtrType()) {
10850         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10851         return computeResultTy();
10852       }
10853       if (RHSType->isNullPtrType()) {
10854         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10855         return computeResultTy();
10856       }
10857     }
10858 
10859     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10860     // These aren't covered by the composite pointer type rules.
10861     if (!IsRelational && RHSType->isNullPtrType() &&
10862         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10863       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10864       return computeResultTy();
10865     }
10866     if (!IsRelational && LHSType->isNullPtrType() &&
10867         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10868       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10869       return computeResultTy();
10870     }
10871 
10872     if (IsRelational &&
10873         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10874          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10875       // HACK: Relational comparison of nullptr_t against a pointer type is
10876       // invalid per DR583, but we allow it within std::less<> and friends,
10877       // since otherwise common uses of it break.
10878       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10879       // friends to have std::nullptr_t overload candidates.
10880       DeclContext *DC = CurContext;
10881       if (isa<FunctionDecl>(DC))
10882         DC = DC->getParent();
10883       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10884         if (CTSD->isInStdNamespace() &&
10885             llvm::StringSwitch<bool>(CTSD->getName())
10886                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10887                 .Default(false)) {
10888           if (RHSType->isNullPtrType())
10889             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10890           else
10891             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10892           return computeResultTy();
10893         }
10894       }
10895     }
10896 
10897     // C++ [expr.eq]p2:
10898     //   If at least one operand is a pointer to member, [...] bring them to
10899     //   their composite pointer type.
10900     if (!IsRelational &&
10901         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10902       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10903         return QualType();
10904       else
10905         return computeResultTy();
10906     }
10907   }
10908 
10909   // Handle block pointer types.
10910   if (!IsRelational && LHSType->isBlockPointerType() &&
10911       RHSType->isBlockPointerType()) {
10912     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10913     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10914 
10915     if (!LHSIsNull && !RHSIsNull &&
10916         !Context.typesAreCompatible(lpointee, rpointee)) {
10917       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10918         << LHSType << RHSType << LHS.get()->getSourceRange()
10919         << RHS.get()->getSourceRange();
10920     }
10921     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10922     return computeResultTy();
10923   }
10924 
10925   // Allow block pointers to be compared with null pointer constants.
10926   if (!IsRelational
10927       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10928           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10929     if (!LHSIsNull && !RHSIsNull) {
10930       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10931              ->getPointeeType()->isVoidType())
10932             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10933                 ->getPointeeType()->isVoidType())))
10934         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10935           << LHSType << RHSType << LHS.get()->getSourceRange()
10936           << RHS.get()->getSourceRange();
10937     }
10938     if (LHSIsNull && !RHSIsNull)
10939       LHS = ImpCastExprToType(LHS.get(), RHSType,
10940                               RHSType->isPointerType() ? CK_BitCast
10941                                 : CK_AnyPointerToBlockPointerCast);
10942     else
10943       RHS = ImpCastExprToType(RHS.get(), LHSType,
10944                               LHSType->isPointerType() ? CK_BitCast
10945                                 : CK_AnyPointerToBlockPointerCast);
10946     return computeResultTy();
10947   }
10948 
10949   if (LHSType->isObjCObjectPointerType() ||
10950       RHSType->isObjCObjectPointerType()) {
10951     const PointerType *LPT = LHSType->getAs<PointerType>();
10952     const PointerType *RPT = RHSType->getAs<PointerType>();
10953     if (LPT || RPT) {
10954       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10955       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10956 
10957       if (!LPtrToVoid && !RPtrToVoid &&
10958           !Context.typesAreCompatible(LHSType, RHSType)) {
10959         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10960                                           /*isError*/false);
10961       }
10962       if (LHSIsNull && !RHSIsNull) {
10963         Expr *E = LHS.get();
10964         if (getLangOpts().ObjCAutoRefCount)
10965           CheckObjCConversion(SourceRange(), RHSType, E,
10966                               CCK_ImplicitConversion);
10967         LHS = ImpCastExprToType(E, RHSType,
10968                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10969       }
10970       else {
10971         Expr *E = RHS.get();
10972         if (getLangOpts().ObjCAutoRefCount)
10973           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10974                               /*Diagnose=*/true,
10975                               /*DiagnoseCFAudited=*/false, Opc);
10976         RHS = ImpCastExprToType(E, LHSType,
10977                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10978       }
10979       return computeResultTy();
10980     }
10981     if (LHSType->isObjCObjectPointerType() &&
10982         RHSType->isObjCObjectPointerType()) {
10983       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10984         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10985                                           /*isError*/false);
10986       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10987         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10988 
10989       if (LHSIsNull && !RHSIsNull)
10990         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10991       else
10992         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10993       return computeResultTy();
10994     }
10995 
10996     if (!IsRelational && LHSType->isBlockPointerType() &&
10997         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10998       LHS = ImpCastExprToType(LHS.get(), RHSType,
10999                               CK_BlockPointerToObjCPointerCast);
11000       return computeResultTy();
11001     } else if (!IsRelational &&
11002                LHSType->isBlockCompatibleObjCPointerType(Context) &&
11003                RHSType->isBlockPointerType()) {
11004       RHS = ImpCastExprToType(RHS.get(), LHSType,
11005                               CK_BlockPointerToObjCPointerCast);
11006       return computeResultTy();
11007     }
11008   }
11009   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11010       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11011     unsigned DiagID = 0;
11012     bool isError = false;
11013     if (LangOpts.DebuggerSupport) {
11014       // Under a debugger, allow the comparison of pointers to integers,
11015       // since users tend to want to compare addresses.
11016     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11017                (RHSIsNull && RHSType->isIntegerType())) {
11018       if (IsRelational) {
11019         isError = getLangOpts().CPlusPlus;
11020         DiagID =
11021           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11022                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11023       }
11024     } else if (getLangOpts().CPlusPlus) {
11025       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11026       isError = true;
11027     } else if (IsRelational)
11028       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11029     else
11030       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11031 
11032     if (DiagID) {
11033       Diag(Loc, DiagID)
11034         << LHSType << RHSType << LHS.get()->getSourceRange()
11035         << RHS.get()->getSourceRange();
11036       if (isError)
11037         return QualType();
11038     }
11039 
11040     if (LHSType->isIntegerType())
11041       LHS = ImpCastExprToType(LHS.get(), RHSType,
11042                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11043     else
11044       RHS = ImpCastExprToType(RHS.get(), LHSType,
11045                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11046     return computeResultTy();
11047   }
11048 
11049   // Handle block pointers.
11050   if (!IsRelational && RHSIsNull
11051       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11052     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11053     return computeResultTy();
11054   }
11055   if (!IsRelational && LHSIsNull
11056       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11057     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11058     return computeResultTy();
11059   }
11060 
11061   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11062     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11063       return computeResultTy();
11064     }
11065 
11066     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11067       return computeResultTy();
11068     }
11069 
11070     if (LHSIsNull && RHSType->isQueueT()) {
11071       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11072       return computeResultTy();
11073     }
11074 
11075     if (LHSType->isQueueT() && RHSIsNull) {
11076       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11077       return computeResultTy();
11078     }
11079   }
11080 
11081   return InvalidOperands(Loc, LHS, RHS);
11082 }
11083 
11084 // Return a signed ext_vector_type that is of identical size and number of
11085 // elements. For floating point vectors, return an integer type of identical
11086 // size and number of elements. In the non ext_vector_type case, search from
11087 // the largest type to the smallest type to avoid cases where long long == long,
11088 // where long gets picked over long long.
11089 QualType Sema::GetSignedVectorType(QualType V) {
11090   const VectorType *VTy = V->castAs<VectorType>();
11091   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11092 
11093   if (isa<ExtVectorType>(VTy)) {
11094     if (TypeSize == Context.getTypeSize(Context.CharTy))
11095       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11096     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11097       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11098     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11099       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11100     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11101       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11102     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11103            "Unhandled vector element size in vector compare");
11104     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11105   }
11106 
11107   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11108     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11109                                  VectorType::GenericVector);
11110   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11111     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11112                                  VectorType::GenericVector);
11113   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11114     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11115                                  VectorType::GenericVector);
11116   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11117     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11118                                  VectorType::GenericVector);
11119   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11120          "Unhandled vector element size in vector compare");
11121   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11122                                VectorType::GenericVector);
11123 }
11124 
11125 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11126 /// operates on extended vector types.  Instead of producing an IntTy result,
11127 /// like a scalar comparison, a vector comparison produces a vector of integer
11128 /// types.
11129 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11130                                           SourceLocation Loc,
11131                                           BinaryOperatorKind Opc) {
11132   // Check to make sure we're operating on vectors of the same type and width,
11133   // Allowing one side to be a scalar of element type.
11134   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11135                               /*AllowBothBool*/true,
11136                               /*AllowBoolConversions*/getLangOpts().ZVector);
11137   if (vType.isNull())
11138     return vType;
11139 
11140   QualType LHSType = LHS.get()->getType();
11141 
11142   // If AltiVec, the comparison results in a numeric type, i.e.
11143   // bool for C++, int for C
11144   if (getLangOpts().AltiVec &&
11145       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11146     return Context.getLogicalOperationType();
11147 
11148   // For non-floating point types, check for self-comparisons of the form
11149   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11150   // often indicate logic errors in the program.
11151   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11152 
11153   // Check for comparisons of floating point operands using != and ==.
11154   if (BinaryOperator::isEqualityOp(Opc) &&
11155       LHSType->hasFloatingRepresentation()) {
11156     assert(RHS.get()->getType()->hasFloatingRepresentation());
11157     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11158   }
11159 
11160   // Return a signed type for the vector.
11161   return GetSignedVectorType(vType);
11162 }
11163 
11164 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11165                                     const ExprResult &XorRHS,
11166                                     const SourceLocation Loc) {
11167   // Do not diagnose macros.
11168   if (Loc.isMacroID())
11169     return;
11170 
11171   bool Negative = false;
11172   bool ExplicitPlus = false;
11173   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11174   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11175 
11176   if (!LHSInt)
11177     return;
11178   if (!RHSInt) {
11179     // Check negative literals.
11180     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11181       UnaryOperatorKind Opc = UO->getOpcode();
11182       if (Opc != UO_Minus && Opc != UO_Plus)
11183         return;
11184       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11185       if (!RHSInt)
11186         return;
11187       Negative = (Opc == UO_Minus);
11188       ExplicitPlus = !Negative;
11189     } else {
11190       return;
11191     }
11192   }
11193 
11194   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11195   llvm::APInt RightSideValue = RHSInt->getValue();
11196   if (LeftSideValue != 2 && LeftSideValue != 10)
11197     return;
11198 
11199   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11200     return;
11201 
11202   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11203       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11204   llvm::StringRef ExprStr =
11205       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11206 
11207   CharSourceRange XorRange =
11208       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11209   llvm::StringRef XorStr =
11210       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11211   // Do not diagnose if xor keyword/macro is used.
11212   if (XorStr == "xor")
11213     return;
11214 
11215   std::string LHSStr = Lexer::getSourceText(
11216       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11217       S.getSourceManager(), S.getLangOpts());
11218   std::string RHSStr = Lexer::getSourceText(
11219       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11220       S.getSourceManager(), S.getLangOpts());
11221 
11222   if (Negative) {
11223     RightSideValue = -RightSideValue;
11224     RHSStr = "-" + RHSStr;
11225   } else if (ExplicitPlus) {
11226     RHSStr = "+" + RHSStr;
11227   }
11228 
11229   StringRef LHSStrRef = LHSStr;
11230   StringRef RHSStrRef = RHSStr;
11231   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11232   // literals.
11233   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11234       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11235       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11236       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11237       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11238       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11239       LHSStrRef.find('\'') != StringRef::npos ||
11240       RHSStrRef.find('\'') != StringRef::npos)
11241     return;
11242 
11243   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11244   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11245   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11246   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11247     std::string SuggestedExpr = "1 << " + RHSStr;
11248     bool Overflow = false;
11249     llvm::APInt One = (LeftSideValue - 1);
11250     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11251     if (Overflow) {
11252       if (RightSideIntValue < 64)
11253         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11254             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11255             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11256       else if (RightSideIntValue == 64)
11257         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11258       else
11259         return;
11260     } else {
11261       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11262           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11263           << PowValue.toString(10, true)
11264           << FixItHint::CreateReplacement(
11265                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11266     }
11267 
11268     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11269   } else if (LeftSideValue == 10) {
11270     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11271     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11272         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11273         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11274     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11275   }
11276 }
11277 
11278 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11279                                           SourceLocation Loc) {
11280   // Ensure that either both operands are of the same vector type, or
11281   // one operand is of a vector type and the other is of its element type.
11282   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11283                                        /*AllowBothBool*/true,
11284                                        /*AllowBoolConversions*/false);
11285   if (vType.isNull())
11286     return InvalidOperands(Loc, LHS, RHS);
11287   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11288       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11289     return InvalidOperands(Loc, LHS, RHS);
11290   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11291   //        usage of the logical operators && and || with vectors in C. This
11292   //        check could be notionally dropped.
11293   if (!getLangOpts().CPlusPlus &&
11294       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11295     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11296 
11297   return GetSignedVectorType(LHS.get()->getType());
11298 }
11299 
11300 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11301                                            SourceLocation Loc,
11302                                            BinaryOperatorKind Opc) {
11303   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11304 
11305   bool IsCompAssign =
11306       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11307 
11308   if (LHS.get()->getType()->isVectorType() ||
11309       RHS.get()->getType()->isVectorType()) {
11310     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11311         RHS.get()->getType()->hasIntegerRepresentation())
11312       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11313                         /*AllowBothBool*/true,
11314                         /*AllowBoolConversions*/getLangOpts().ZVector);
11315     return InvalidOperands(Loc, LHS, RHS);
11316   }
11317 
11318   if (Opc == BO_And)
11319     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11320 
11321   ExprResult LHSResult = LHS, RHSResult = RHS;
11322   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
11323                                                  IsCompAssign);
11324   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11325     return QualType();
11326   LHS = LHSResult.get();
11327   RHS = RHSResult.get();
11328 
11329   if (Opc == BO_Xor)
11330     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11331 
11332   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11333     return compType;
11334   return InvalidOperands(Loc, LHS, RHS);
11335 }
11336 
11337 // C99 6.5.[13,14]
11338 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11339                                            SourceLocation Loc,
11340                                            BinaryOperatorKind Opc) {
11341   // Check vector operands differently.
11342   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11343     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11344 
11345   bool EnumConstantInBoolContext = false;
11346   for (const ExprResult &HS : {LHS, RHS}) {
11347     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11348       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11349       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11350         EnumConstantInBoolContext = true;
11351     }
11352   }
11353 
11354   if (EnumConstantInBoolContext)
11355     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11356 
11357   // Diagnose cases where the user write a logical and/or but probably meant a
11358   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11359   // is a constant.
11360   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11361       !LHS.get()->getType()->isBooleanType() &&
11362       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11363       // Don't warn in macros or template instantiations.
11364       !Loc.isMacroID() && !inTemplateInstantiation()) {
11365     // If the RHS can be constant folded, and if it constant folds to something
11366     // that isn't 0 or 1 (which indicate a potential logical operation that
11367     // happened to fold to true/false) then warn.
11368     // Parens on the RHS are ignored.
11369     Expr::EvalResult EVResult;
11370     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11371       llvm::APSInt Result = EVResult.Val.getInt();
11372       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11373            !RHS.get()->getExprLoc().isMacroID()) ||
11374           (Result != 0 && Result != 1)) {
11375         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11376           << RHS.get()->getSourceRange()
11377           << (Opc == BO_LAnd ? "&&" : "||");
11378         // Suggest replacing the logical operator with the bitwise version
11379         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11380             << (Opc == BO_LAnd ? "&" : "|")
11381             << FixItHint::CreateReplacement(SourceRange(
11382                                                  Loc, getLocForEndOfToken(Loc)),
11383                                             Opc == BO_LAnd ? "&" : "|");
11384         if (Opc == BO_LAnd)
11385           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11386           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11387               << FixItHint::CreateRemoval(
11388                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11389                                  RHS.get()->getEndLoc()));
11390       }
11391     }
11392   }
11393 
11394   if (!Context.getLangOpts().CPlusPlus) {
11395     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11396     // not operate on the built-in scalar and vector float types.
11397     if (Context.getLangOpts().OpenCL &&
11398         Context.getLangOpts().OpenCLVersion < 120) {
11399       if (LHS.get()->getType()->isFloatingType() ||
11400           RHS.get()->getType()->isFloatingType())
11401         return InvalidOperands(Loc, LHS, RHS);
11402     }
11403 
11404     LHS = UsualUnaryConversions(LHS.get());
11405     if (LHS.isInvalid())
11406       return QualType();
11407 
11408     RHS = UsualUnaryConversions(RHS.get());
11409     if (RHS.isInvalid())
11410       return QualType();
11411 
11412     if (!LHS.get()->getType()->isScalarType() ||
11413         !RHS.get()->getType()->isScalarType())
11414       return InvalidOperands(Loc, LHS, RHS);
11415 
11416     return Context.IntTy;
11417   }
11418 
11419   // The following is safe because we only use this method for
11420   // non-overloadable operands.
11421 
11422   // C++ [expr.log.and]p1
11423   // C++ [expr.log.or]p1
11424   // The operands are both contextually converted to type bool.
11425   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11426   if (LHSRes.isInvalid())
11427     return InvalidOperands(Loc, LHS, RHS);
11428   LHS = LHSRes;
11429 
11430   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11431   if (RHSRes.isInvalid())
11432     return InvalidOperands(Loc, LHS, RHS);
11433   RHS = RHSRes;
11434 
11435   // C++ [expr.log.and]p2
11436   // C++ [expr.log.or]p2
11437   // The result is a bool.
11438   return Context.BoolTy;
11439 }
11440 
11441 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11442   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11443   if (!ME) return false;
11444   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11445   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11446       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11447   if (!Base) return false;
11448   return Base->getMethodDecl() != nullptr;
11449 }
11450 
11451 /// Is the given expression (which must be 'const') a reference to a
11452 /// variable which was originally non-const, but which has become
11453 /// 'const' due to being captured within a block?
11454 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11455 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11456   assert(E->isLValue() && E->getType().isConstQualified());
11457   E = E->IgnoreParens();
11458 
11459   // Must be a reference to a declaration from an enclosing scope.
11460   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11461   if (!DRE) return NCCK_None;
11462   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11463 
11464   // The declaration must be a variable which is not declared 'const'.
11465   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11466   if (!var) return NCCK_None;
11467   if (var->getType().isConstQualified()) return NCCK_None;
11468   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11469 
11470   // Decide whether the first capture was for a block or a lambda.
11471   DeclContext *DC = S.CurContext, *Prev = nullptr;
11472   // Decide whether the first capture was for a block or a lambda.
11473   while (DC) {
11474     // For init-capture, it is possible that the variable belongs to the
11475     // template pattern of the current context.
11476     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11477       if (var->isInitCapture() &&
11478           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11479         break;
11480     if (DC == var->getDeclContext())
11481       break;
11482     Prev = DC;
11483     DC = DC->getParent();
11484   }
11485   // Unless we have an init-capture, we've gone one step too far.
11486   if (!var->isInitCapture())
11487     DC = Prev;
11488   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11489 }
11490 
11491 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11492   Ty = Ty.getNonReferenceType();
11493   if (IsDereference && Ty->isPointerType())
11494     Ty = Ty->getPointeeType();
11495   return !Ty.isConstQualified();
11496 }
11497 
11498 // Update err_typecheck_assign_const and note_typecheck_assign_const
11499 // when this enum is changed.
11500 enum {
11501   ConstFunction,
11502   ConstVariable,
11503   ConstMember,
11504   ConstMethod,
11505   NestedConstMember,
11506   ConstUnknown,  // Keep as last element
11507 };
11508 
11509 /// Emit the "read-only variable not assignable" error and print notes to give
11510 /// more information about why the variable is not assignable, such as pointing
11511 /// to the declaration of a const variable, showing that a method is const, or
11512 /// that the function is returning a const reference.
11513 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11514                                     SourceLocation Loc) {
11515   SourceRange ExprRange = E->getSourceRange();
11516 
11517   // Only emit one error on the first const found.  All other consts will emit
11518   // a note to the error.
11519   bool DiagnosticEmitted = false;
11520 
11521   // Track if the current expression is the result of a dereference, and if the
11522   // next checked expression is the result of a dereference.
11523   bool IsDereference = false;
11524   bool NextIsDereference = false;
11525 
11526   // Loop to process MemberExpr chains.
11527   while (true) {
11528     IsDereference = NextIsDereference;
11529 
11530     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11531     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11532       NextIsDereference = ME->isArrow();
11533       const ValueDecl *VD = ME->getMemberDecl();
11534       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11535         // Mutable fields can be modified even if the class is const.
11536         if (Field->isMutable()) {
11537           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11538           break;
11539         }
11540 
11541         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11542           if (!DiagnosticEmitted) {
11543             S.Diag(Loc, diag::err_typecheck_assign_const)
11544                 << ExprRange << ConstMember << false /*static*/ << Field
11545                 << Field->getType();
11546             DiagnosticEmitted = true;
11547           }
11548           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11549               << ConstMember << false /*static*/ << Field << Field->getType()
11550               << Field->getSourceRange();
11551         }
11552         E = ME->getBase();
11553         continue;
11554       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11555         if (VDecl->getType().isConstQualified()) {
11556           if (!DiagnosticEmitted) {
11557             S.Diag(Loc, diag::err_typecheck_assign_const)
11558                 << ExprRange << ConstMember << true /*static*/ << VDecl
11559                 << VDecl->getType();
11560             DiagnosticEmitted = true;
11561           }
11562           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11563               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11564               << VDecl->getSourceRange();
11565         }
11566         // Static fields do not inherit constness from parents.
11567         break;
11568       }
11569       break; // End MemberExpr
11570     } else if (const ArraySubscriptExpr *ASE =
11571                    dyn_cast<ArraySubscriptExpr>(E)) {
11572       E = ASE->getBase()->IgnoreParenImpCasts();
11573       continue;
11574     } else if (const ExtVectorElementExpr *EVE =
11575                    dyn_cast<ExtVectorElementExpr>(E)) {
11576       E = EVE->getBase()->IgnoreParenImpCasts();
11577       continue;
11578     }
11579     break;
11580   }
11581 
11582   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11583     // Function calls
11584     const FunctionDecl *FD = CE->getDirectCallee();
11585     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11586       if (!DiagnosticEmitted) {
11587         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11588                                                       << ConstFunction << FD;
11589         DiagnosticEmitted = true;
11590       }
11591       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11592              diag::note_typecheck_assign_const)
11593           << ConstFunction << FD << FD->getReturnType()
11594           << FD->getReturnTypeSourceRange();
11595     }
11596   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11597     // Point to variable declaration.
11598     if (const ValueDecl *VD = DRE->getDecl()) {
11599       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11600         if (!DiagnosticEmitted) {
11601           S.Diag(Loc, diag::err_typecheck_assign_const)
11602               << ExprRange << ConstVariable << VD << VD->getType();
11603           DiagnosticEmitted = true;
11604         }
11605         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11606             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11607       }
11608     }
11609   } else if (isa<CXXThisExpr>(E)) {
11610     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11611       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11612         if (MD->isConst()) {
11613           if (!DiagnosticEmitted) {
11614             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11615                                                           << ConstMethod << MD;
11616             DiagnosticEmitted = true;
11617           }
11618           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11619               << ConstMethod << MD << MD->getSourceRange();
11620         }
11621       }
11622     }
11623   }
11624 
11625   if (DiagnosticEmitted)
11626     return;
11627 
11628   // Can't determine a more specific message, so display the generic error.
11629   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11630 }
11631 
11632 enum OriginalExprKind {
11633   OEK_Variable,
11634   OEK_Member,
11635   OEK_LValue
11636 };
11637 
11638 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11639                                          const RecordType *Ty,
11640                                          SourceLocation Loc, SourceRange Range,
11641                                          OriginalExprKind OEK,
11642                                          bool &DiagnosticEmitted) {
11643   std::vector<const RecordType *> RecordTypeList;
11644   RecordTypeList.push_back(Ty);
11645   unsigned NextToCheckIndex = 0;
11646   // We walk the record hierarchy breadth-first to ensure that we print
11647   // diagnostics in field nesting order.
11648   while (RecordTypeList.size() > NextToCheckIndex) {
11649     bool IsNested = NextToCheckIndex > 0;
11650     for (const FieldDecl *Field :
11651          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11652       // First, check every field for constness.
11653       QualType FieldTy = Field->getType();
11654       if (FieldTy.isConstQualified()) {
11655         if (!DiagnosticEmitted) {
11656           S.Diag(Loc, diag::err_typecheck_assign_const)
11657               << Range << NestedConstMember << OEK << VD
11658               << IsNested << Field;
11659           DiagnosticEmitted = true;
11660         }
11661         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11662             << NestedConstMember << IsNested << Field
11663             << FieldTy << Field->getSourceRange();
11664       }
11665 
11666       // Then we append it to the list to check next in order.
11667       FieldTy = FieldTy.getCanonicalType();
11668       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11669         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11670           RecordTypeList.push_back(FieldRecTy);
11671       }
11672     }
11673     ++NextToCheckIndex;
11674   }
11675 }
11676 
11677 /// Emit an error for the case where a record we are trying to assign to has a
11678 /// const-qualified field somewhere in its hierarchy.
11679 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11680                                          SourceLocation Loc) {
11681   QualType Ty = E->getType();
11682   assert(Ty->isRecordType() && "lvalue was not record?");
11683   SourceRange Range = E->getSourceRange();
11684   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11685   bool DiagEmitted = false;
11686 
11687   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11688     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11689             Range, OEK_Member, DiagEmitted);
11690   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11691     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11692             Range, OEK_Variable, DiagEmitted);
11693   else
11694     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11695             Range, OEK_LValue, DiagEmitted);
11696   if (!DiagEmitted)
11697     DiagnoseConstAssignment(S, E, Loc);
11698 }
11699 
11700 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11701 /// emit an error and return true.  If so, return false.
11702 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11703   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11704 
11705   S.CheckShadowingDeclModification(E, Loc);
11706 
11707   SourceLocation OrigLoc = Loc;
11708   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11709                                                               &Loc);
11710   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11711     IsLV = Expr::MLV_InvalidMessageExpression;
11712   if (IsLV == Expr::MLV_Valid)
11713     return false;
11714 
11715   unsigned DiagID = 0;
11716   bool NeedType = false;
11717   switch (IsLV) { // C99 6.5.16p2
11718   case Expr::MLV_ConstQualified:
11719     // Use a specialized diagnostic when we're assigning to an object
11720     // from an enclosing function or block.
11721     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11722       if (NCCK == NCCK_Block)
11723         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11724       else
11725         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11726       break;
11727     }
11728 
11729     // In ARC, use some specialized diagnostics for occasions where we
11730     // infer 'const'.  These are always pseudo-strong variables.
11731     if (S.getLangOpts().ObjCAutoRefCount) {
11732       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11733       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11734         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11735 
11736         // Use the normal diagnostic if it's pseudo-__strong but the
11737         // user actually wrote 'const'.
11738         if (var->isARCPseudoStrong() &&
11739             (!var->getTypeSourceInfo() ||
11740              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11741           // There are three pseudo-strong cases:
11742           //  - self
11743           ObjCMethodDecl *method = S.getCurMethodDecl();
11744           if (method && var == method->getSelfDecl()) {
11745             DiagID = method->isClassMethod()
11746               ? diag::err_typecheck_arc_assign_self_class_method
11747               : diag::err_typecheck_arc_assign_self;
11748 
11749           //  - Objective-C externally_retained attribute.
11750           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11751                      isa<ParmVarDecl>(var)) {
11752             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11753 
11754           //  - fast enumeration variables
11755           } else {
11756             DiagID = diag::err_typecheck_arr_assign_enumeration;
11757           }
11758 
11759           SourceRange Assign;
11760           if (Loc != OrigLoc)
11761             Assign = SourceRange(OrigLoc, OrigLoc);
11762           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11763           // We need to preserve the AST regardless, so migration tool
11764           // can do its job.
11765           return false;
11766         }
11767       }
11768     }
11769 
11770     // If none of the special cases above are triggered, then this is a
11771     // simple const assignment.
11772     if (DiagID == 0) {
11773       DiagnoseConstAssignment(S, E, Loc);
11774       return true;
11775     }
11776 
11777     break;
11778   case Expr::MLV_ConstAddrSpace:
11779     DiagnoseConstAssignment(S, E, Loc);
11780     return true;
11781   case Expr::MLV_ConstQualifiedField:
11782     DiagnoseRecursiveConstFields(S, E, Loc);
11783     return true;
11784   case Expr::MLV_ArrayType:
11785   case Expr::MLV_ArrayTemporary:
11786     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11787     NeedType = true;
11788     break;
11789   case Expr::MLV_NotObjectType:
11790     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11791     NeedType = true;
11792     break;
11793   case Expr::MLV_LValueCast:
11794     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11795     break;
11796   case Expr::MLV_Valid:
11797     llvm_unreachable("did not take early return for MLV_Valid");
11798   case Expr::MLV_InvalidExpression:
11799   case Expr::MLV_MemberFunction:
11800   case Expr::MLV_ClassTemporary:
11801     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11802     break;
11803   case Expr::MLV_IncompleteType:
11804   case Expr::MLV_IncompleteVoidType:
11805     return S.RequireCompleteType(Loc, E->getType(),
11806              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11807   case Expr::MLV_DuplicateVectorComponents:
11808     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11809     break;
11810   case Expr::MLV_NoSetterProperty:
11811     llvm_unreachable("readonly properties should be processed differently");
11812   case Expr::MLV_InvalidMessageExpression:
11813     DiagID = diag::err_readonly_message_assignment;
11814     break;
11815   case Expr::MLV_SubObjCPropertySetting:
11816     DiagID = diag::err_no_subobject_property_setting;
11817     break;
11818   }
11819 
11820   SourceRange Assign;
11821   if (Loc != OrigLoc)
11822     Assign = SourceRange(OrigLoc, OrigLoc);
11823   if (NeedType)
11824     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11825   else
11826     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11827   return true;
11828 }
11829 
11830 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11831                                          SourceLocation Loc,
11832                                          Sema &Sema) {
11833   if (Sema.inTemplateInstantiation())
11834     return;
11835   if (Sema.isUnevaluatedContext())
11836     return;
11837   if (Loc.isInvalid() || Loc.isMacroID())
11838     return;
11839   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11840     return;
11841 
11842   // C / C++ fields
11843   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11844   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11845   if (ML && MR) {
11846     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11847       return;
11848     const ValueDecl *LHSDecl =
11849         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11850     const ValueDecl *RHSDecl =
11851         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11852     if (LHSDecl != RHSDecl)
11853       return;
11854     if (LHSDecl->getType().isVolatileQualified())
11855       return;
11856     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11857       if (RefTy->getPointeeType().isVolatileQualified())
11858         return;
11859 
11860     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11861   }
11862 
11863   // Objective-C instance variables
11864   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11865   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11866   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11867     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11868     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11869     if (RL && RR && RL->getDecl() == RR->getDecl())
11870       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11871   }
11872 }
11873 
11874 // C99 6.5.16.1
11875 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11876                                        SourceLocation Loc,
11877                                        QualType CompoundType) {
11878   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11879 
11880   // Verify that LHS is a modifiable lvalue, and emit error if not.
11881   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11882     return QualType();
11883 
11884   QualType LHSType = LHSExpr->getType();
11885   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11886                                              CompoundType;
11887   // OpenCL v1.2 s6.1.1.1 p2:
11888   // The half data type can only be used to declare a pointer to a buffer that
11889   // contains half values
11890   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11891     LHSType->isHalfType()) {
11892     Diag(Loc, diag::err_opencl_half_load_store) << 1
11893         << LHSType.getUnqualifiedType();
11894     return QualType();
11895   }
11896 
11897   AssignConvertType ConvTy;
11898   if (CompoundType.isNull()) {
11899     Expr *RHSCheck = RHS.get();
11900 
11901     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11902 
11903     QualType LHSTy(LHSType);
11904     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11905     if (RHS.isInvalid())
11906       return QualType();
11907     // Special case of NSObject attributes on c-style pointer types.
11908     if (ConvTy == IncompatiblePointer &&
11909         ((Context.isObjCNSObjectType(LHSType) &&
11910           RHSType->isObjCObjectPointerType()) ||
11911          (Context.isObjCNSObjectType(RHSType) &&
11912           LHSType->isObjCObjectPointerType())))
11913       ConvTy = Compatible;
11914 
11915     if (ConvTy == Compatible &&
11916         LHSType->isObjCObjectType())
11917         Diag(Loc, diag::err_objc_object_assignment)
11918           << LHSType;
11919 
11920     // If the RHS is a unary plus or minus, check to see if they = and + are
11921     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11922     // instead of "x += 4".
11923     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11924       RHSCheck = ICE->getSubExpr();
11925     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11926       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11927           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11928           // Only if the two operators are exactly adjacent.
11929           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11930           // And there is a space or other character before the subexpr of the
11931           // unary +/-.  We don't want to warn on "x=-1".
11932           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11933           UO->getSubExpr()->getBeginLoc().isFileID()) {
11934         Diag(Loc, diag::warn_not_compound_assign)
11935           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11936           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11937       }
11938     }
11939 
11940     if (ConvTy == Compatible) {
11941       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11942         // Warn about retain cycles where a block captures the LHS, but
11943         // not if the LHS is a simple variable into which the block is
11944         // being stored...unless that variable can be captured by reference!
11945         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11946         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11947         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11948           checkRetainCycles(LHSExpr, RHS.get());
11949       }
11950 
11951       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11952           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11953         // It is safe to assign a weak reference into a strong variable.
11954         // Although this code can still have problems:
11955         //   id x = self.weakProp;
11956         //   id y = self.weakProp;
11957         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11958         // paths through the function. This should be revisited if
11959         // -Wrepeated-use-of-weak is made flow-sensitive.
11960         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11961         // variable, which will be valid for the current autorelease scope.
11962         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11963                              RHS.get()->getBeginLoc()))
11964           getCurFunction()->markSafeWeakUse(RHS.get());
11965 
11966       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11967         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11968       }
11969     }
11970   } else {
11971     // Compound assignment "x += y"
11972     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11973   }
11974 
11975   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11976                                RHS.get(), AA_Assigning))
11977     return QualType();
11978 
11979   CheckForNullPointerDereference(*this, LHSExpr);
11980 
11981   if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
11982     if (CompoundType.isNull()) {
11983       // C++2a [expr.ass]p5:
11984       //   A simple-assignment whose left operand is of a volatile-qualified
11985       //   type is deprecated unless the assignment is either a discarded-value
11986       //   expression or an unevaluated operand
11987       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
11988     } else {
11989       // C++2a [expr.ass]p6:
11990       //   [Compound-assignment] expressions are deprecated if E1 has
11991       //   volatile-qualified type
11992       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
11993     }
11994   }
11995 
11996   // C99 6.5.16p3: The type of an assignment expression is the type of the
11997   // left operand unless the left operand has qualified type, in which case
11998   // it is the unqualified version of the type of the left operand.
11999   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12000   // is converted to the type of the assignment expression (above).
12001   // C++ 5.17p1: the type of the assignment expression is that of its left
12002   // operand.
12003   return (getLangOpts().CPlusPlus
12004           ? LHSType : LHSType.getUnqualifiedType());
12005 }
12006 
12007 // Only ignore explicit casts to void.
12008 static bool IgnoreCommaOperand(const Expr *E) {
12009   E = E->IgnoreParens();
12010 
12011   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12012     if (CE->getCastKind() == CK_ToVoid) {
12013       return true;
12014     }
12015 
12016     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12017     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12018         CE->getSubExpr()->getType()->isDependentType()) {
12019       return true;
12020     }
12021   }
12022 
12023   return false;
12024 }
12025 
12026 // Look for instances where it is likely the comma operator is confused with
12027 // another operator.  There is a whitelist of acceptable expressions for the
12028 // left hand side of the comma operator, otherwise emit a warning.
12029 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12030   // No warnings in macros
12031   if (Loc.isMacroID())
12032     return;
12033 
12034   // Don't warn in template instantiations.
12035   if (inTemplateInstantiation())
12036     return;
12037 
12038   // Scope isn't fine-grained enough to whitelist the specific cases, so
12039   // instead, skip more than needed, then call back into here with the
12040   // CommaVisitor in SemaStmt.cpp.
12041   // The whitelisted locations are the initialization and increment portions
12042   // of a for loop.  The additional checks are on the condition of
12043   // if statements, do/while loops, and for loops.
12044   // Differences in scope flags for C89 mode requires the extra logic.
12045   const unsigned ForIncrementFlags =
12046       getLangOpts().C99 || getLangOpts().CPlusPlus
12047           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12048           : Scope::ContinueScope | Scope::BreakScope;
12049   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12050   const unsigned ScopeFlags = getCurScope()->getFlags();
12051   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12052       (ScopeFlags & ForInitFlags) == ForInitFlags)
12053     return;
12054 
12055   // If there are multiple comma operators used together, get the RHS of the
12056   // of the comma operator as the LHS.
12057   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12058     if (BO->getOpcode() != BO_Comma)
12059       break;
12060     LHS = BO->getRHS();
12061   }
12062 
12063   // Only allow some expressions on LHS to not warn.
12064   if (IgnoreCommaOperand(LHS))
12065     return;
12066 
12067   Diag(Loc, diag::warn_comma_operator);
12068   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12069       << LHS->getSourceRange()
12070       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12071                                     LangOpts.CPlusPlus ? "static_cast<void>("
12072                                                        : "(void)(")
12073       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12074                                     ")");
12075 }
12076 
12077 // C99 6.5.17
12078 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12079                                    SourceLocation Loc) {
12080   LHS = S.CheckPlaceholderExpr(LHS.get());
12081   RHS = S.CheckPlaceholderExpr(RHS.get());
12082   if (LHS.isInvalid() || RHS.isInvalid())
12083     return QualType();
12084 
12085   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12086   // operands, but not unary promotions.
12087   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12088 
12089   // So we treat the LHS as a ignored value, and in C++ we allow the
12090   // containing site to determine what should be done with the RHS.
12091   LHS = S.IgnoredValueConversions(LHS.get());
12092   if (LHS.isInvalid())
12093     return QualType();
12094 
12095   S.DiagnoseUnusedExprResult(LHS.get());
12096 
12097   if (!S.getLangOpts().CPlusPlus) {
12098     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12099     if (RHS.isInvalid())
12100       return QualType();
12101     if (!RHS.get()->getType()->isVoidType())
12102       S.RequireCompleteType(Loc, RHS.get()->getType(),
12103                             diag::err_incomplete_type);
12104   }
12105 
12106   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12107     S.DiagnoseCommaOperator(LHS.get(), Loc);
12108 
12109   return RHS.get()->getType();
12110 }
12111 
12112 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12113 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12114 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12115                                                ExprValueKind &VK,
12116                                                ExprObjectKind &OK,
12117                                                SourceLocation OpLoc,
12118                                                bool IsInc, bool IsPrefix) {
12119   if (Op->isTypeDependent())
12120     return S.Context.DependentTy;
12121 
12122   QualType ResType = Op->getType();
12123   // Atomic types can be used for increment / decrement where the non-atomic
12124   // versions can, so ignore the _Atomic() specifier for the purpose of
12125   // checking.
12126   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12127     ResType = ResAtomicType->getValueType();
12128 
12129   assert(!ResType.isNull() && "no type for increment/decrement expression");
12130 
12131   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12132     // Decrement of bool is not allowed.
12133     if (!IsInc) {
12134       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12135       return QualType();
12136     }
12137     // Increment of bool sets it to true, but is deprecated.
12138     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12139                                               : diag::warn_increment_bool)
12140       << Op->getSourceRange();
12141   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12142     // Error on enum increments and decrements in C++ mode
12143     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12144     return QualType();
12145   } else if (ResType->isRealType()) {
12146     // OK!
12147   } else if (ResType->isPointerType()) {
12148     // C99 6.5.2.4p2, 6.5.6p2
12149     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12150       return QualType();
12151   } else if (ResType->isObjCObjectPointerType()) {
12152     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12153     // Otherwise, we just need a complete type.
12154     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12155         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12156       return QualType();
12157   } else if (ResType->isAnyComplexType()) {
12158     // C99 does not support ++/-- on complex types, we allow as an extension.
12159     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12160       << ResType << Op->getSourceRange();
12161   } else if (ResType->isPlaceholderType()) {
12162     ExprResult PR = S.CheckPlaceholderExpr(Op);
12163     if (PR.isInvalid()) return QualType();
12164     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12165                                           IsInc, IsPrefix);
12166   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12167     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12168   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12169              (ResType->castAs<VectorType>()->getVectorKind() !=
12170               VectorType::AltiVecBool)) {
12171     // The z vector extensions allow ++ and -- for non-bool vectors.
12172   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12173             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12174     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12175   } else {
12176     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12177       << ResType << int(IsInc) << Op->getSourceRange();
12178     return QualType();
12179   }
12180   // At this point, we know we have a real, complex or pointer type.
12181   // Now make sure the operand is a modifiable lvalue.
12182   if (CheckForModifiableLvalue(Op, OpLoc, S))
12183     return QualType();
12184   if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12185     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12186     //   An operand with volatile-qualified type is deprecated
12187     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12188         << IsInc << ResType;
12189   }
12190   // In C++, a prefix increment is the same type as the operand. Otherwise
12191   // (in C or with postfix), the increment is the unqualified type of the
12192   // operand.
12193   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12194     VK = VK_LValue;
12195     OK = Op->getObjectKind();
12196     return ResType;
12197   } else {
12198     VK = VK_RValue;
12199     return ResType.getUnqualifiedType();
12200   }
12201 }
12202 
12203 
12204 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12205 /// This routine allows us to typecheck complex/recursive expressions
12206 /// where the declaration is needed for type checking. We only need to
12207 /// handle cases when the expression references a function designator
12208 /// or is an lvalue. Here are some examples:
12209 ///  - &(x) => x
12210 ///  - &*****f => f for f a function designator.
12211 ///  - &s.xx => s
12212 ///  - &s.zz[1].yy -> s, if zz is an array
12213 ///  - *(x + 1) -> x, if x is an array
12214 ///  - &"123"[2] -> 0
12215 ///  - & __real__ x -> x
12216 static ValueDecl *getPrimaryDecl(Expr *E) {
12217   switch (E->getStmtClass()) {
12218   case Stmt::DeclRefExprClass:
12219     return cast<DeclRefExpr>(E)->getDecl();
12220   case Stmt::MemberExprClass:
12221     // If this is an arrow operator, the address is an offset from
12222     // the base's value, so the object the base refers to is
12223     // irrelevant.
12224     if (cast<MemberExpr>(E)->isArrow())
12225       return nullptr;
12226     // Otherwise, the expression refers to a part of the base
12227     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12228   case Stmt::ArraySubscriptExprClass: {
12229     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12230     // promotion of register arrays earlier.
12231     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12232     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12233       if (ICE->getSubExpr()->getType()->isArrayType())
12234         return getPrimaryDecl(ICE->getSubExpr());
12235     }
12236     return nullptr;
12237   }
12238   case Stmt::UnaryOperatorClass: {
12239     UnaryOperator *UO = cast<UnaryOperator>(E);
12240 
12241     switch(UO->getOpcode()) {
12242     case UO_Real:
12243     case UO_Imag:
12244     case UO_Extension:
12245       return getPrimaryDecl(UO->getSubExpr());
12246     default:
12247       return nullptr;
12248     }
12249   }
12250   case Stmt::ParenExprClass:
12251     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12252   case Stmt::ImplicitCastExprClass:
12253     // If the result of an implicit cast is an l-value, we care about
12254     // the sub-expression; otherwise, the result here doesn't matter.
12255     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12256   default:
12257     return nullptr;
12258   }
12259 }
12260 
12261 namespace {
12262   enum {
12263     AO_Bit_Field = 0,
12264     AO_Vector_Element = 1,
12265     AO_Property_Expansion = 2,
12266     AO_Register_Variable = 3,
12267     AO_No_Error = 4
12268   };
12269 }
12270 /// Diagnose invalid operand for address of operations.
12271 ///
12272 /// \param Type The type of operand which cannot have its address taken.
12273 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12274                                          Expr *E, unsigned Type) {
12275   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12276 }
12277 
12278 /// CheckAddressOfOperand - The operand of & must be either a function
12279 /// designator or an lvalue designating an object. If it is an lvalue, the
12280 /// object cannot be declared with storage class register or be a bit field.
12281 /// Note: The usual conversions are *not* applied to the operand of the &
12282 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12283 /// In C++, the operand might be an overloaded function name, in which case
12284 /// we allow the '&' but retain the overloaded-function type.
12285 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12286   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12287     if (PTy->getKind() == BuiltinType::Overload) {
12288       Expr *E = OrigOp.get()->IgnoreParens();
12289       if (!isa<OverloadExpr>(E)) {
12290         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12291         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12292           << OrigOp.get()->getSourceRange();
12293         return QualType();
12294       }
12295 
12296       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12297       if (isa<UnresolvedMemberExpr>(Ovl))
12298         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12299           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12300             << OrigOp.get()->getSourceRange();
12301           return QualType();
12302         }
12303 
12304       return Context.OverloadTy;
12305     }
12306 
12307     if (PTy->getKind() == BuiltinType::UnknownAny)
12308       return Context.UnknownAnyTy;
12309 
12310     if (PTy->getKind() == BuiltinType::BoundMember) {
12311       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12312         << OrigOp.get()->getSourceRange();
12313       return QualType();
12314     }
12315 
12316     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12317     if (OrigOp.isInvalid()) return QualType();
12318   }
12319 
12320   if (OrigOp.get()->isTypeDependent())
12321     return Context.DependentTy;
12322 
12323   assert(!OrigOp.get()->getType()->isPlaceholderType());
12324 
12325   // Make sure to ignore parentheses in subsequent checks
12326   Expr *op = OrigOp.get()->IgnoreParens();
12327 
12328   // In OpenCL captures for blocks called as lambda functions
12329   // are located in the private address space. Blocks used in
12330   // enqueue_kernel can be located in a different address space
12331   // depending on a vendor implementation. Thus preventing
12332   // taking an address of the capture to avoid invalid AS casts.
12333   if (LangOpts.OpenCL) {
12334     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12335     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12336       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12337       return QualType();
12338     }
12339   }
12340 
12341   if (getLangOpts().C99) {
12342     // Implement C99-only parts of addressof rules.
12343     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12344       if (uOp->getOpcode() == UO_Deref)
12345         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12346         // (assuming the deref expression is valid).
12347         return uOp->getSubExpr()->getType();
12348     }
12349     // Technically, there should be a check for array subscript
12350     // expressions here, but the result of one is always an lvalue anyway.
12351   }
12352   ValueDecl *dcl = getPrimaryDecl(op);
12353 
12354   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12355     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12356                                            op->getBeginLoc()))
12357       return QualType();
12358 
12359   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12360   unsigned AddressOfError = AO_No_Error;
12361 
12362   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12363     bool sfinae = (bool)isSFINAEContext();
12364     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12365                                   : diag::ext_typecheck_addrof_temporary)
12366       << op->getType() << op->getSourceRange();
12367     if (sfinae)
12368       return QualType();
12369     // Materialize the temporary as an lvalue so that we can take its address.
12370     OrigOp = op =
12371         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12372   } else if (isa<ObjCSelectorExpr>(op)) {
12373     return Context.getPointerType(op->getType());
12374   } else if (lval == Expr::LV_MemberFunction) {
12375     // If it's an instance method, make a member pointer.
12376     // The expression must have exactly the form &A::foo.
12377 
12378     // If the underlying expression isn't a decl ref, give up.
12379     if (!isa<DeclRefExpr>(op)) {
12380       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12381         << OrigOp.get()->getSourceRange();
12382       return QualType();
12383     }
12384     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12385     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12386 
12387     // The id-expression was parenthesized.
12388     if (OrigOp.get() != DRE) {
12389       Diag(OpLoc, diag::err_parens_pointer_member_function)
12390         << OrigOp.get()->getSourceRange();
12391 
12392     // The method was named without a qualifier.
12393     } else if (!DRE->getQualifier()) {
12394       if (MD->getParent()->getName().empty())
12395         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12396           << op->getSourceRange();
12397       else {
12398         SmallString<32> Str;
12399         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12400         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12401           << op->getSourceRange()
12402           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12403       }
12404     }
12405 
12406     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12407     if (isa<CXXDestructorDecl>(MD))
12408       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12409 
12410     QualType MPTy = Context.getMemberPointerType(
12411         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12412     // Under the MS ABI, lock down the inheritance model now.
12413     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12414       (void)isCompleteType(OpLoc, MPTy);
12415     return MPTy;
12416   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12417     // C99 6.5.3.2p1
12418     // The operand must be either an l-value or a function designator
12419     if (!op->getType()->isFunctionType()) {
12420       // Use a special diagnostic for loads from property references.
12421       if (isa<PseudoObjectExpr>(op)) {
12422         AddressOfError = AO_Property_Expansion;
12423       } else {
12424         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12425           << op->getType() << op->getSourceRange();
12426         return QualType();
12427       }
12428     }
12429   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12430     // The operand cannot be a bit-field
12431     AddressOfError = AO_Bit_Field;
12432   } else if (op->getObjectKind() == OK_VectorComponent) {
12433     // The operand cannot be an element of a vector
12434     AddressOfError = AO_Vector_Element;
12435   } else if (dcl) { // C99 6.5.3.2p1
12436     // We have an lvalue with a decl. Make sure the decl is not declared
12437     // with the register storage-class specifier.
12438     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12439       // in C++ it is not error to take address of a register
12440       // variable (c++03 7.1.1P3)
12441       if (vd->getStorageClass() == SC_Register &&
12442           !getLangOpts().CPlusPlus) {
12443         AddressOfError = AO_Register_Variable;
12444       }
12445     } else if (isa<MSPropertyDecl>(dcl)) {
12446       AddressOfError = AO_Property_Expansion;
12447     } else if (isa<FunctionTemplateDecl>(dcl)) {
12448       return Context.OverloadTy;
12449     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12450       // Okay: we can take the address of a field.
12451       // Could be a pointer to member, though, if there is an explicit
12452       // scope qualifier for the class.
12453       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12454         DeclContext *Ctx = dcl->getDeclContext();
12455         if (Ctx && Ctx->isRecord()) {
12456           if (dcl->getType()->isReferenceType()) {
12457             Diag(OpLoc,
12458                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12459               << dcl->getDeclName() << dcl->getType();
12460             return QualType();
12461           }
12462 
12463           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12464             Ctx = Ctx->getParent();
12465 
12466           QualType MPTy = Context.getMemberPointerType(
12467               op->getType(),
12468               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12469           // Under the MS ABI, lock down the inheritance model now.
12470           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12471             (void)isCompleteType(OpLoc, MPTy);
12472           return MPTy;
12473         }
12474       }
12475     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12476                !isa<BindingDecl>(dcl))
12477       llvm_unreachable("Unknown/unexpected decl type");
12478   }
12479 
12480   if (AddressOfError != AO_No_Error) {
12481     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12482     return QualType();
12483   }
12484 
12485   if (lval == Expr::LV_IncompleteVoidType) {
12486     // Taking the address of a void variable is technically illegal, but we
12487     // allow it in cases which are otherwise valid.
12488     // Example: "extern void x; void* y = &x;".
12489     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12490   }
12491 
12492   // If the operand has type "type", the result has type "pointer to type".
12493   if (op->getType()->isObjCObjectType())
12494     return Context.getObjCObjectPointerType(op->getType());
12495 
12496   CheckAddressOfPackedMember(op);
12497 
12498   return Context.getPointerType(op->getType());
12499 }
12500 
12501 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12502   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12503   if (!DRE)
12504     return;
12505   const Decl *D = DRE->getDecl();
12506   if (!D)
12507     return;
12508   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12509   if (!Param)
12510     return;
12511   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12512     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12513       return;
12514   if (FunctionScopeInfo *FD = S.getCurFunction())
12515     if (!FD->ModifiedNonNullParams.count(Param))
12516       FD->ModifiedNonNullParams.insert(Param);
12517 }
12518 
12519 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12520 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12521                                         SourceLocation OpLoc) {
12522   if (Op->isTypeDependent())
12523     return S.Context.DependentTy;
12524 
12525   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12526   if (ConvResult.isInvalid())
12527     return QualType();
12528   Op = ConvResult.get();
12529   QualType OpTy = Op->getType();
12530   QualType Result;
12531 
12532   if (isa<CXXReinterpretCastExpr>(Op)) {
12533     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12534     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12535                                      Op->getSourceRange());
12536   }
12537 
12538   if (const PointerType *PT = OpTy->getAs<PointerType>())
12539   {
12540     Result = PT->getPointeeType();
12541   }
12542   else if (const ObjCObjectPointerType *OPT =
12543              OpTy->getAs<ObjCObjectPointerType>())
12544     Result = OPT->getPointeeType();
12545   else {
12546     ExprResult PR = S.CheckPlaceholderExpr(Op);
12547     if (PR.isInvalid()) return QualType();
12548     if (PR.get() != Op)
12549       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12550   }
12551 
12552   if (Result.isNull()) {
12553     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12554       << OpTy << Op->getSourceRange();
12555     return QualType();
12556   }
12557 
12558   // Note that per both C89 and C99, indirection is always legal, even if Result
12559   // is an incomplete type or void.  It would be possible to warn about
12560   // dereferencing a void pointer, but it's completely well-defined, and such a
12561   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12562   // for pointers to 'void' but is fine for any other pointer type:
12563   //
12564   // C++ [expr.unary.op]p1:
12565   //   [...] the expression to which [the unary * operator] is applied shall
12566   //   be a pointer to an object type, or a pointer to a function type
12567   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12568     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12569       << OpTy << Op->getSourceRange();
12570 
12571   // Dereferences are usually l-values...
12572   VK = VK_LValue;
12573 
12574   // ...except that certain expressions are never l-values in C.
12575   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12576     VK = VK_RValue;
12577 
12578   return Result;
12579 }
12580 
12581 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12582   BinaryOperatorKind Opc;
12583   switch (Kind) {
12584   default: llvm_unreachable("Unknown binop!");
12585   case tok::periodstar:           Opc = BO_PtrMemD; break;
12586   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12587   case tok::star:                 Opc = BO_Mul; break;
12588   case tok::slash:                Opc = BO_Div; break;
12589   case tok::percent:              Opc = BO_Rem; break;
12590   case tok::plus:                 Opc = BO_Add; break;
12591   case tok::minus:                Opc = BO_Sub; break;
12592   case tok::lessless:             Opc = BO_Shl; break;
12593   case tok::greatergreater:       Opc = BO_Shr; break;
12594   case tok::lessequal:            Opc = BO_LE; break;
12595   case tok::less:                 Opc = BO_LT; break;
12596   case tok::greaterequal:         Opc = BO_GE; break;
12597   case tok::greater:              Opc = BO_GT; break;
12598   case tok::exclaimequal:         Opc = BO_NE; break;
12599   case tok::equalequal:           Opc = BO_EQ; break;
12600   case tok::spaceship:            Opc = BO_Cmp; break;
12601   case tok::amp:                  Opc = BO_And; break;
12602   case tok::caret:                Opc = BO_Xor; break;
12603   case tok::pipe:                 Opc = BO_Or; break;
12604   case tok::ampamp:               Opc = BO_LAnd; break;
12605   case tok::pipepipe:             Opc = BO_LOr; break;
12606   case tok::equal:                Opc = BO_Assign; break;
12607   case tok::starequal:            Opc = BO_MulAssign; break;
12608   case tok::slashequal:           Opc = BO_DivAssign; break;
12609   case tok::percentequal:         Opc = BO_RemAssign; break;
12610   case tok::plusequal:            Opc = BO_AddAssign; break;
12611   case tok::minusequal:           Opc = BO_SubAssign; break;
12612   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12613   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12614   case tok::ampequal:             Opc = BO_AndAssign; break;
12615   case tok::caretequal:           Opc = BO_XorAssign; break;
12616   case tok::pipeequal:            Opc = BO_OrAssign; break;
12617   case tok::comma:                Opc = BO_Comma; break;
12618   }
12619   return Opc;
12620 }
12621 
12622 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12623   tok::TokenKind Kind) {
12624   UnaryOperatorKind Opc;
12625   switch (Kind) {
12626   default: llvm_unreachable("Unknown unary op!");
12627   case tok::plusplus:     Opc = UO_PreInc; break;
12628   case tok::minusminus:   Opc = UO_PreDec; break;
12629   case tok::amp:          Opc = UO_AddrOf; break;
12630   case tok::star:         Opc = UO_Deref; break;
12631   case tok::plus:         Opc = UO_Plus; break;
12632   case tok::minus:        Opc = UO_Minus; break;
12633   case tok::tilde:        Opc = UO_Not; break;
12634   case tok::exclaim:      Opc = UO_LNot; break;
12635   case tok::kw___real:    Opc = UO_Real; break;
12636   case tok::kw___imag:    Opc = UO_Imag; break;
12637   case tok::kw___extension__: Opc = UO_Extension; break;
12638   }
12639   return Opc;
12640 }
12641 
12642 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12643 /// This warning suppressed in the event of macro expansions.
12644 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12645                                    SourceLocation OpLoc, bool IsBuiltin) {
12646   if (S.inTemplateInstantiation())
12647     return;
12648   if (S.isUnevaluatedContext())
12649     return;
12650   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12651     return;
12652   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12653   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12654   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12655   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12656   if (!LHSDeclRef || !RHSDeclRef ||
12657       LHSDeclRef->getLocation().isMacroID() ||
12658       RHSDeclRef->getLocation().isMacroID())
12659     return;
12660   const ValueDecl *LHSDecl =
12661     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12662   const ValueDecl *RHSDecl =
12663     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12664   if (LHSDecl != RHSDecl)
12665     return;
12666   if (LHSDecl->getType().isVolatileQualified())
12667     return;
12668   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12669     if (RefTy->getPointeeType().isVolatileQualified())
12670       return;
12671 
12672   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12673                           : diag::warn_self_assignment_overloaded)
12674       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12675       << RHSExpr->getSourceRange();
12676 }
12677 
12678 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12679 /// is usually indicative of introspection within the Objective-C pointer.
12680 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12681                                           SourceLocation OpLoc) {
12682   if (!S.getLangOpts().ObjC)
12683     return;
12684 
12685   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12686   const Expr *LHS = L.get();
12687   const Expr *RHS = R.get();
12688 
12689   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12690     ObjCPointerExpr = LHS;
12691     OtherExpr = RHS;
12692   }
12693   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12694     ObjCPointerExpr = RHS;
12695     OtherExpr = LHS;
12696   }
12697 
12698   // This warning is deliberately made very specific to reduce false
12699   // positives with logic that uses '&' for hashing.  This logic mainly
12700   // looks for code trying to introspect into tagged pointers, which
12701   // code should generally never do.
12702   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12703     unsigned Diag = diag::warn_objc_pointer_masking;
12704     // Determine if we are introspecting the result of performSelectorXXX.
12705     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12706     // Special case messages to -performSelector and friends, which
12707     // can return non-pointer values boxed in a pointer value.
12708     // Some clients may wish to silence warnings in this subcase.
12709     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12710       Selector S = ME->getSelector();
12711       StringRef SelArg0 = S.getNameForSlot(0);
12712       if (SelArg0.startswith("performSelector"))
12713         Diag = diag::warn_objc_pointer_masking_performSelector;
12714     }
12715 
12716     S.Diag(OpLoc, Diag)
12717       << ObjCPointerExpr->getSourceRange();
12718   }
12719 }
12720 
12721 static NamedDecl *getDeclFromExpr(Expr *E) {
12722   if (!E)
12723     return nullptr;
12724   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12725     return DRE->getDecl();
12726   if (auto *ME = dyn_cast<MemberExpr>(E))
12727     return ME->getMemberDecl();
12728   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12729     return IRE->getDecl();
12730   return nullptr;
12731 }
12732 
12733 // This helper function promotes a binary operator's operands (which are of a
12734 // half vector type) to a vector of floats and then truncates the result to
12735 // a vector of either half or short.
12736 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12737                                       BinaryOperatorKind Opc, QualType ResultTy,
12738                                       ExprValueKind VK, ExprObjectKind OK,
12739                                       bool IsCompAssign, SourceLocation OpLoc,
12740                                       FPOptions FPFeatures) {
12741   auto &Context = S.getASTContext();
12742   assert((isVector(ResultTy, Context.HalfTy) ||
12743           isVector(ResultTy, Context.ShortTy)) &&
12744          "Result must be a vector of half or short");
12745   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12746          isVector(RHS.get()->getType(), Context.HalfTy) &&
12747          "both operands expected to be a half vector");
12748 
12749   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12750   QualType BinOpResTy = RHS.get()->getType();
12751 
12752   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12753   // change BinOpResTy to a vector of ints.
12754   if (isVector(ResultTy, Context.ShortTy))
12755     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12756 
12757   if (IsCompAssign)
12758     return new (Context) CompoundAssignOperator(
12759         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12760         OpLoc, FPFeatures);
12761 
12762   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12763   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12764                                           VK, OK, OpLoc, FPFeatures);
12765   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12766 }
12767 
12768 static std::pair<ExprResult, ExprResult>
12769 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12770                            Expr *RHSExpr) {
12771   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12772   if (!S.getLangOpts().CPlusPlus) {
12773     // C cannot handle TypoExpr nodes on either side of a binop because it
12774     // doesn't handle dependent types properly, so make sure any TypoExprs have
12775     // been dealt with before checking the operands.
12776     LHS = S.CorrectDelayedTyposInExpr(LHS);
12777     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12778       if (Opc != BO_Assign)
12779         return ExprResult(E);
12780       // Avoid correcting the RHS to the same Expr as the LHS.
12781       Decl *D = getDeclFromExpr(E);
12782       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12783     });
12784   }
12785   return std::make_pair(LHS, RHS);
12786 }
12787 
12788 /// Returns true if conversion between vectors of halfs and vectors of floats
12789 /// is needed.
12790 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12791                                      QualType SrcType) {
12792   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12793          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12794          isVector(SrcType, Ctx.HalfTy);
12795 }
12796 
12797 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12798 /// operator @p Opc at location @c TokLoc. This routine only supports
12799 /// built-in operations; ActOnBinOp handles overloaded operators.
12800 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12801                                     BinaryOperatorKind Opc,
12802                                     Expr *LHSExpr, Expr *RHSExpr) {
12803   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12804     // The syntax only allows initializer lists on the RHS of assignment,
12805     // so we don't need to worry about accepting invalid code for
12806     // non-assignment operators.
12807     // C++11 5.17p9:
12808     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12809     //   of x = {} is x = T().
12810     InitializationKind Kind = InitializationKind::CreateDirectList(
12811         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12812     InitializedEntity Entity =
12813         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12814     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12815     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12816     if (Init.isInvalid())
12817       return Init;
12818     RHSExpr = Init.get();
12819   }
12820 
12821   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12822   QualType ResultTy;     // Result type of the binary operator.
12823   // The following two variables are used for compound assignment operators
12824   QualType CompLHSTy;    // Type of LHS after promotions for computation
12825   QualType CompResultTy; // Type of computation result
12826   ExprValueKind VK = VK_RValue;
12827   ExprObjectKind OK = OK_Ordinary;
12828   bool ConvertHalfVec = false;
12829 
12830   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12831   if (!LHS.isUsable() || !RHS.isUsable())
12832     return ExprError();
12833 
12834   if (getLangOpts().OpenCL) {
12835     QualType LHSTy = LHSExpr->getType();
12836     QualType RHSTy = RHSExpr->getType();
12837     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12838     // the ATOMIC_VAR_INIT macro.
12839     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12840       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12841       if (BO_Assign == Opc)
12842         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12843       else
12844         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12845       return ExprError();
12846     }
12847 
12848     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12849     // only with a builtin functions and therefore should be disallowed here.
12850     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12851         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12852         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12853         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12854       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12855       return ExprError();
12856     }
12857   }
12858 
12859   // Diagnose operations on the unsupported types for OpenMP device compilation.
12860   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12861     if (Opc != BO_Assign && Opc != BO_Comma) {
12862       checkOpenMPDeviceExpr(LHSExpr);
12863       checkOpenMPDeviceExpr(RHSExpr);
12864     }
12865   }
12866 
12867   switch (Opc) {
12868   case BO_Assign:
12869     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12870     if (getLangOpts().CPlusPlus &&
12871         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12872       VK = LHS.get()->getValueKind();
12873       OK = LHS.get()->getObjectKind();
12874     }
12875     if (!ResultTy.isNull()) {
12876       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12877       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12878 
12879       // Avoid copying a block to the heap if the block is assigned to a local
12880       // auto variable that is declared in the same scope as the block. This
12881       // optimization is unsafe if the local variable is declared in an outer
12882       // scope. For example:
12883       //
12884       // BlockTy b;
12885       // {
12886       //   b = ^{...};
12887       // }
12888       // // It is unsafe to invoke the block here if it wasn't copied to the
12889       // // heap.
12890       // b();
12891 
12892       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12893         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12894           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12895             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12896               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12897 
12898       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
12899         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
12900                               NTCUC_Assignment, NTCUK_Copy);
12901     }
12902     RecordModifiableNonNullParam(*this, LHS.get());
12903     break;
12904   case BO_PtrMemD:
12905   case BO_PtrMemI:
12906     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12907                                             Opc == BO_PtrMemI);
12908     break;
12909   case BO_Mul:
12910   case BO_Div:
12911     ConvertHalfVec = true;
12912     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12913                                            Opc == BO_Div);
12914     break;
12915   case BO_Rem:
12916     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12917     break;
12918   case BO_Add:
12919     ConvertHalfVec = true;
12920     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12921     break;
12922   case BO_Sub:
12923     ConvertHalfVec = true;
12924     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12925     break;
12926   case BO_Shl:
12927   case BO_Shr:
12928     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12929     break;
12930   case BO_LE:
12931   case BO_LT:
12932   case BO_GE:
12933   case BO_GT:
12934     ConvertHalfVec = true;
12935     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12936     break;
12937   case BO_EQ:
12938   case BO_NE:
12939     ConvertHalfVec = true;
12940     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12941     break;
12942   case BO_Cmp:
12943     ConvertHalfVec = true;
12944     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12945     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12946     break;
12947   case BO_And:
12948     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12949     LLVM_FALLTHROUGH;
12950   case BO_Xor:
12951   case BO_Or:
12952     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12953     break;
12954   case BO_LAnd:
12955   case BO_LOr:
12956     ConvertHalfVec = true;
12957     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12958     break;
12959   case BO_MulAssign:
12960   case BO_DivAssign:
12961     ConvertHalfVec = true;
12962     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12963                                                Opc == BO_DivAssign);
12964     CompLHSTy = CompResultTy;
12965     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12966       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12967     break;
12968   case BO_RemAssign:
12969     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12970     CompLHSTy = CompResultTy;
12971     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12972       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12973     break;
12974   case BO_AddAssign:
12975     ConvertHalfVec = true;
12976     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12977     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12978       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12979     break;
12980   case BO_SubAssign:
12981     ConvertHalfVec = true;
12982     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12983     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12984       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12985     break;
12986   case BO_ShlAssign:
12987   case BO_ShrAssign:
12988     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12989     CompLHSTy = CompResultTy;
12990     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12991       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12992     break;
12993   case BO_AndAssign:
12994   case BO_OrAssign: // fallthrough
12995     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12996     LLVM_FALLTHROUGH;
12997   case BO_XorAssign:
12998     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12999     CompLHSTy = CompResultTy;
13000     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13001       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13002     break;
13003   case BO_Comma:
13004     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13005     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13006       VK = RHS.get()->getValueKind();
13007       OK = RHS.get()->getObjectKind();
13008     }
13009     break;
13010   }
13011   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13012     return ExprError();
13013 
13014   // Some of the binary operations require promoting operands of half vector to
13015   // float vectors and truncating the result back to half vector. For now, we do
13016   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13017   // arm64).
13018   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13019          isVector(LHS.get()->getType(), Context.HalfTy) &&
13020          "both sides are half vectors or neither sides are");
13021   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
13022                                             LHS.get()->getType());
13023 
13024   // Check for array bounds violations for both sides of the BinaryOperator
13025   CheckArrayAccess(LHS.get());
13026   CheckArrayAccess(RHS.get());
13027 
13028   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13029     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13030                                                  &Context.Idents.get("object_setClass"),
13031                                                  SourceLocation(), LookupOrdinaryName);
13032     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13033       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13034       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13035           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13036                                         "object_setClass(")
13037           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13038                                           ",")
13039           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13040     }
13041     else
13042       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13043   }
13044   else if (const ObjCIvarRefExpr *OIRE =
13045            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13046     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13047 
13048   // Opc is not a compound assignment if CompResultTy is null.
13049   if (CompResultTy.isNull()) {
13050     if (ConvertHalfVec)
13051       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13052                                  OpLoc, FPFeatures);
13053     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13054                                         OK, OpLoc, FPFeatures);
13055   }
13056 
13057   // Handle compound assignments.
13058   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13059       OK_ObjCProperty) {
13060     VK = VK_LValue;
13061     OK = LHS.get()->getObjectKind();
13062   }
13063 
13064   if (ConvertHalfVec)
13065     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13066                                OpLoc, FPFeatures);
13067 
13068   return new (Context) CompoundAssignOperator(
13069       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13070       OpLoc, FPFeatures);
13071 }
13072 
13073 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13074 /// operators are mixed in a way that suggests that the programmer forgot that
13075 /// comparison operators have higher precedence. The most typical example of
13076 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13077 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13078                                       SourceLocation OpLoc, Expr *LHSExpr,
13079                                       Expr *RHSExpr) {
13080   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13081   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13082 
13083   // Check that one of the sides is a comparison operator and the other isn't.
13084   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13085   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13086   if (isLeftComp == isRightComp)
13087     return;
13088 
13089   // Bitwise operations are sometimes used as eager logical ops.
13090   // Don't diagnose this.
13091   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13092   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13093   if (isLeftBitwise || isRightBitwise)
13094     return;
13095 
13096   SourceRange DiagRange = isLeftComp
13097                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13098                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13099   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13100   SourceRange ParensRange =
13101       isLeftComp
13102           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13103           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13104 
13105   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13106     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13107   SuggestParentheses(Self, OpLoc,
13108     Self.PDiag(diag::note_precedence_silence) << OpStr,
13109     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13110   SuggestParentheses(Self, OpLoc,
13111     Self.PDiag(diag::note_precedence_bitwise_first)
13112       << BinaryOperator::getOpcodeStr(Opc),
13113     ParensRange);
13114 }
13115 
13116 /// It accepts a '&&' expr that is inside a '||' one.
13117 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13118 /// in parentheses.
13119 static void
13120 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13121                                        BinaryOperator *Bop) {
13122   assert(Bop->getOpcode() == BO_LAnd);
13123   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13124       << Bop->getSourceRange() << OpLoc;
13125   SuggestParentheses(Self, Bop->getOperatorLoc(),
13126     Self.PDiag(diag::note_precedence_silence)
13127       << Bop->getOpcodeStr(),
13128     Bop->getSourceRange());
13129 }
13130 
13131 /// Returns true if the given expression can be evaluated as a constant
13132 /// 'true'.
13133 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13134   bool Res;
13135   return !E->isValueDependent() &&
13136          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13137 }
13138 
13139 /// Returns true if the given expression can be evaluated as a constant
13140 /// 'false'.
13141 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13142   bool Res;
13143   return !E->isValueDependent() &&
13144          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13145 }
13146 
13147 /// Look for '&&' in the left hand of a '||' expr.
13148 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13149                                              Expr *LHSExpr, Expr *RHSExpr) {
13150   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13151     if (Bop->getOpcode() == BO_LAnd) {
13152       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13153       if (EvaluatesAsFalse(S, RHSExpr))
13154         return;
13155       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13156       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13157         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13158     } else if (Bop->getOpcode() == BO_LOr) {
13159       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13160         // If it's "a || b && 1 || c" we didn't warn earlier for
13161         // "a || b && 1", but warn now.
13162         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13163           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13164       }
13165     }
13166   }
13167 }
13168 
13169 /// Look for '&&' in the right hand of a '||' expr.
13170 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13171                                              Expr *LHSExpr, Expr *RHSExpr) {
13172   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13173     if (Bop->getOpcode() == BO_LAnd) {
13174       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13175       if (EvaluatesAsFalse(S, LHSExpr))
13176         return;
13177       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13178       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13179         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13180     }
13181   }
13182 }
13183 
13184 /// Look for bitwise op in the left or right hand of a bitwise op with
13185 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13186 /// the '&' expression in parentheses.
13187 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13188                                          SourceLocation OpLoc, Expr *SubExpr) {
13189   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13190     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13191       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13192         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13193         << Bop->getSourceRange() << OpLoc;
13194       SuggestParentheses(S, Bop->getOperatorLoc(),
13195         S.PDiag(diag::note_precedence_silence)
13196           << Bop->getOpcodeStr(),
13197         Bop->getSourceRange());
13198     }
13199   }
13200 }
13201 
13202 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13203                                     Expr *SubExpr, StringRef Shift) {
13204   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13205     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13206       StringRef Op = Bop->getOpcodeStr();
13207       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13208           << Bop->getSourceRange() << OpLoc << Shift << Op;
13209       SuggestParentheses(S, Bop->getOperatorLoc(),
13210           S.PDiag(diag::note_precedence_silence) << Op,
13211           Bop->getSourceRange());
13212     }
13213   }
13214 }
13215 
13216 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13217                                  Expr *LHSExpr, Expr *RHSExpr) {
13218   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13219   if (!OCE)
13220     return;
13221 
13222   FunctionDecl *FD = OCE->getDirectCallee();
13223   if (!FD || !FD->isOverloadedOperator())
13224     return;
13225 
13226   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13227   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13228     return;
13229 
13230   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13231       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13232       << (Kind == OO_LessLess);
13233   SuggestParentheses(S, OCE->getOperatorLoc(),
13234                      S.PDiag(diag::note_precedence_silence)
13235                          << (Kind == OO_LessLess ? "<<" : ">>"),
13236                      OCE->getSourceRange());
13237   SuggestParentheses(
13238       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13239       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13240 }
13241 
13242 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13243 /// precedence.
13244 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13245                                     SourceLocation OpLoc, Expr *LHSExpr,
13246                                     Expr *RHSExpr){
13247   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13248   if (BinaryOperator::isBitwiseOp(Opc))
13249     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13250 
13251   // Diagnose "arg1 & arg2 | arg3"
13252   if ((Opc == BO_Or || Opc == BO_Xor) &&
13253       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13254     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13255     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13256   }
13257 
13258   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13259   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13260   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13261     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13262     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13263   }
13264 
13265   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13266       || Opc == BO_Shr) {
13267     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13268     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13269     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13270   }
13271 
13272   // Warn on overloaded shift operators and comparisons, such as:
13273   // cout << 5 == 4;
13274   if (BinaryOperator::isComparisonOp(Opc))
13275     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13276 }
13277 
13278 // Binary Operators.  'Tok' is the token for the operator.
13279 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13280                             tok::TokenKind Kind,
13281                             Expr *LHSExpr, Expr *RHSExpr) {
13282   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13283   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13284   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13285 
13286   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13287   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13288 
13289   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13290 }
13291 
13292 /// Build an overloaded binary operator expression in the given scope.
13293 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13294                                        BinaryOperatorKind Opc,
13295                                        Expr *LHS, Expr *RHS) {
13296   switch (Opc) {
13297   case BO_Assign:
13298   case BO_DivAssign:
13299   case BO_RemAssign:
13300   case BO_SubAssign:
13301   case BO_AndAssign:
13302   case BO_OrAssign:
13303   case BO_XorAssign:
13304     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13305     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13306     break;
13307   default:
13308     break;
13309   }
13310 
13311   // Find all of the overloaded operators visible from this
13312   // point. We perform both an operator-name lookup from the local
13313   // scope and an argument-dependent lookup based on the types of
13314   // the arguments.
13315   UnresolvedSet<16> Functions;
13316   OverloadedOperatorKind OverOp
13317     = BinaryOperator::getOverloadedOperator(Opc);
13318   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13319     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13320                                    RHS->getType(), Functions);
13321 
13322   // In C++20 onwards, we may have a second operator to look up.
13323   if (S.getLangOpts().CPlusPlus2a) {
13324     if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13325       S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13326                                      RHS->getType(), Functions);
13327   }
13328 
13329   // Build the (potentially-overloaded, potentially-dependent)
13330   // binary operation.
13331   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13332 }
13333 
13334 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13335                             BinaryOperatorKind Opc,
13336                             Expr *LHSExpr, Expr *RHSExpr) {
13337   ExprResult LHS, RHS;
13338   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13339   if (!LHS.isUsable() || !RHS.isUsable())
13340     return ExprError();
13341   LHSExpr = LHS.get();
13342   RHSExpr = RHS.get();
13343 
13344   // We want to end up calling one of checkPseudoObjectAssignment
13345   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13346   // both expressions are overloadable or either is type-dependent),
13347   // or CreateBuiltinBinOp (in any other case).  We also want to get
13348   // any placeholder types out of the way.
13349 
13350   // Handle pseudo-objects in the LHS.
13351   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13352     // Assignments with a pseudo-object l-value need special analysis.
13353     if (pty->getKind() == BuiltinType::PseudoObject &&
13354         BinaryOperator::isAssignmentOp(Opc))
13355       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13356 
13357     // Don't resolve overloads if the other type is overloadable.
13358     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13359       // We can't actually test that if we still have a placeholder,
13360       // though.  Fortunately, none of the exceptions we see in that
13361       // code below are valid when the LHS is an overload set.  Note
13362       // that an overload set can be dependently-typed, but it never
13363       // instantiates to having an overloadable type.
13364       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13365       if (resolvedRHS.isInvalid()) return ExprError();
13366       RHSExpr = resolvedRHS.get();
13367 
13368       if (RHSExpr->isTypeDependent() ||
13369           RHSExpr->getType()->isOverloadableType())
13370         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13371     }
13372 
13373     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13374     // template, diagnose the missing 'template' keyword instead of diagnosing
13375     // an invalid use of a bound member function.
13376     //
13377     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13378     // to C++1z [over.over]/1.4, but we already checked for that case above.
13379     if (Opc == BO_LT && inTemplateInstantiation() &&
13380         (pty->getKind() == BuiltinType::BoundMember ||
13381          pty->getKind() == BuiltinType::Overload)) {
13382       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13383       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13384           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13385             return isa<FunctionTemplateDecl>(ND);
13386           })) {
13387         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13388                                 : OE->getNameLoc(),
13389              diag::err_template_kw_missing)
13390           << OE->getName().getAsString() << "";
13391         return ExprError();
13392       }
13393     }
13394 
13395     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13396     if (LHS.isInvalid()) return ExprError();
13397     LHSExpr = LHS.get();
13398   }
13399 
13400   // Handle pseudo-objects in the RHS.
13401   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13402     // An overload in the RHS can potentially be resolved by the type
13403     // being assigned to.
13404     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13405       if (getLangOpts().CPlusPlus &&
13406           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13407            LHSExpr->getType()->isOverloadableType()))
13408         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13409 
13410       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13411     }
13412 
13413     // Don't resolve overloads if the other type is overloadable.
13414     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13415         LHSExpr->getType()->isOverloadableType())
13416       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13417 
13418     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13419     if (!resolvedRHS.isUsable()) return ExprError();
13420     RHSExpr = resolvedRHS.get();
13421   }
13422 
13423   if (getLangOpts().CPlusPlus) {
13424     // If either expression is type-dependent, always build an
13425     // overloaded op.
13426     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13427       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13428 
13429     // Otherwise, build an overloaded op if either expression has an
13430     // overloadable type.
13431     if (LHSExpr->getType()->isOverloadableType() ||
13432         RHSExpr->getType()->isOverloadableType())
13433       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13434   }
13435 
13436   // Build a built-in binary operation.
13437   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13438 }
13439 
13440 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13441   if (T.isNull() || T->isDependentType())
13442     return false;
13443 
13444   if (!T->isPromotableIntegerType())
13445     return true;
13446 
13447   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13448 }
13449 
13450 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13451                                       UnaryOperatorKind Opc,
13452                                       Expr *InputExpr) {
13453   ExprResult Input = InputExpr;
13454   ExprValueKind VK = VK_RValue;
13455   ExprObjectKind OK = OK_Ordinary;
13456   QualType resultType;
13457   bool CanOverflow = false;
13458 
13459   bool ConvertHalfVec = false;
13460   if (getLangOpts().OpenCL) {
13461     QualType Ty = InputExpr->getType();
13462     // The only legal unary operation for atomics is '&'.
13463     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13464     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13465     // only with a builtin functions and therefore should be disallowed here.
13466         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13467         || Ty->isBlockPointerType())) {
13468       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13469                        << InputExpr->getType()
13470                        << Input.get()->getSourceRange());
13471     }
13472   }
13473   // Diagnose operations on the unsupported types for OpenMP device compilation.
13474   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13475     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13476         UnaryOperator::isArithmeticOp(Opc))
13477       checkOpenMPDeviceExpr(InputExpr);
13478   }
13479 
13480   switch (Opc) {
13481   case UO_PreInc:
13482   case UO_PreDec:
13483   case UO_PostInc:
13484   case UO_PostDec:
13485     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13486                                                 OpLoc,
13487                                                 Opc == UO_PreInc ||
13488                                                 Opc == UO_PostInc,
13489                                                 Opc == UO_PreInc ||
13490                                                 Opc == UO_PreDec);
13491     CanOverflow = isOverflowingIntegerType(Context, resultType);
13492     break;
13493   case UO_AddrOf:
13494     resultType = CheckAddressOfOperand(Input, OpLoc);
13495     CheckAddressOfNoDeref(InputExpr);
13496     RecordModifiableNonNullParam(*this, InputExpr);
13497     break;
13498   case UO_Deref: {
13499     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13500     if (Input.isInvalid()) return ExprError();
13501     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13502     break;
13503   }
13504   case UO_Plus:
13505   case UO_Minus:
13506     CanOverflow = Opc == UO_Minus &&
13507                   isOverflowingIntegerType(Context, Input.get()->getType());
13508     Input = UsualUnaryConversions(Input.get());
13509     if (Input.isInvalid()) return ExprError();
13510     // Unary plus and minus require promoting an operand of half vector to a
13511     // float vector and truncating the result back to a half vector. For now, we
13512     // do this only when HalfArgsAndReturns is set (that is, when the target is
13513     // arm or arm64).
13514     ConvertHalfVec =
13515         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13516 
13517     // If the operand is a half vector, promote it to a float vector.
13518     if (ConvertHalfVec)
13519       Input = convertVector(Input.get(), Context.FloatTy, *this);
13520     resultType = Input.get()->getType();
13521     if (resultType->isDependentType())
13522       break;
13523     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13524       break;
13525     else if (resultType->isVectorType() &&
13526              // The z vector extensions don't allow + or - with bool vectors.
13527              (!Context.getLangOpts().ZVector ||
13528               resultType->castAs<VectorType>()->getVectorKind() !=
13529               VectorType::AltiVecBool))
13530       break;
13531     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13532              Opc == UO_Plus &&
13533              resultType->isPointerType())
13534       break;
13535 
13536     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13537       << resultType << Input.get()->getSourceRange());
13538 
13539   case UO_Not: // bitwise complement
13540     Input = UsualUnaryConversions(Input.get());
13541     if (Input.isInvalid())
13542       return ExprError();
13543     resultType = Input.get()->getType();
13544     if (resultType->isDependentType())
13545       break;
13546     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13547     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13548       // C99 does not support '~' for complex conjugation.
13549       Diag(OpLoc, diag::ext_integer_complement_complex)
13550           << resultType << Input.get()->getSourceRange();
13551     else if (resultType->hasIntegerRepresentation())
13552       break;
13553     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13554       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13555       // on vector float types.
13556       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13557       if (!T->isIntegerType())
13558         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13559                           << resultType << Input.get()->getSourceRange());
13560     } else {
13561       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13562                        << resultType << Input.get()->getSourceRange());
13563     }
13564     break;
13565 
13566   case UO_LNot: // logical negation
13567     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13568     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13569     if (Input.isInvalid()) return ExprError();
13570     resultType = Input.get()->getType();
13571 
13572     // Though we still have to promote half FP to float...
13573     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13574       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13575       resultType = Context.FloatTy;
13576     }
13577 
13578     if (resultType->isDependentType())
13579       break;
13580     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13581       // C99 6.5.3.3p1: ok, fallthrough;
13582       if (Context.getLangOpts().CPlusPlus) {
13583         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13584         // operand contextually converted to bool.
13585         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13586                                   ScalarTypeToBooleanCastKind(resultType));
13587       } else if (Context.getLangOpts().OpenCL &&
13588                  Context.getLangOpts().OpenCLVersion < 120) {
13589         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13590         // operate on scalar float types.
13591         if (!resultType->isIntegerType() && !resultType->isPointerType())
13592           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13593                            << resultType << Input.get()->getSourceRange());
13594       }
13595     } else if (resultType->isExtVectorType()) {
13596       if (Context.getLangOpts().OpenCL &&
13597           Context.getLangOpts().OpenCLVersion < 120 &&
13598           !Context.getLangOpts().OpenCLCPlusPlus) {
13599         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13600         // operate on vector float types.
13601         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13602         if (!T->isIntegerType())
13603           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13604                            << resultType << Input.get()->getSourceRange());
13605       }
13606       // Vector logical not returns the signed variant of the operand type.
13607       resultType = GetSignedVectorType(resultType);
13608       break;
13609     } else {
13610       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13611       //        type in C++. We should allow that here too.
13612       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13613         << resultType << Input.get()->getSourceRange());
13614     }
13615 
13616     // LNot always has type int. C99 6.5.3.3p5.
13617     // In C++, it's bool. C++ 5.3.1p8
13618     resultType = Context.getLogicalOperationType();
13619     break;
13620   case UO_Real:
13621   case UO_Imag:
13622     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13623     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13624     // complex l-values to ordinary l-values and all other values to r-values.
13625     if (Input.isInvalid()) return ExprError();
13626     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13627       if (Input.get()->getValueKind() != VK_RValue &&
13628           Input.get()->getObjectKind() == OK_Ordinary)
13629         VK = Input.get()->getValueKind();
13630     } else if (!getLangOpts().CPlusPlus) {
13631       // In C, a volatile scalar is read by __imag. In C++, it is not.
13632       Input = DefaultLvalueConversion(Input.get());
13633     }
13634     break;
13635   case UO_Extension:
13636     resultType = Input.get()->getType();
13637     VK = Input.get()->getValueKind();
13638     OK = Input.get()->getObjectKind();
13639     break;
13640   case UO_Coawait:
13641     // It's unnecessary to represent the pass-through operator co_await in the
13642     // AST; just return the input expression instead.
13643     assert(!Input.get()->getType()->isDependentType() &&
13644                    "the co_await expression must be non-dependant before "
13645                    "building operator co_await");
13646     return Input;
13647   }
13648   if (resultType.isNull() || Input.isInvalid())
13649     return ExprError();
13650 
13651   // Check for array bounds violations in the operand of the UnaryOperator,
13652   // except for the '*' and '&' operators that have to be handled specially
13653   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13654   // that are explicitly defined as valid by the standard).
13655   if (Opc != UO_AddrOf && Opc != UO_Deref)
13656     CheckArrayAccess(Input.get());
13657 
13658   auto *UO = new (Context)
13659       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13660 
13661   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13662       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13663     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13664 
13665   // Convert the result back to a half vector.
13666   if (ConvertHalfVec)
13667     return convertVector(UO, Context.HalfTy, *this);
13668   return UO;
13669 }
13670 
13671 /// Determine whether the given expression is a qualified member
13672 /// access expression, of a form that could be turned into a pointer to member
13673 /// with the address-of operator.
13674 bool Sema::isQualifiedMemberAccess(Expr *E) {
13675   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13676     if (!DRE->getQualifier())
13677       return false;
13678 
13679     ValueDecl *VD = DRE->getDecl();
13680     if (!VD->isCXXClassMember())
13681       return false;
13682 
13683     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13684       return true;
13685     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13686       return Method->isInstance();
13687 
13688     return false;
13689   }
13690 
13691   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13692     if (!ULE->getQualifier())
13693       return false;
13694 
13695     for (NamedDecl *D : ULE->decls()) {
13696       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13697         if (Method->isInstance())
13698           return true;
13699       } else {
13700         // Overload set does not contain methods.
13701         break;
13702       }
13703     }
13704 
13705     return false;
13706   }
13707 
13708   return false;
13709 }
13710 
13711 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13712                               UnaryOperatorKind Opc, Expr *Input) {
13713   // First things first: handle placeholders so that the
13714   // overloaded-operator check considers the right type.
13715   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13716     // Increment and decrement of pseudo-object references.
13717     if (pty->getKind() == BuiltinType::PseudoObject &&
13718         UnaryOperator::isIncrementDecrementOp(Opc))
13719       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13720 
13721     // extension is always a builtin operator.
13722     if (Opc == UO_Extension)
13723       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13724 
13725     // & gets special logic for several kinds of placeholder.
13726     // The builtin code knows what to do.
13727     if (Opc == UO_AddrOf &&
13728         (pty->getKind() == BuiltinType::Overload ||
13729          pty->getKind() == BuiltinType::UnknownAny ||
13730          pty->getKind() == BuiltinType::BoundMember))
13731       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13732 
13733     // Anything else needs to be handled now.
13734     ExprResult Result = CheckPlaceholderExpr(Input);
13735     if (Result.isInvalid()) return ExprError();
13736     Input = Result.get();
13737   }
13738 
13739   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13740       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13741       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13742     // Find all of the overloaded operators visible from this
13743     // point. We perform both an operator-name lookup from the local
13744     // scope and an argument-dependent lookup based on the types of
13745     // the arguments.
13746     UnresolvedSet<16> Functions;
13747     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13748     if (S && OverOp != OO_None)
13749       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13750                                    Functions);
13751 
13752     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13753   }
13754 
13755   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13756 }
13757 
13758 // Unary Operators.  'Tok' is the token for the operator.
13759 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13760                               tok::TokenKind Op, Expr *Input) {
13761   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13762 }
13763 
13764 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13765 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13766                                 LabelDecl *TheDecl) {
13767   TheDecl->markUsed(Context);
13768   // Create the AST node.  The address of a label always has type 'void*'.
13769   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13770                                      Context.getPointerType(Context.VoidTy));
13771 }
13772 
13773 void Sema::ActOnStartStmtExpr() {
13774   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13775 }
13776 
13777 void Sema::ActOnStmtExprError() {
13778   // Note that function is also called by TreeTransform when leaving a
13779   // StmtExpr scope without rebuilding anything.
13780 
13781   DiscardCleanupsInEvaluationContext();
13782   PopExpressionEvaluationContext();
13783 }
13784 
13785 ExprResult
13786 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13787                     SourceLocation RPLoc) { // "({..})"
13788   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13789   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13790 
13791   if (hasAnyUnrecoverableErrorsInThisFunction())
13792     DiscardCleanupsInEvaluationContext();
13793   assert(!Cleanup.exprNeedsCleanups() &&
13794          "cleanups within StmtExpr not correctly bound!");
13795   PopExpressionEvaluationContext();
13796 
13797   // FIXME: there are a variety of strange constraints to enforce here, for
13798   // example, it is not possible to goto into a stmt expression apparently.
13799   // More semantic analysis is needed.
13800 
13801   // If there are sub-stmts in the compound stmt, take the type of the last one
13802   // as the type of the stmtexpr.
13803   QualType Ty = Context.VoidTy;
13804   bool StmtExprMayBindToTemp = false;
13805   if (!Compound->body_empty()) {
13806     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13807     if (const auto *LastStmt =
13808             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13809       if (const Expr *Value = LastStmt->getExprStmt()) {
13810         StmtExprMayBindToTemp = true;
13811         Ty = Value->getType();
13812       }
13813     }
13814   }
13815 
13816   // FIXME: Check that expression type is complete/non-abstract; statement
13817   // expressions are not lvalues.
13818   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13819   if (StmtExprMayBindToTemp)
13820     return MaybeBindToTemporary(ResStmtExpr);
13821   return ResStmtExpr;
13822 }
13823 
13824 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13825   if (ER.isInvalid())
13826     return ExprError();
13827 
13828   // Do function/array conversion on the last expression, but not
13829   // lvalue-to-rvalue.  However, initialize an unqualified type.
13830   ER = DefaultFunctionArrayConversion(ER.get());
13831   if (ER.isInvalid())
13832     return ExprError();
13833   Expr *E = ER.get();
13834 
13835   if (E->isTypeDependent())
13836     return E;
13837 
13838   // In ARC, if the final expression ends in a consume, splice
13839   // the consume out and bind it later.  In the alternate case
13840   // (when dealing with a retainable type), the result
13841   // initialization will create a produce.  In both cases the
13842   // result will be +1, and we'll need to balance that out with
13843   // a bind.
13844   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13845   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13846     return Cast->getSubExpr();
13847 
13848   // FIXME: Provide a better location for the initialization.
13849   return PerformCopyInitialization(
13850       InitializedEntity::InitializeStmtExprResult(
13851           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13852       SourceLocation(), E);
13853 }
13854 
13855 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13856                                       TypeSourceInfo *TInfo,
13857                                       ArrayRef<OffsetOfComponent> Components,
13858                                       SourceLocation RParenLoc) {
13859   QualType ArgTy = TInfo->getType();
13860   bool Dependent = ArgTy->isDependentType();
13861   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13862 
13863   // We must have at least one component that refers to the type, and the first
13864   // one is known to be a field designator.  Verify that the ArgTy represents
13865   // a struct/union/class.
13866   if (!Dependent && !ArgTy->isRecordType())
13867     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13868                        << ArgTy << TypeRange);
13869 
13870   // Type must be complete per C99 7.17p3 because a declaring a variable
13871   // with an incomplete type would be ill-formed.
13872   if (!Dependent
13873       && RequireCompleteType(BuiltinLoc, ArgTy,
13874                              diag::err_offsetof_incomplete_type, TypeRange))
13875     return ExprError();
13876 
13877   bool DidWarnAboutNonPOD = false;
13878   QualType CurrentType = ArgTy;
13879   SmallVector<OffsetOfNode, 4> Comps;
13880   SmallVector<Expr*, 4> Exprs;
13881   for (const OffsetOfComponent &OC : Components) {
13882     if (OC.isBrackets) {
13883       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13884       if (!CurrentType->isDependentType()) {
13885         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13886         if(!AT)
13887           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13888                            << CurrentType);
13889         CurrentType = AT->getElementType();
13890       } else
13891         CurrentType = Context.DependentTy;
13892 
13893       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13894       if (IdxRval.isInvalid())
13895         return ExprError();
13896       Expr *Idx = IdxRval.get();
13897 
13898       // The expression must be an integral expression.
13899       // FIXME: An integral constant expression?
13900       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13901           !Idx->getType()->isIntegerType())
13902         return ExprError(
13903             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13904             << Idx->getSourceRange());
13905 
13906       // Record this array index.
13907       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13908       Exprs.push_back(Idx);
13909       continue;
13910     }
13911 
13912     // Offset of a field.
13913     if (CurrentType->isDependentType()) {
13914       // We have the offset of a field, but we can't look into the dependent
13915       // type. Just record the identifier of the field.
13916       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13917       CurrentType = Context.DependentTy;
13918       continue;
13919     }
13920 
13921     // We need to have a complete type to look into.
13922     if (RequireCompleteType(OC.LocStart, CurrentType,
13923                             diag::err_offsetof_incomplete_type))
13924       return ExprError();
13925 
13926     // Look for the designated field.
13927     const RecordType *RC = CurrentType->getAs<RecordType>();
13928     if (!RC)
13929       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13930                        << CurrentType);
13931     RecordDecl *RD = RC->getDecl();
13932 
13933     // C++ [lib.support.types]p5:
13934     //   The macro offsetof accepts a restricted set of type arguments in this
13935     //   International Standard. type shall be a POD structure or a POD union
13936     //   (clause 9).
13937     // C++11 [support.types]p4:
13938     //   If type is not a standard-layout class (Clause 9), the results are
13939     //   undefined.
13940     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13941       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13942       unsigned DiagID =
13943         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13944                             : diag::ext_offsetof_non_pod_type;
13945 
13946       if (!IsSafe && !DidWarnAboutNonPOD &&
13947           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13948                               PDiag(DiagID)
13949                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13950                               << CurrentType))
13951         DidWarnAboutNonPOD = true;
13952     }
13953 
13954     // Look for the field.
13955     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13956     LookupQualifiedName(R, RD);
13957     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13958     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13959     if (!MemberDecl) {
13960       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13961         MemberDecl = IndirectMemberDecl->getAnonField();
13962     }
13963 
13964     if (!MemberDecl)
13965       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13966                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13967                                                               OC.LocEnd));
13968 
13969     // C99 7.17p3:
13970     //   (If the specified member is a bit-field, the behavior is undefined.)
13971     //
13972     // We diagnose this as an error.
13973     if (MemberDecl->isBitField()) {
13974       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13975         << MemberDecl->getDeclName()
13976         << SourceRange(BuiltinLoc, RParenLoc);
13977       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13978       return ExprError();
13979     }
13980 
13981     RecordDecl *Parent = MemberDecl->getParent();
13982     if (IndirectMemberDecl)
13983       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13984 
13985     // If the member was found in a base class, introduce OffsetOfNodes for
13986     // the base class indirections.
13987     CXXBasePaths Paths;
13988     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13989                       Paths)) {
13990       if (Paths.getDetectedVirtual()) {
13991         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13992           << MemberDecl->getDeclName()
13993           << SourceRange(BuiltinLoc, RParenLoc);
13994         return ExprError();
13995       }
13996 
13997       CXXBasePath &Path = Paths.front();
13998       for (const CXXBasePathElement &B : Path)
13999         Comps.push_back(OffsetOfNode(B.Base));
14000     }
14001 
14002     if (IndirectMemberDecl) {
14003       for (auto *FI : IndirectMemberDecl->chain()) {
14004         assert(isa<FieldDecl>(FI));
14005         Comps.push_back(OffsetOfNode(OC.LocStart,
14006                                      cast<FieldDecl>(FI), OC.LocEnd));
14007       }
14008     } else
14009       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14010 
14011     CurrentType = MemberDecl->getType().getNonReferenceType();
14012   }
14013 
14014   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14015                               Comps, Exprs, RParenLoc);
14016 }
14017 
14018 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14019                                       SourceLocation BuiltinLoc,
14020                                       SourceLocation TypeLoc,
14021                                       ParsedType ParsedArgTy,
14022                                       ArrayRef<OffsetOfComponent> Components,
14023                                       SourceLocation RParenLoc) {
14024 
14025   TypeSourceInfo *ArgTInfo;
14026   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14027   if (ArgTy.isNull())
14028     return ExprError();
14029 
14030   if (!ArgTInfo)
14031     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14032 
14033   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14034 }
14035 
14036 
14037 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14038                                  Expr *CondExpr,
14039                                  Expr *LHSExpr, Expr *RHSExpr,
14040                                  SourceLocation RPLoc) {
14041   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14042 
14043   ExprValueKind VK = VK_RValue;
14044   ExprObjectKind OK = OK_Ordinary;
14045   QualType resType;
14046   bool ValueDependent = false;
14047   bool CondIsTrue = false;
14048   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14049     resType = Context.DependentTy;
14050     ValueDependent = true;
14051   } else {
14052     // The conditional expression is required to be a constant expression.
14053     llvm::APSInt condEval(32);
14054     ExprResult CondICE
14055       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14056           diag::err_typecheck_choose_expr_requires_constant, false);
14057     if (CondICE.isInvalid())
14058       return ExprError();
14059     CondExpr = CondICE.get();
14060     CondIsTrue = condEval.getZExtValue();
14061 
14062     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14063     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14064 
14065     resType = ActiveExpr->getType();
14066     ValueDependent = ActiveExpr->isValueDependent();
14067     VK = ActiveExpr->getValueKind();
14068     OK = ActiveExpr->getObjectKind();
14069   }
14070 
14071   return new (Context)
14072       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14073                  CondIsTrue, resType->isDependentType(), ValueDependent);
14074 }
14075 
14076 //===----------------------------------------------------------------------===//
14077 // Clang Extensions.
14078 //===----------------------------------------------------------------------===//
14079 
14080 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14081 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14082   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14083 
14084   if (LangOpts.CPlusPlus) {
14085     MangleNumberingContext *MCtx;
14086     Decl *ManglingContextDecl;
14087     std::tie(MCtx, ManglingContextDecl) =
14088         getCurrentMangleNumberContext(Block->getDeclContext());
14089     if (MCtx) {
14090       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14091       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14092     }
14093   }
14094 
14095   PushBlockScope(CurScope, Block);
14096   CurContext->addDecl(Block);
14097   if (CurScope)
14098     PushDeclContext(CurScope, Block);
14099   else
14100     CurContext = Block;
14101 
14102   getCurBlock()->HasImplicitReturnType = true;
14103 
14104   // Enter a new evaluation context to insulate the block from any
14105   // cleanups from the enclosing full-expression.
14106   PushExpressionEvaluationContext(
14107       ExpressionEvaluationContext::PotentiallyEvaluated);
14108 }
14109 
14110 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14111                                Scope *CurScope) {
14112   assert(ParamInfo.getIdentifier() == nullptr &&
14113          "block-id should have no identifier!");
14114   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14115   BlockScopeInfo *CurBlock = getCurBlock();
14116 
14117   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14118   QualType T = Sig->getType();
14119 
14120   // FIXME: We should allow unexpanded parameter packs here, but that would,
14121   // in turn, make the block expression contain unexpanded parameter packs.
14122   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14123     // Drop the parameters.
14124     FunctionProtoType::ExtProtoInfo EPI;
14125     EPI.HasTrailingReturn = false;
14126     EPI.TypeQuals.addConst();
14127     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14128     Sig = Context.getTrivialTypeSourceInfo(T);
14129   }
14130 
14131   // GetTypeForDeclarator always produces a function type for a block
14132   // literal signature.  Furthermore, it is always a FunctionProtoType
14133   // unless the function was written with a typedef.
14134   assert(T->isFunctionType() &&
14135          "GetTypeForDeclarator made a non-function block signature");
14136 
14137   // Look for an explicit signature in that function type.
14138   FunctionProtoTypeLoc ExplicitSignature;
14139 
14140   if ((ExplicitSignature = Sig->getTypeLoc()
14141                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14142 
14143     // Check whether that explicit signature was synthesized by
14144     // GetTypeForDeclarator.  If so, don't save that as part of the
14145     // written signature.
14146     if (ExplicitSignature.getLocalRangeBegin() ==
14147         ExplicitSignature.getLocalRangeEnd()) {
14148       // This would be much cheaper if we stored TypeLocs instead of
14149       // TypeSourceInfos.
14150       TypeLoc Result = ExplicitSignature.getReturnLoc();
14151       unsigned Size = Result.getFullDataSize();
14152       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14153       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14154 
14155       ExplicitSignature = FunctionProtoTypeLoc();
14156     }
14157   }
14158 
14159   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14160   CurBlock->FunctionType = T;
14161 
14162   const FunctionType *Fn = T->getAs<FunctionType>();
14163   QualType RetTy = Fn->getReturnType();
14164   bool isVariadic =
14165     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14166 
14167   CurBlock->TheDecl->setIsVariadic(isVariadic);
14168 
14169   // Context.DependentTy is used as a placeholder for a missing block
14170   // return type.  TODO:  what should we do with declarators like:
14171   //   ^ * { ... }
14172   // If the answer is "apply template argument deduction"....
14173   if (RetTy != Context.DependentTy) {
14174     CurBlock->ReturnType = RetTy;
14175     CurBlock->TheDecl->setBlockMissingReturnType(false);
14176     CurBlock->HasImplicitReturnType = false;
14177   }
14178 
14179   // Push block parameters from the declarator if we had them.
14180   SmallVector<ParmVarDecl*, 8> Params;
14181   if (ExplicitSignature) {
14182     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14183       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14184       if (Param->getIdentifier() == nullptr &&
14185           !Param->isImplicit() &&
14186           !Param->isInvalidDecl() &&
14187           !getLangOpts().CPlusPlus)
14188         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14189       Params.push_back(Param);
14190     }
14191 
14192   // Fake up parameter variables if we have a typedef, like
14193   //   ^ fntype { ... }
14194   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14195     for (const auto &I : Fn->param_types()) {
14196       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14197           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14198       Params.push_back(Param);
14199     }
14200   }
14201 
14202   // Set the parameters on the block decl.
14203   if (!Params.empty()) {
14204     CurBlock->TheDecl->setParams(Params);
14205     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14206                              /*CheckParameterNames=*/false);
14207   }
14208 
14209   // Finally we can process decl attributes.
14210   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14211 
14212   // Put the parameter variables in scope.
14213   for (auto AI : CurBlock->TheDecl->parameters()) {
14214     AI->setOwningFunction(CurBlock->TheDecl);
14215 
14216     // If this has an identifier, add it to the scope stack.
14217     if (AI->getIdentifier()) {
14218       CheckShadow(CurBlock->TheScope, AI);
14219 
14220       PushOnScopeChains(AI, CurBlock->TheScope);
14221     }
14222   }
14223 }
14224 
14225 /// ActOnBlockError - If there is an error parsing a block, this callback
14226 /// is invoked to pop the information about the block from the action impl.
14227 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14228   // Leave the expression-evaluation context.
14229   DiscardCleanupsInEvaluationContext();
14230   PopExpressionEvaluationContext();
14231 
14232   // Pop off CurBlock, handle nested blocks.
14233   PopDeclContext();
14234   PopFunctionScopeInfo();
14235 }
14236 
14237 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14238 /// literal was successfully completed.  ^(int x){...}
14239 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14240                                     Stmt *Body, Scope *CurScope) {
14241   // If blocks are disabled, emit an error.
14242   if (!LangOpts.Blocks)
14243     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14244 
14245   // Leave the expression-evaluation context.
14246   if (hasAnyUnrecoverableErrorsInThisFunction())
14247     DiscardCleanupsInEvaluationContext();
14248   assert(!Cleanup.exprNeedsCleanups() &&
14249          "cleanups within block not correctly bound!");
14250   PopExpressionEvaluationContext();
14251 
14252   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14253   BlockDecl *BD = BSI->TheDecl;
14254 
14255   if (BSI->HasImplicitReturnType)
14256     deduceClosureReturnType(*BSI);
14257 
14258   QualType RetTy = Context.VoidTy;
14259   if (!BSI->ReturnType.isNull())
14260     RetTy = BSI->ReturnType;
14261 
14262   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14263   QualType BlockTy;
14264 
14265   // If the user wrote a function type in some form, try to use that.
14266   if (!BSI->FunctionType.isNull()) {
14267     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14268 
14269     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14270     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14271 
14272     // Turn protoless block types into nullary block types.
14273     if (isa<FunctionNoProtoType>(FTy)) {
14274       FunctionProtoType::ExtProtoInfo EPI;
14275       EPI.ExtInfo = Ext;
14276       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14277 
14278     // Otherwise, if we don't need to change anything about the function type,
14279     // preserve its sugar structure.
14280     } else if (FTy->getReturnType() == RetTy &&
14281                (!NoReturn || FTy->getNoReturnAttr())) {
14282       BlockTy = BSI->FunctionType;
14283 
14284     // Otherwise, make the minimal modifications to the function type.
14285     } else {
14286       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14287       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14288       EPI.TypeQuals = Qualifiers();
14289       EPI.ExtInfo = Ext;
14290       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14291     }
14292 
14293   // If we don't have a function type, just build one from nothing.
14294   } else {
14295     FunctionProtoType::ExtProtoInfo EPI;
14296     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14297     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14298   }
14299 
14300   DiagnoseUnusedParameters(BD->parameters());
14301   BlockTy = Context.getBlockPointerType(BlockTy);
14302 
14303   // If needed, diagnose invalid gotos and switches in the block.
14304   if (getCurFunction()->NeedsScopeChecking() &&
14305       !PP.isCodeCompletionEnabled())
14306     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14307 
14308   BD->setBody(cast<CompoundStmt>(Body));
14309 
14310   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14311     DiagnoseUnguardedAvailabilityViolations(BD);
14312 
14313   // Try to apply the named return value optimization. We have to check again
14314   // if we can do this, though, because blocks keep return statements around
14315   // to deduce an implicit return type.
14316   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14317       !BD->isDependentContext())
14318     computeNRVO(Body, BSI);
14319 
14320   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14321       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14322     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14323                           NTCUK_Destruct|NTCUK_Copy);
14324 
14325   PopDeclContext();
14326 
14327   // Pop the block scope now but keep it alive to the end of this function.
14328   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14329   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14330 
14331   // Set the captured variables on the block.
14332   SmallVector<BlockDecl::Capture, 4> Captures;
14333   for (Capture &Cap : BSI->Captures) {
14334     if (Cap.isInvalid() || Cap.isThisCapture())
14335       continue;
14336 
14337     VarDecl *Var = Cap.getVariable();
14338     Expr *CopyExpr = nullptr;
14339     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14340       if (const RecordType *Record =
14341               Cap.getCaptureType()->getAs<RecordType>()) {
14342         // The capture logic needs the destructor, so make sure we mark it.
14343         // Usually this is unnecessary because most local variables have
14344         // their destructors marked at declaration time, but parameters are
14345         // an exception because it's technically only the call site that
14346         // actually requires the destructor.
14347         if (isa<ParmVarDecl>(Var))
14348           FinalizeVarWithDestructor(Var, Record);
14349 
14350         // Enter a separate potentially-evaluated context while building block
14351         // initializers to isolate their cleanups from those of the block
14352         // itself.
14353         // FIXME: Is this appropriate even when the block itself occurs in an
14354         // unevaluated operand?
14355         EnterExpressionEvaluationContext EvalContext(
14356             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14357 
14358         SourceLocation Loc = Cap.getLocation();
14359 
14360         ExprResult Result = BuildDeclarationNameExpr(
14361             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14362 
14363         // According to the blocks spec, the capture of a variable from
14364         // the stack requires a const copy constructor.  This is not true
14365         // of the copy/move done to move a __block variable to the heap.
14366         if (!Result.isInvalid() &&
14367             !Result.get()->getType().isConstQualified()) {
14368           Result = ImpCastExprToType(Result.get(),
14369                                      Result.get()->getType().withConst(),
14370                                      CK_NoOp, VK_LValue);
14371         }
14372 
14373         if (!Result.isInvalid()) {
14374           Result = PerformCopyInitialization(
14375               InitializedEntity::InitializeBlock(Var->getLocation(),
14376                                                  Cap.getCaptureType(), false),
14377               Loc, Result.get());
14378         }
14379 
14380         // Build a full-expression copy expression if initialization
14381         // succeeded and used a non-trivial constructor.  Recover from
14382         // errors by pretending that the copy isn't necessary.
14383         if (!Result.isInvalid() &&
14384             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14385                 ->isTrivial()) {
14386           Result = MaybeCreateExprWithCleanups(Result);
14387           CopyExpr = Result.get();
14388         }
14389       }
14390     }
14391 
14392     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14393                               CopyExpr);
14394     Captures.push_back(NewCap);
14395   }
14396   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14397 
14398   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14399 
14400   // If the block isn't obviously global, i.e. it captures anything at
14401   // all, then we need to do a few things in the surrounding context:
14402   if (Result->getBlockDecl()->hasCaptures()) {
14403     // First, this expression has a new cleanup object.
14404     ExprCleanupObjects.push_back(Result->getBlockDecl());
14405     Cleanup.setExprNeedsCleanups(true);
14406 
14407     // It also gets a branch-protected scope if any of the captured
14408     // variables needs destruction.
14409     for (const auto &CI : Result->getBlockDecl()->captures()) {
14410       const VarDecl *var = CI.getVariable();
14411       if (var->getType().isDestructedType() != QualType::DK_none) {
14412         setFunctionHasBranchProtectedScope();
14413         break;
14414       }
14415     }
14416   }
14417 
14418   if (getCurFunction())
14419     getCurFunction()->addBlock(BD);
14420 
14421   return Result;
14422 }
14423 
14424 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14425                             SourceLocation RPLoc) {
14426   TypeSourceInfo *TInfo;
14427   GetTypeFromParser(Ty, &TInfo);
14428   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14429 }
14430 
14431 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14432                                 Expr *E, TypeSourceInfo *TInfo,
14433                                 SourceLocation RPLoc) {
14434   Expr *OrigExpr = E;
14435   bool IsMS = false;
14436 
14437   // CUDA device code does not support varargs.
14438   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14439     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14440       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14441       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14442         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14443     }
14444   }
14445 
14446   // NVPTX does not support va_arg expression.
14447   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14448       Context.getTargetInfo().getTriple().isNVPTX())
14449     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14450 
14451   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14452   // as Microsoft ABI on an actual Microsoft platform, where
14453   // __builtin_ms_va_list and __builtin_va_list are the same.)
14454   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14455       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14456     QualType MSVaListType = Context.getBuiltinMSVaListType();
14457     if (Context.hasSameType(MSVaListType, E->getType())) {
14458       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14459         return ExprError();
14460       IsMS = true;
14461     }
14462   }
14463 
14464   // Get the va_list type
14465   QualType VaListType = Context.getBuiltinVaListType();
14466   if (!IsMS) {
14467     if (VaListType->isArrayType()) {
14468       // Deal with implicit array decay; for example, on x86-64,
14469       // va_list is an array, but it's supposed to decay to
14470       // a pointer for va_arg.
14471       VaListType = Context.getArrayDecayedType(VaListType);
14472       // Make sure the input expression also decays appropriately.
14473       ExprResult Result = UsualUnaryConversions(E);
14474       if (Result.isInvalid())
14475         return ExprError();
14476       E = Result.get();
14477     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14478       // If va_list is a record type and we are compiling in C++ mode,
14479       // check the argument using reference binding.
14480       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14481           Context, Context.getLValueReferenceType(VaListType), false);
14482       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14483       if (Init.isInvalid())
14484         return ExprError();
14485       E = Init.getAs<Expr>();
14486     } else {
14487       // Otherwise, the va_list argument must be an l-value because
14488       // it is modified by va_arg.
14489       if (!E->isTypeDependent() &&
14490           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14491         return ExprError();
14492     }
14493   }
14494 
14495   if (!IsMS && !E->isTypeDependent() &&
14496       !Context.hasSameType(VaListType, E->getType()))
14497     return ExprError(
14498         Diag(E->getBeginLoc(),
14499              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14500         << OrigExpr->getType() << E->getSourceRange());
14501 
14502   if (!TInfo->getType()->isDependentType()) {
14503     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14504                             diag::err_second_parameter_to_va_arg_incomplete,
14505                             TInfo->getTypeLoc()))
14506       return ExprError();
14507 
14508     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14509                                TInfo->getType(),
14510                                diag::err_second_parameter_to_va_arg_abstract,
14511                                TInfo->getTypeLoc()))
14512       return ExprError();
14513 
14514     if (!TInfo->getType().isPODType(Context)) {
14515       Diag(TInfo->getTypeLoc().getBeginLoc(),
14516            TInfo->getType()->isObjCLifetimeType()
14517              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14518              : diag::warn_second_parameter_to_va_arg_not_pod)
14519         << TInfo->getType()
14520         << TInfo->getTypeLoc().getSourceRange();
14521     }
14522 
14523     // Check for va_arg where arguments of the given type will be promoted
14524     // (i.e. this va_arg is guaranteed to have undefined behavior).
14525     QualType PromoteType;
14526     if (TInfo->getType()->isPromotableIntegerType()) {
14527       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14528       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14529         PromoteType = QualType();
14530     }
14531     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14532       PromoteType = Context.DoubleTy;
14533     if (!PromoteType.isNull())
14534       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14535                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14536                           << TInfo->getType()
14537                           << PromoteType
14538                           << TInfo->getTypeLoc().getSourceRange());
14539   }
14540 
14541   QualType T = TInfo->getType().getNonLValueExprType(Context);
14542   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14543 }
14544 
14545 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14546   // The type of __null will be int or long, depending on the size of
14547   // pointers on the target.
14548   QualType Ty;
14549   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14550   if (pw == Context.getTargetInfo().getIntWidth())
14551     Ty = Context.IntTy;
14552   else if (pw == Context.getTargetInfo().getLongWidth())
14553     Ty = Context.LongTy;
14554   else if (pw == Context.getTargetInfo().getLongLongWidth())
14555     Ty = Context.LongLongTy;
14556   else {
14557     llvm_unreachable("I don't know size of pointer!");
14558   }
14559 
14560   return new (Context) GNUNullExpr(Ty, TokenLoc);
14561 }
14562 
14563 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14564                                     SourceLocation BuiltinLoc,
14565                                     SourceLocation RPLoc) {
14566   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14567 }
14568 
14569 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14570                                     SourceLocation BuiltinLoc,
14571                                     SourceLocation RPLoc,
14572                                     DeclContext *ParentContext) {
14573   return new (Context)
14574       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14575 }
14576 
14577 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14578                                               bool Diagnose) {
14579   if (!getLangOpts().ObjC)
14580     return false;
14581 
14582   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14583   if (!PT)
14584     return false;
14585 
14586   if (!PT->isObjCIdType()) {
14587     // Check if the destination is the 'NSString' interface.
14588     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14589     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14590       return false;
14591   }
14592 
14593   // Ignore any parens, implicit casts (should only be
14594   // array-to-pointer decays), and not-so-opaque values.  The last is
14595   // important for making this trigger for property assignments.
14596   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14597   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14598     if (OV->getSourceExpr())
14599       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14600 
14601   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14602   if (!SL || !SL->isAscii())
14603     return false;
14604   if (Diagnose) {
14605     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14606         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14607     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14608   }
14609   return true;
14610 }
14611 
14612 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14613                                               const Expr *SrcExpr) {
14614   if (!DstType->isFunctionPointerType() ||
14615       !SrcExpr->getType()->isFunctionType())
14616     return false;
14617 
14618   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14619   if (!DRE)
14620     return false;
14621 
14622   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14623   if (!FD)
14624     return false;
14625 
14626   return !S.checkAddressOfFunctionIsAvailable(FD,
14627                                               /*Complain=*/true,
14628                                               SrcExpr->getBeginLoc());
14629 }
14630 
14631 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14632                                     SourceLocation Loc,
14633                                     QualType DstType, QualType SrcType,
14634                                     Expr *SrcExpr, AssignmentAction Action,
14635                                     bool *Complained) {
14636   if (Complained)
14637     *Complained = false;
14638 
14639   // Decode the result (notice that AST's are still created for extensions).
14640   bool CheckInferredResultType = false;
14641   bool isInvalid = false;
14642   unsigned DiagKind = 0;
14643   FixItHint Hint;
14644   ConversionFixItGenerator ConvHints;
14645   bool MayHaveConvFixit = false;
14646   bool MayHaveFunctionDiff = false;
14647   const ObjCInterfaceDecl *IFace = nullptr;
14648   const ObjCProtocolDecl *PDecl = nullptr;
14649 
14650   switch (ConvTy) {
14651   case Compatible:
14652       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14653       return false;
14654 
14655   case PointerToInt:
14656     DiagKind = diag::ext_typecheck_convert_pointer_int;
14657     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14658     MayHaveConvFixit = true;
14659     break;
14660   case IntToPointer:
14661     DiagKind = diag::ext_typecheck_convert_int_pointer;
14662     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14663     MayHaveConvFixit = true;
14664     break;
14665   case IncompatiblePointer:
14666     if (Action == AA_Passing_CFAudited)
14667       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14668     else if (SrcType->isFunctionPointerType() &&
14669              DstType->isFunctionPointerType())
14670       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14671     else
14672       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14673 
14674     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14675       SrcType->isObjCObjectPointerType();
14676     if (Hint.isNull() && !CheckInferredResultType) {
14677       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14678     }
14679     else if (CheckInferredResultType) {
14680       SrcType = SrcType.getUnqualifiedType();
14681       DstType = DstType.getUnqualifiedType();
14682     }
14683     MayHaveConvFixit = true;
14684     break;
14685   case IncompatiblePointerSign:
14686     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14687     break;
14688   case FunctionVoidPointer:
14689     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14690     break;
14691   case IncompatiblePointerDiscardsQualifiers: {
14692     // Perform array-to-pointer decay if necessary.
14693     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14694 
14695     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14696     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14697     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14698       DiagKind = diag::err_typecheck_incompatible_address_space;
14699       break;
14700 
14701     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14702       DiagKind = diag::err_typecheck_incompatible_ownership;
14703       break;
14704     }
14705 
14706     llvm_unreachable("unknown error case for discarding qualifiers!");
14707     // fallthrough
14708   }
14709   case CompatiblePointerDiscardsQualifiers:
14710     // If the qualifiers lost were because we were applying the
14711     // (deprecated) C++ conversion from a string literal to a char*
14712     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14713     // Ideally, this check would be performed in
14714     // checkPointerTypesForAssignment. However, that would require a
14715     // bit of refactoring (so that the second argument is an
14716     // expression, rather than a type), which should be done as part
14717     // of a larger effort to fix checkPointerTypesForAssignment for
14718     // C++ semantics.
14719     if (getLangOpts().CPlusPlus &&
14720         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14721       return false;
14722     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14723     break;
14724   case IncompatibleNestedPointerQualifiers:
14725     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14726     break;
14727   case IncompatibleNestedPointerAddressSpaceMismatch:
14728     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14729     break;
14730   case IntToBlockPointer:
14731     DiagKind = diag::err_int_to_block_pointer;
14732     break;
14733   case IncompatibleBlockPointer:
14734     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14735     break;
14736   case IncompatibleObjCQualifiedId: {
14737     if (SrcType->isObjCQualifiedIdType()) {
14738       const ObjCObjectPointerType *srcOPT =
14739                 SrcType->castAs<ObjCObjectPointerType>();
14740       for (auto *srcProto : srcOPT->quals()) {
14741         PDecl = srcProto;
14742         break;
14743       }
14744       if (const ObjCInterfaceType *IFaceT =
14745             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14746         IFace = IFaceT->getDecl();
14747     }
14748     else if (DstType->isObjCQualifiedIdType()) {
14749       const ObjCObjectPointerType *dstOPT =
14750         DstType->castAs<ObjCObjectPointerType>();
14751       for (auto *dstProto : dstOPT->quals()) {
14752         PDecl = dstProto;
14753         break;
14754       }
14755       if (const ObjCInterfaceType *IFaceT =
14756             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14757         IFace = IFaceT->getDecl();
14758     }
14759     DiagKind = diag::warn_incompatible_qualified_id;
14760     break;
14761   }
14762   case IncompatibleVectors:
14763     DiagKind = diag::warn_incompatible_vectors;
14764     break;
14765   case IncompatibleObjCWeakRef:
14766     DiagKind = diag::err_arc_weak_unavailable_assign;
14767     break;
14768   case Incompatible:
14769     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14770       if (Complained)
14771         *Complained = true;
14772       return true;
14773     }
14774 
14775     DiagKind = diag::err_typecheck_convert_incompatible;
14776     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14777     MayHaveConvFixit = true;
14778     isInvalid = true;
14779     MayHaveFunctionDiff = true;
14780     break;
14781   }
14782 
14783   QualType FirstType, SecondType;
14784   switch (Action) {
14785   case AA_Assigning:
14786   case AA_Initializing:
14787     // The destination type comes first.
14788     FirstType = DstType;
14789     SecondType = SrcType;
14790     break;
14791 
14792   case AA_Returning:
14793   case AA_Passing:
14794   case AA_Passing_CFAudited:
14795   case AA_Converting:
14796   case AA_Sending:
14797   case AA_Casting:
14798     // The source type comes first.
14799     FirstType = SrcType;
14800     SecondType = DstType;
14801     break;
14802   }
14803 
14804   PartialDiagnostic FDiag = PDiag(DiagKind);
14805   if (Action == AA_Passing_CFAudited)
14806     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14807   else
14808     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14809 
14810   // If we can fix the conversion, suggest the FixIts.
14811   assert(ConvHints.isNull() || Hint.isNull());
14812   if (!ConvHints.isNull()) {
14813     for (FixItHint &H : ConvHints.Hints)
14814       FDiag << H;
14815   } else {
14816     FDiag << Hint;
14817   }
14818   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14819 
14820   if (MayHaveFunctionDiff)
14821     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14822 
14823   Diag(Loc, FDiag);
14824   if (DiagKind == diag::warn_incompatible_qualified_id &&
14825       PDecl && IFace && !IFace->hasDefinition())
14826       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14827         << IFace << PDecl;
14828 
14829   if (SecondType == Context.OverloadTy)
14830     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14831                               FirstType, /*TakingAddress=*/true);
14832 
14833   if (CheckInferredResultType)
14834     EmitRelatedResultTypeNote(SrcExpr);
14835 
14836   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14837     EmitRelatedResultTypeNoteForReturn(DstType);
14838 
14839   if (Complained)
14840     *Complained = true;
14841   return isInvalid;
14842 }
14843 
14844 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14845                                                  llvm::APSInt *Result) {
14846   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14847   public:
14848     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14849       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14850     }
14851   } Diagnoser;
14852 
14853   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14854 }
14855 
14856 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14857                                                  llvm::APSInt *Result,
14858                                                  unsigned DiagID,
14859                                                  bool AllowFold) {
14860   class IDDiagnoser : public VerifyICEDiagnoser {
14861     unsigned DiagID;
14862 
14863   public:
14864     IDDiagnoser(unsigned DiagID)
14865       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14866 
14867     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14868       S.Diag(Loc, DiagID) << SR;
14869     }
14870   } Diagnoser(DiagID);
14871 
14872   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14873 }
14874 
14875 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14876                                             SourceRange SR) {
14877   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14878 }
14879 
14880 ExprResult
14881 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14882                                       VerifyICEDiagnoser &Diagnoser,
14883                                       bool AllowFold) {
14884   SourceLocation DiagLoc = E->getBeginLoc();
14885 
14886   if (getLangOpts().CPlusPlus11) {
14887     // C++11 [expr.const]p5:
14888     //   If an expression of literal class type is used in a context where an
14889     //   integral constant expression is required, then that class type shall
14890     //   have a single non-explicit conversion function to an integral or
14891     //   unscoped enumeration type
14892     ExprResult Converted;
14893     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14894     public:
14895       CXX11ConvertDiagnoser(bool Silent)
14896           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14897                                 Silent, true) {}
14898 
14899       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14900                                            QualType T) override {
14901         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14902       }
14903 
14904       SemaDiagnosticBuilder diagnoseIncomplete(
14905           Sema &S, SourceLocation Loc, QualType T) override {
14906         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14907       }
14908 
14909       SemaDiagnosticBuilder diagnoseExplicitConv(
14910           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14911         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14912       }
14913 
14914       SemaDiagnosticBuilder noteExplicitConv(
14915           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14916         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14917                  << ConvTy->isEnumeralType() << ConvTy;
14918       }
14919 
14920       SemaDiagnosticBuilder diagnoseAmbiguous(
14921           Sema &S, SourceLocation Loc, QualType T) override {
14922         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14923       }
14924 
14925       SemaDiagnosticBuilder noteAmbiguous(
14926           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14927         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14928                  << ConvTy->isEnumeralType() << ConvTy;
14929       }
14930 
14931       SemaDiagnosticBuilder diagnoseConversion(
14932           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14933         llvm_unreachable("conversion functions are permitted");
14934       }
14935     } ConvertDiagnoser(Diagnoser.Suppress);
14936 
14937     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14938                                                     ConvertDiagnoser);
14939     if (Converted.isInvalid())
14940       return Converted;
14941     E = Converted.get();
14942     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14943       return ExprError();
14944   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14945     // An ICE must be of integral or unscoped enumeration type.
14946     if (!Diagnoser.Suppress)
14947       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14948     return ExprError();
14949   }
14950 
14951   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14952   // in the non-ICE case.
14953   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14954     if (Result)
14955       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14956     if (!isa<ConstantExpr>(E))
14957       E = ConstantExpr::Create(Context, E);
14958     return E;
14959   }
14960 
14961   Expr::EvalResult EvalResult;
14962   SmallVector<PartialDiagnosticAt, 8> Notes;
14963   EvalResult.Diag = &Notes;
14964 
14965   // Try to evaluate the expression, and produce diagnostics explaining why it's
14966   // not a constant expression as a side-effect.
14967   bool Folded =
14968       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14969       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14970 
14971   if (!isa<ConstantExpr>(E))
14972     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14973 
14974   // In C++11, we can rely on diagnostics being produced for any expression
14975   // which is not a constant expression. If no diagnostics were produced, then
14976   // this is a constant expression.
14977   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14978     if (Result)
14979       *Result = EvalResult.Val.getInt();
14980     return E;
14981   }
14982 
14983   // If our only note is the usual "invalid subexpression" note, just point
14984   // the caret at its location rather than producing an essentially
14985   // redundant note.
14986   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14987         diag::note_invalid_subexpr_in_const_expr) {
14988     DiagLoc = Notes[0].first;
14989     Notes.clear();
14990   }
14991 
14992   if (!Folded || !AllowFold) {
14993     if (!Diagnoser.Suppress) {
14994       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14995       for (const PartialDiagnosticAt &Note : Notes)
14996         Diag(Note.first, Note.second);
14997     }
14998 
14999     return ExprError();
15000   }
15001 
15002   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15003   for (const PartialDiagnosticAt &Note : Notes)
15004     Diag(Note.first, Note.second);
15005 
15006   if (Result)
15007     *Result = EvalResult.Val.getInt();
15008   return E;
15009 }
15010 
15011 namespace {
15012   // Handle the case where we conclude a expression which we speculatively
15013   // considered to be unevaluated is actually evaluated.
15014   class TransformToPE : public TreeTransform<TransformToPE> {
15015     typedef TreeTransform<TransformToPE> BaseTransform;
15016 
15017   public:
15018     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15019 
15020     // Make sure we redo semantic analysis
15021     bool AlwaysRebuild() { return true; }
15022     bool ReplacingOriginal() { return true; }
15023 
15024     // We need to special-case DeclRefExprs referring to FieldDecls which
15025     // are not part of a member pointer formation; normal TreeTransforming
15026     // doesn't catch this case because of the way we represent them in the AST.
15027     // FIXME: This is a bit ugly; is it really the best way to handle this
15028     // case?
15029     //
15030     // Error on DeclRefExprs referring to FieldDecls.
15031     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15032       if (isa<FieldDecl>(E->getDecl()) &&
15033           !SemaRef.isUnevaluatedContext())
15034         return SemaRef.Diag(E->getLocation(),
15035                             diag::err_invalid_non_static_member_use)
15036             << E->getDecl() << E->getSourceRange();
15037 
15038       return BaseTransform::TransformDeclRefExpr(E);
15039     }
15040 
15041     // Exception: filter out member pointer formation
15042     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15043       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15044         return E;
15045 
15046       return BaseTransform::TransformUnaryOperator(E);
15047     }
15048 
15049     // The body of a lambda-expression is in a separate expression evaluation
15050     // context so never needs to be transformed.
15051     // FIXME: Ideally we wouldn't transform the closure type either, and would
15052     // just recreate the capture expressions and lambda expression.
15053     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15054       return SkipLambdaBody(E, Body);
15055     }
15056   };
15057 }
15058 
15059 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15060   assert(isUnevaluatedContext() &&
15061          "Should only transform unevaluated expressions");
15062   ExprEvalContexts.back().Context =
15063       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15064   if (isUnevaluatedContext())
15065     return E;
15066   return TransformToPE(*this).TransformExpr(E);
15067 }
15068 
15069 void
15070 Sema::PushExpressionEvaluationContext(
15071     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15072     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15073   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15074                                 LambdaContextDecl, ExprContext);
15075   Cleanup.reset();
15076   if (!MaybeODRUseExprs.empty())
15077     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15078 }
15079 
15080 void
15081 Sema::PushExpressionEvaluationContext(
15082     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15083     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15084   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15085   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15086 }
15087 
15088 namespace {
15089 
15090 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15091   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15092   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15093     if (E->getOpcode() == UO_Deref)
15094       return CheckPossibleDeref(S, E->getSubExpr());
15095   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15096     return CheckPossibleDeref(S, E->getBase());
15097   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15098     return CheckPossibleDeref(S, E->getBase());
15099   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15100     QualType Inner;
15101     QualType Ty = E->getType();
15102     if (const auto *Ptr = Ty->getAs<PointerType>())
15103       Inner = Ptr->getPointeeType();
15104     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15105       Inner = Arr->getElementType();
15106     else
15107       return nullptr;
15108 
15109     if (Inner->hasAttr(attr::NoDeref))
15110       return E;
15111   }
15112   return nullptr;
15113 }
15114 
15115 } // namespace
15116 
15117 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15118   for (const Expr *E : Rec.PossibleDerefs) {
15119     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15120     if (DeclRef) {
15121       const ValueDecl *Decl = DeclRef->getDecl();
15122       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15123           << Decl->getName() << E->getSourceRange();
15124       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15125     } else {
15126       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15127           << E->getSourceRange();
15128     }
15129   }
15130   Rec.PossibleDerefs.clear();
15131 }
15132 
15133 /// Check whether E, which is either a discarded-value expression or an
15134 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15135 /// and if so, remove it from the list of volatile-qualified assignments that
15136 /// we are going to warn are deprecated.
15137 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15138   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15139     return;
15140 
15141   // Note: ignoring parens here is not justified by the standard rules, but
15142   // ignoring parentheses seems like a more reasonable approach, and this only
15143   // drives a deprecation warning so doesn't affect conformance.
15144   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15145     if (BO->getOpcode() == BO_Assign) {
15146       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15147       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15148                  LHSs.end());
15149     }
15150   }
15151 }
15152 
15153 void Sema::PopExpressionEvaluationContext() {
15154   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15155   unsigned NumTypos = Rec.NumTypos;
15156 
15157   if (!Rec.Lambdas.empty()) {
15158     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15159     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15160         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15161       unsigned D;
15162       if (Rec.isUnevaluated()) {
15163         // C++11 [expr.prim.lambda]p2:
15164         //   A lambda-expression shall not appear in an unevaluated operand
15165         //   (Clause 5).
15166         D = diag::err_lambda_unevaluated_operand;
15167       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15168         // C++1y [expr.const]p2:
15169         //   A conditional-expression e is a core constant expression unless the
15170         //   evaluation of e, following the rules of the abstract machine, would
15171         //   evaluate [...] a lambda-expression.
15172         D = diag::err_lambda_in_constant_expression;
15173       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15174         // C++17 [expr.prim.lamda]p2:
15175         // A lambda-expression shall not appear [...] in a template-argument.
15176         D = diag::err_lambda_in_invalid_context;
15177       } else
15178         llvm_unreachable("Couldn't infer lambda error message.");
15179 
15180       for (const auto *L : Rec.Lambdas)
15181         Diag(L->getBeginLoc(), D);
15182     }
15183   }
15184 
15185   WarnOnPendingNoDerefs(Rec);
15186 
15187   // Warn on any volatile-qualified simple-assignments that are not discarded-
15188   // value expressions nor unevaluated operands (those cases get removed from
15189   // this list by CheckUnusedVolatileAssignment).
15190   for (auto *BO : Rec.VolatileAssignmentLHSs)
15191     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15192         << BO->getType();
15193 
15194   // When are coming out of an unevaluated context, clear out any
15195   // temporaries that we may have created as part of the evaluation of
15196   // the expression in that context: they aren't relevant because they
15197   // will never be constructed.
15198   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15199     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15200                              ExprCleanupObjects.end());
15201     Cleanup = Rec.ParentCleanup;
15202     CleanupVarDeclMarking();
15203     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15204   // Otherwise, merge the contexts together.
15205   } else {
15206     Cleanup.mergeFrom(Rec.ParentCleanup);
15207     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15208                             Rec.SavedMaybeODRUseExprs.end());
15209   }
15210 
15211   // Pop the current expression evaluation context off the stack.
15212   ExprEvalContexts.pop_back();
15213 
15214   // The global expression evaluation context record is never popped.
15215   ExprEvalContexts.back().NumTypos += NumTypos;
15216 }
15217 
15218 void Sema::DiscardCleanupsInEvaluationContext() {
15219   ExprCleanupObjects.erase(
15220          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15221          ExprCleanupObjects.end());
15222   Cleanup.reset();
15223   MaybeODRUseExprs.clear();
15224 }
15225 
15226 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15227   ExprResult Result = CheckPlaceholderExpr(E);
15228   if (Result.isInvalid())
15229     return ExprError();
15230   E = Result.get();
15231   if (!E->getType()->isVariablyModifiedType())
15232     return E;
15233   return TransformToPotentiallyEvaluated(E);
15234 }
15235 
15236 /// Are we in a context that is potentially constant evaluated per C++20
15237 /// [expr.const]p12?
15238 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15239   /// C++2a [expr.const]p12:
15240   //   An expression or conversion is potentially constant evaluated if it is
15241   switch (SemaRef.ExprEvalContexts.back().Context) {
15242     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15243       // -- a manifestly constant-evaluated expression,
15244     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15245     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15246     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15247       // -- a potentially-evaluated expression,
15248     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15249       // -- an immediate subexpression of a braced-init-list,
15250 
15251       // -- [FIXME] an expression of the form & cast-expression that occurs
15252       //    within a templated entity
15253       // -- a subexpression of one of the above that is not a subexpression of
15254       // a nested unevaluated operand.
15255       return true;
15256 
15257     case Sema::ExpressionEvaluationContext::Unevaluated:
15258     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15259       // Expressions in this context are never evaluated.
15260       return false;
15261   }
15262   llvm_unreachable("Invalid context");
15263 }
15264 
15265 /// Return true if this function has a calling convention that requires mangling
15266 /// in the size of the parameter pack.
15267 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15268   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15269   // we don't need parameter type sizes.
15270   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15271   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
15272                             TT.getArch() != llvm::Triple::x86_64))
15273     return false;
15274 
15275   // If this is C++ and this isn't an extern "C" function, parameters do not
15276   // need to be complete. In this case, C++ mangling will apply, which doesn't
15277   // use the size of the parameters.
15278   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15279     return false;
15280 
15281   // Stdcall, fastcall, and vectorcall need this special treatment.
15282   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15283   switch (CC) {
15284   case CC_X86StdCall:
15285   case CC_X86FastCall:
15286   case CC_X86VectorCall:
15287     return true;
15288   default:
15289     break;
15290   }
15291   return false;
15292 }
15293 
15294 /// Require that all of the parameter types of function be complete. Normally,
15295 /// parameter types are only required to be complete when a function is called
15296 /// or defined, but to mangle functions with certain calling conventions, the
15297 /// mangler needs to know the size of the parameter list. In this situation,
15298 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15299 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15300 /// result in a linker error. Clang doesn't implement this behavior, and instead
15301 /// attempts to error at compile time.
15302 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15303                                                   SourceLocation Loc) {
15304   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15305     FunctionDecl *FD;
15306     ParmVarDecl *Param;
15307 
15308   public:
15309     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15310         : FD(FD), Param(Param) {}
15311 
15312     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15313       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15314       StringRef CCName;
15315       switch (CC) {
15316       case CC_X86StdCall:
15317         CCName = "stdcall";
15318         break;
15319       case CC_X86FastCall:
15320         CCName = "fastcall";
15321         break;
15322       case CC_X86VectorCall:
15323         CCName = "vectorcall";
15324         break;
15325       default:
15326         llvm_unreachable("CC does not need mangling");
15327       }
15328 
15329       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15330           << Param->getDeclName() << FD->getDeclName() << CCName;
15331     }
15332   };
15333 
15334   for (ParmVarDecl *Param : FD->parameters()) {
15335     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15336     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15337   }
15338 }
15339 
15340 namespace {
15341 enum class OdrUseContext {
15342   /// Declarations in this context are not odr-used.
15343   None,
15344   /// Declarations in this context are formally odr-used, but this is a
15345   /// dependent context.
15346   Dependent,
15347   /// Declarations in this context are odr-used but not actually used (yet).
15348   FormallyOdrUsed,
15349   /// Declarations in this context are used.
15350   Used
15351 };
15352 }
15353 
15354 /// Are we within a context in which references to resolved functions or to
15355 /// variables result in odr-use?
15356 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15357   OdrUseContext Result;
15358 
15359   switch (SemaRef.ExprEvalContexts.back().Context) {
15360     case Sema::ExpressionEvaluationContext::Unevaluated:
15361     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15362     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15363       return OdrUseContext::None;
15364 
15365     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15366     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15367       Result = OdrUseContext::Used;
15368       break;
15369 
15370     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15371       Result = OdrUseContext::FormallyOdrUsed;
15372       break;
15373 
15374     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15375       // A default argument formally results in odr-use, but doesn't actually
15376       // result in a use in any real sense until it itself is used.
15377       Result = OdrUseContext::FormallyOdrUsed;
15378       break;
15379   }
15380 
15381   if (SemaRef.CurContext->isDependentContext())
15382     return OdrUseContext::Dependent;
15383 
15384   return Result;
15385 }
15386 
15387 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15388   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
15389   return Func->isConstexpr() &&
15390          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
15391 }
15392 
15393 /// Mark a function referenced, and check whether it is odr-used
15394 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15395 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15396                                   bool MightBeOdrUse) {
15397   assert(Func && "No function?");
15398 
15399   Func->setReferenced();
15400 
15401   // Recursive functions aren't really used until they're used from some other
15402   // context.
15403   bool IsRecursiveCall = CurContext == Func;
15404 
15405   // C++11 [basic.def.odr]p3:
15406   //   A function whose name appears as a potentially-evaluated expression is
15407   //   odr-used if it is the unique lookup result or the selected member of a
15408   //   set of overloaded functions [...].
15409   //
15410   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15411   // can just check that here.
15412   OdrUseContext OdrUse =
15413       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15414   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15415     OdrUse = OdrUseContext::FormallyOdrUsed;
15416 
15417   // Trivial default constructors and destructors are never actually used.
15418   // FIXME: What about other special members?
15419   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15420       OdrUse == OdrUseContext::Used) {
15421     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15422       if (Constructor->isDefaultConstructor())
15423         OdrUse = OdrUseContext::FormallyOdrUsed;
15424     if (isa<CXXDestructorDecl>(Func))
15425       OdrUse = OdrUseContext::FormallyOdrUsed;
15426   }
15427 
15428   // C++20 [expr.const]p12:
15429   //   A function [...] is needed for constant evaluation if it is [...] a
15430   //   constexpr function that is named by an expression that is potentially
15431   //   constant evaluated
15432   bool NeededForConstantEvaluation =
15433       isPotentiallyConstantEvaluatedContext(*this) &&
15434       isImplicitlyDefinableConstexprFunction(Func);
15435 
15436   // Determine whether we require a function definition to exist, per
15437   // C++11 [temp.inst]p3:
15438   //   Unless a function template specialization has been explicitly
15439   //   instantiated or explicitly specialized, the function template
15440   //   specialization is implicitly instantiated when the specialization is
15441   //   referenced in a context that requires a function definition to exist.
15442   // C++20 [temp.inst]p7:
15443   //   The existence of a definition of a [...] function is considered to
15444   //   affect the semantics of the program if the [...] function is needed for
15445   //   constant evaluation by an expression
15446   // C++20 [basic.def.odr]p10:
15447   //   Every program shall contain exactly one definition of every non-inline
15448   //   function or variable that is odr-used in that program outside of a
15449   //   discarded statement
15450   // C++20 [special]p1:
15451   //   The implementation will implicitly define [defaulted special members]
15452   //   if they are odr-used or needed for constant evaluation.
15453   //
15454   // Note that we skip the implicit instantiation of templates that are only
15455   // used in unused default arguments or by recursive calls to themselves.
15456   // This is formally non-conforming, but seems reasonable in practice.
15457   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15458                                              NeededForConstantEvaluation);
15459 
15460   // C++14 [temp.expl.spec]p6:
15461   //   If a template [...] is explicitly specialized then that specialization
15462   //   shall be declared before the first use of that specialization that would
15463   //   cause an implicit instantiation to take place, in every translation unit
15464   //   in which such a use occurs
15465   if (NeedDefinition &&
15466       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15467        Func->getMemberSpecializationInfo()))
15468     checkSpecializationVisibility(Loc, Func);
15469 
15470   // C++14 [except.spec]p17:
15471   //   An exception-specification is considered to be needed when:
15472   //   - the function is odr-used or, if it appears in an unevaluated operand,
15473   //     would be odr-used if the expression were potentially-evaluated;
15474   //
15475   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15476   // function is a pure virtual function we're calling, and in that case the
15477   // function was selected by overload resolution and we need to resolve its
15478   // exception specification for a different reason.
15479   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15480   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15481     ResolveExceptionSpec(Loc, FPT);
15482 
15483   if (getLangOpts().CUDA)
15484     CheckCUDACall(Loc, Func);
15485 
15486   // If we need a definition, try to create one.
15487   if (NeedDefinition && !Func->getBody()) {
15488     runWithSufficientStackSpace(Loc, [&] {
15489       if (CXXConstructorDecl *Constructor =
15490               dyn_cast<CXXConstructorDecl>(Func)) {
15491         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15492         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15493           if (Constructor->isDefaultConstructor()) {
15494             if (Constructor->isTrivial() &&
15495                 !Constructor->hasAttr<DLLExportAttr>())
15496               return;
15497             DefineImplicitDefaultConstructor(Loc, Constructor);
15498           } else if (Constructor->isCopyConstructor()) {
15499             DefineImplicitCopyConstructor(Loc, Constructor);
15500           } else if (Constructor->isMoveConstructor()) {
15501             DefineImplicitMoveConstructor(Loc, Constructor);
15502           }
15503         } else if (Constructor->getInheritedConstructor()) {
15504           DefineInheritingConstructor(Loc, Constructor);
15505         }
15506       } else if (CXXDestructorDecl *Destructor =
15507                      dyn_cast<CXXDestructorDecl>(Func)) {
15508         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15509         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15510           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15511             return;
15512           DefineImplicitDestructor(Loc, Destructor);
15513         }
15514         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15515           MarkVTableUsed(Loc, Destructor->getParent());
15516       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15517         if (MethodDecl->isOverloadedOperator() &&
15518             MethodDecl->getOverloadedOperator() == OO_Equal) {
15519           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15520           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15521             if (MethodDecl->isCopyAssignmentOperator())
15522               DefineImplicitCopyAssignment(Loc, MethodDecl);
15523             else if (MethodDecl->isMoveAssignmentOperator())
15524               DefineImplicitMoveAssignment(Loc, MethodDecl);
15525           }
15526         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15527                    MethodDecl->getParent()->isLambda()) {
15528           CXXConversionDecl *Conversion =
15529               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15530           if (Conversion->isLambdaToBlockPointerConversion())
15531             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15532           else
15533             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15534         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15535           MarkVTableUsed(Loc, MethodDecl->getParent());
15536       }
15537 
15538       // Implicit instantiation of function templates and member functions of
15539       // class templates.
15540       if (Func->isImplicitlyInstantiable()) {
15541         TemplateSpecializationKind TSK =
15542             Func->getTemplateSpecializationKindForInstantiation();
15543         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15544         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15545         if (FirstInstantiation) {
15546           PointOfInstantiation = Loc;
15547           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15548         } else if (TSK != TSK_ImplicitInstantiation) {
15549           // Use the point of use as the point of instantiation, instead of the
15550           // point of explicit instantiation (which we track as the actual point
15551           // of instantiation). This gives better backtraces in diagnostics.
15552           PointOfInstantiation = Loc;
15553         }
15554 
15555         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15556             Func->isConstexpr()) {
15557           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15558               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15559               CodeSynthesisContexts.size())
15560             PendingLocalImplicitInstantiations.push_back(
15561                 std::make_pair(Func, PointOfInstantiation));
15562           else if (Func->isConstexpr())
15563             // Do not defer instantiations of constexpr functions, to avoid the
15564             // expression evaluator needing to call back into Sema if it sees a
15565             // call to such a function.
15566             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15567           else {
15568             Func->setInstantiationIsPending(true);
15569             PendingInstantiations.push_back(
15570                 std::make_pair(Func, PointOfInstantiation));
15571             // Notify the consumer that a function was implicitly instantiated.
15572             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15573           }
15574         }
15575       } else {
15576         // Walk redefinitions, as some of them may be instantiable.
15577         for (auto i : Func->redecls()) {
15578           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15579             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15580         }
15581       }
15582     });
15583   }
15584 
15585   // If this is the first "real" use, act on that.
15586   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15587     // Keep track of used but undefined functions.
15588     if (!Func->isDefined()) {
15589       if (mightHaveNonExternalLinkage(Func))
15590         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15591       else if (Func->getMostRecentDecl()->isInlined() &&
15592                !LangOpts.GNUInline &&
15593                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15594         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15595       else if (isExternalWithNoLinkageType(Func))
15596         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15597     }
15598 
15599     // Some x86 Windows calling conventions mangle the size of the parameter
15600     // pack into the name. Computing the size of the parameters requires the
15601     // parameter types to be complete. Check that now.
15602     if (funcHasParameterSizeMangling(*this, Func))
15603       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15604 
15605     Func->markUsed(Context);
15606   }
15607 
15608   if (LangOpts.OpenMP) {
15609     markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15610     if (LangOpts.OpenMPIsDevice)
15611       checkOpenMPDeviceFunction(Loc, Func);
15612     else
15613       checkOpenMPHostFunction(Loc, Func);
15614   }
15615 }
15616 
15617 /// Directly mark a variable odr-used. Given a choice, prefer to use
15618 /// MarkVariableReferenced since it does additional checks and then
15619 /// calls MarkVarDeclODRUsed.
15620 /// If the variable must be captured:
15621 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15622 ///  - else capture it in the DeclContext that maps to the
15623 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15624 static void
15625 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15626                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15627   // Keep track of used but undefined variables.
15628   // FIXME: We shouldn't suppress this warning for static data members.
15629   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15630       (!Var->isExternallyVisible() || Var->isInline() ||
15631        SemaRef.isExternalWithNoLinkageType(Var)) &&
15632       !(Var->isStaticDataMember() && Var->hasInit())) {
15633     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15634     if (old.isInvalid())
15635       old = Loc;
15636   }
15637   QualType CaptureType, DeclRefType;
15638   if (SemaRef.LangOpts.OpenMP)
15639     SemaRef.tryCaptureOpenMPLambdas(Var);
15640   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15641     /*EllipsisLoc*/ SourceLocation(),
15642     /*BuildAndDiagnose*/ true,
15643     CaptureType, DeclRefType,
15644     FunctionScopeIndexToStopAt);
15645 
15646   Var->markUsed(SemaRef.Context);
15647 }
15648 
15649 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15650                                              SourceLocation Loc,
15651                                              unsigned CapturingScopeIndex) {
15652   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15653 }
15654 
15655 static void
15656 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15657                                    ValueDecl *var, DeclContext *DC) {
15658   DeclContext *VarDC = var->getDeclContext();
15659 
15660   //  If the parameter still belongs to the translation unit, then
15661   //  we're actually just using one parameter in the declaration of
15662   //  the next.
15663   if (isa<ParmVarDecl>(var) &&
15664       isa<TranslationUnitDecl>(VarDC))
15665     return;
15666 
15667   // For C code, don't diagnose about capture if we're not actually in code
15668   // right now; it's impossible to write a non-constant expression outside of
15669   // function context, so we'll get other (more useful) diagnostics later.
15670   //
15671   // For C++, things get a bit more nasty... it would be nice to suppress this
15672   // diagnostic for certain cases like using a local variable in an array bound
15673   // for a member of a local class, but the correct predicate is not obvious.
15674   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15675     return;
15676 
15677   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15678   unsigned ContextKind = 3; // unknown
15679   if (isa<CXXMethodDecl>(VarDC) &&
15680       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15681     ContextKind = 2;
15682   } else if (isa<FunctionDecl>(VarDC)) {
15683     ContextKind = 0;
15684   } else if (isa<BlockDecl>(VarDC)) {
15685     ContextKind = 1;
15686   }
15687 
15688   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15689     << var << ValueKind << ContextKind << VarDC;
15690   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15691       << var;
15692 
15693   // FIXME: Add additional diagnostic info about class etc. which prevents
15694   // capture.
15695 }
15696 
15697 
15698 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15699                                       bool &SubCapturesAreNested,
15700                                       QualType &CaptureType,
15701                                       QualType &DeclRefType) {
15702    // Check whether we've already captured it.
15703   if (CSI->CaptureMap.count(Var)) {
15704     // If we found a capture, any subcaptures are nested.
15705     SubCapturesAreNested = true;
15706 
15707     // Retrieve the capture type for this variable.
15708     CaptureType = CSI->getCapture(Var).getCaptureType();
15709 
15710     // Compute the type of an expression that refers to this variable.
15711     DeclRefType = CaptureType.getNonReferenceType();
15712 
15713     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15714     // are mutable in the sense that user can change their value - they are
15715     // private instances of the captured declarations.
15716     const Capture &Cap = CSI->getCapture(Var);
15717     if (Cap.isCopyCapture() &&
15718         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15719         !(isa<CapturedRegionScopeInfo>(CSI) &&
15720           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15721       DeclRefType.addConst();
15722     return true;
15723   }
15724   return false;
15725 }
15726 
15727 // Only block literals, captured statements, and lambda expressions can
15728 // capture; other scopes don't work.
15729 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15730                                  SourceLocation Loc,
15731                                  const bool Diagnose, Sema &S) {
15732   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15733     return getLambdaAwareParentOfDeclContext(DC);
15734   else if (Var->hasLocalStorage()) {
15735     if (Diagnose)
15736        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15737   }
15738   return nullptr;
15739 }
15740 
15741 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15742 // certain types of variables (unnamed, variably modified types etc.)
15743 // so check for eligibility.
15744 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15745                                  SourceLocation Loc,
15746                                  const bool Diagnose, Sema &S) {
15747 
15748   bool IsBlock = isa<BlockScopeInfo>(CSI);
15749   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15750 
15751   // Lambdas are not allowed to capture unnamed variables
15752   // (e.g. anonymous unions).
15753   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15754   // assuming that's the intent.
15755   if (IsLambda && !Var->getDeclName()) {
15756     if (Diagnose) {
15757       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15758       S.Diag(Var->getLocation(), diag::note_declared_at);
15759     }
15760     return false;
15761   }
15762 
15763   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15764   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15765     if (Diagnose) {
15766       S.Diag(Loc, diag::err_ref_vm_type);
15767       S.Diag(Var->getLocation(), diag::note_previous_decl)
15768         << Var->getDeclName();
15769     }
15770     return false;
15771   }
15772   // Prohibit structs with flexible array members too.
15773   // We cannot capture what is in the tail end of the struct.
15774   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15775     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15776       if (Diagnose) {
15777         if (IsBlock)
15778           S.Diag(Loc, diag::err_ref_flexarray_type);
15779         else
15780           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15781             << Var->getDeclName();
15782         S.Diag(Var->getLocation(), diag::note_previous_decl)
15783           << Var->getDeclName();
15784       }
15785       return false;
15786     }
15787   }
15788   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15789   // Lambdas and captured statements are not allowed to capture __block
15790   // variables; they don't support the expected semantics.
15791   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15792     if (Diagnose) {
15793       S.Diag(Loc, diag::err_capture_block_variable)
15794         << Var->getDeclName() << !IsLambda;
15795       S.Diag(Var->getLocation(), diag::note_previous_decl)
15796         << Var->getDeclName();
15797     }
15798     return false;
15799   }
15800   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15801   if (S.getLangOpts().OpenCL && IsBlock &&
15802       Var->getType()->isBlockPointerType()) {
15803     if (Diagnose)
15804       S.Diag(Loc, diag::err_opencl_block_ref_block);
15805     return false;
15806   }
15807 
15808   return true;
15809 }
15810 
15811 // Returns true if the capture by block was successful.
15812 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15813                                  SourceLocation Loc,
15814                                  const bool BuildAndDiagnose,
15815                                  QualType &CaptureType,
15816                                  QualType &DeclRefType,
15817                                  const bool Nested,
15818                                  Sema &S, bool Invalid) {
15819   bool ByRef = false;
15820 
15821   // Blocks are not allowed to capture arrays, excepting OpenCL.
15822   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15823   // (decayed to pointers).
15824   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15825     if (BuildAndDiagnose) {
15826       S.Diag(Loc, diag::err_ref_array_type);
15827       S.Diag(Var->getLocation(), diag::note_previous_decl)
15828       << Var->getDeclName();
15829       Invalid = true;
15830     } else {
15831       return false;
15832     }
15833   }
15834 
15835   // Forbid the block-capture of autoreleasing variables.
15836   if (!Invalid &&
15837       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15838     if (BuildAndDiagnose) {
15839       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15840         << /*block*/ 0;
15841       S.Diag(Var->getLocation(), diag::note_previous_decl)
15842         << Var->getDeclName();
15843       Invalid = true;
15844     } else {
15845       return false;
15846     }
15847   }
15848 
15849   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15850   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15851     QualType PointeeTy = PT->getPointeeType();
15852 
15853     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15854         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15855         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15856       if (BuildAndDiagnose) {
15857         SourceLocation VarLoc = Var->getLocation();
15858         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15859         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15860       }
15861     }
15862   }
15863 
15864   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15865   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15866       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15867     // Block capture by reference does not change the capture or
15868     // declaration reference types.
15869     ByRef = true;
15870   } else {
15871     // Block capture by copy introduces 'const'.
15872     CaptureType = CaptureType.getNonReferenceType().withConst();
15873     DeclRefType = CaptureType;
15874   }
15875 
15876   // Actually capture the variable.
15877   if (BuildAndDiagnose)
15878     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15879                     CaptureType, Invalid);
15880 
15881   return !Invalid;
15882 }
15883 
15884 
15885 /// Capture the given variable in the captured region.
15886 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15887                                     VarDecl *Var,
15888                                     SourceLocation Loc,
15889                                     const bool BuildAndDiagnose,
15890                                     QualType &CaptureType,
15891                                     QualType &DeclRefType,
15892                                     const bool RefersToCapturedVariable,
15893                                     Sema &S, bool Invalid) {
15894   // By default, capture variables by reference.
15895   bool ByRef = true;
15896   // Using an LValue reference type is consistent with Lambdas (see below).
15897   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15898     if (S.isOpenMPCapturedDecl(Var)) {
15899       bool HasConst = DeclRefType.isConstQualified();
15900       DeclRefType = DeclRefType.getUnqualifiedType();
15901       // Don't lose diagnostics about assignments to const.
15902       if (HasConst)
15903         DeclRefType.addConst();
15904     }
15905     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
15906                                     RSI->OpenMPCaptureLevel);
15907   }
15908 
15909   if (ByRef)
15910     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15911   else
15912     CaptureType = DeclRefType;
15913 
15914   // Actually capture the variable.
15915   if (BuildAndDiagnose)
15916     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15917                     Loc, SourceLocation(), CaptureType, Invalid);
15918 
15919   return !Invalid;
15920 }
15921 
15922 /// Capture the given variable in the lambda.
15923 static bool captureInLambda(LambdaScopeInfo *LSI,
15924                             VarDecl *Var,
15925                             SourceLocation Loc,
15926                             const bool BuildAndDiagnose,
15927                             QualType &CaptureType,
15928                             QualType &DeclRefType,
15929                             const bool RefersToCapturedVariable,
15930                             const Sema::TryCaptureKind Kind,
15931                             SourceLocation EllipsisLoc,
15932                             const bool IsTopScope,
15933                             Sema &S, bool Invalid) {
15934   // Determine whether we are capturing by reference or by value.
15935   bool ByRef = false;
15936   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15937     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15938   } else {
15939     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15940   }
15941 
15942   // Compute the type of the field that will capture this variable.
15943   if (ByRef) {
15944     // C++11 [expr.prim.lambda]p15:
15945     //   An entity is captured by reference if it is implicitly or
15946     //   explicitly captured but not captured by copy. It is
15947     //   unspecified whether additional unnamed non-static data
15948     //   members are declared in the closure type for entities
15949     //   captured by reference.
15950     //
15951     // FIXME: It is not clear whether we want to build an lvalue reference
15952     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15953     // to do the former, while EDG does the latter. Core issue 1249 will
15954     // clarify, but for now we follow GCC because it's a more permissive and
15955     // easily defensible position.
15956     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15957   } else {
15958     // C++11 [expr.prim.lambda]p14:
15959     //   For each entity captured by copy, an unnamed non-static
15960     //   data member is declared in the closure type. The
15961     //   declaration order of these members is unspecified. The type
15962     //   of such a data member is the type of the corresponding
15963     //   captured entity if the entity is not a reference to an
15964     //   object, or the referenced type otherwise. [Note: If the
15965     //   captured entity is a reference to a function, the
15966     //   corresponding data member is also a reference to a
15967     //   function. - end note ]
15968     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15969       if (!RefType->getPointeeType()->isFunctionType())
15970         CaptureType = RefType->getPointeeType();
15971     }
15972 
15973     // Forbid the lambda copy-capture of autoreleasing variables.
15974     if (!Invalid &&
15975         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15976       if (BuildAndDiagnose) {
15977         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15978         S.Diag(Var->getLocation(), diag::note_previous_decl)
15979           << Var->getDeclName();
15980         Invalid = true;
15981       } else {
15982         return false;
15983       }
15984     }
15985 
15986     // Make sure that by-copy captures are of a complete and non-abstract type.
15987     if (!Invalid && BuildAndDiagnose) {
15988       if (!CaptureType->isDependentType() &&
15989           S.RequireCompleteType(Loc, CaptureType,
15990                                 diag::err_capture_of_incomplete_type,
15991                                 Var->getDeclName()))
15992         Invalid = true;
15993       else if (S.RequireNonAbstractType(Loc, CaptureType,
15994                                         diag::err_capture_of_abstract_type))
15995         Invalid = true;
15996     }
15997   }
15998 
15999   // Compute the type of a reference to this captured variable.
16000   if (ByRef)
16001     DeclRefType = CaptureType.getNonReferenceType();
16002   else {
16003     // C++ [expr.prim.lambda]p5:
16004     //   The closure type for a lambda-expression has a public inline
16005     //   function call operator [...]. This function call operator is
16006     //   declared const (9.3.1) if and only if the lambda-expression's
16007     //   parameter-declaration-clause is not followed by mutable.
16008     DeclRefType = CaptureType.getNonReferenceType();
16009     if (!LSI->Mutable && !CaptureType->isReferenceType())
16010       DeclRefType.addConst();
16011   }
16012 
16013   // Add the capture.
16014   if (BuildAndDiagnose)
16015     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16016                     Loc, EllipsisLoc, CaptureType, Invalid);
16017 
16018   return !Invalid;
16019 }
16020 
16021 bool Sema::tryCaptureVariable(
16022     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16023     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16024     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16025   // An init-capture is notionally from the context surrounding its
16026   // declaration, but its parent DC is the lambda class.
16027   DeclContext *VarDC = Var->getDeclContext();
16028   if (Var->isInitCapture())
16029     VarDC = VarDC->getParent();
16030 
16031   DeclContext *DC = CurContext;
16032   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16033       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16034   // We need to sync up the Declaration Context with the
16035   // FunctionScopeIndexToStopAt
16036   if (FunctionScopeIndexToStopAt) {
16037     unsigned FSIndex = FunctionScopes.size() - 1;
16038     while (FSIndex != MaxFunctionScopesIndex) {
16039       DC = getLambdaAwareParentOfDeclContext(DC);
16040       --FSIndex;
16041     }
16042   }
16043 
16044 
16045   // If the variable is declared in the current context, there is no need to
16046   // capture it.
16047   if (VarDC == DC) return true;
16048 
16049   // Capture global variables if it is required to use private copy of this
16050   // variable.
16051   bool IsGlobal = !Var->hasLocalStorage();
16052   if (IsGlobal &&
16053       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16054                                                 MaxFunctionScopesIndex)))
16055     return true;
16056   Var = Var->getCanonicalDecl();
16057 
16058   // Walk up the stack to determine whether we can capture the variable,
16059   // performing the "simple" checks that don't depend on type. We stop when
16060   // we've either hit the declared scope of the variable or find an existing
16061   // capture of that variable.  We start from the innermost capturing-entity
16062   // (the DC) and ensure that all intervening capturing-entities
16063   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16064   // declcontext can either capture the variable or have already captured
16065   // the variable.
16066   CaptureType = Var->getType();
16067   DeclRefType = CaptureType.getNonReferenceType();
16068   bool Nested = false;
16069   bool Explicit = (Kind != TryCapture_Implicit);
16070   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16071   do {
16072     // Only block literals, captured statements, and lambda expressions can
16073     // capture; other scopes don't work.
16074     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16075                                                               ExprLoc,
16076                                                               BuildAndDiagnose,
16077                                                               *this);
16078     // We need to check for the parent *first* because, if we *have*
16079     // private-captured a global variable, we need to recursively capture it in
16080     // intermediate blocks, lambdas, etc.
16081     if (!ParentDC) {
16082       if (IsGlobal) {
16083         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16084         break;
16085       }
16086       return true;
16087     }
16088 
16089     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
16090     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16091 
16092 
16093     // Check whether we've already captured it.
16094     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16095                                              DeclRefType)) {
16096       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16097       break;
16098     }
16099     // If we are instantiating a generic lambda call operator body,
16100     // we do not want to capture new variables.  What was captured
16101     // during either a lambdas transformation or initial parsing
16102     // should be used.
16103     if (isGenericLambdaCallOperatorSpecialization(DC)) {
16104       if (BuildAndDiagnose) {
16105         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16106         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16107           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16108           Diag(Var->getLocation(), diag::note_previous_decl)
16109              << Var->getDeclName();
16110           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16111         } else
16112           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16113       }
16114       return true;
16115     }
16116 
16117     // Try to capture variable-length arrays types.
16118     if (Var->getType()->isVariablyModifiedType()) {
16119       // We're going to walk down into the type and look for VLA
16120       // expressions.
16121       QualType QTy = Var->getType();
16122       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16123         QTy = PVD->getOriginalType();
16124       captureVariablyModifiedType(Context, QTy, CSI);
16125     }
16126 
16127     if (getLangOpts().OpenMP) {
16128       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16129         // OpenMP private variables should not be captured in outer scope, so
16130         // just break here. Similarly, global variables that are captured in a
16131         // target region should not be captured outside the scope of the region.
16132         if (RSI->CapRegionKind == CR_OpenMP) {
16133           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16134           // If the variable is private (i.e. not captured) and has variably
16135           // modified type, we still need to capture the type for correct
16136           // codegen in all regions, associated with the construct. Currently,
16137           // it is captured in the innermost captured region only.
16138           if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
16139             QualType QTy = Var->getType();
16140             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16141               QTy = PVD->getOriginalType();
16142             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
16143                  I < E; ++I) {
16144               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
16145                   FunctionScopes[FunctionScopesIndex - I]);
16146               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
16147                      "Wrong number of captured regions associated with the "
16148                      "OpenMP construct.");
16149               captureVariablyModifiedType(Context, QTy, OuterRSI);
16150             }
16151           }
16152           bool IsTargetCap = !IsOpenMPPrivateDecl &&
16153                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16154           // When we detect target captures we are looking from inside the
16155           // target region, therefore we need to propagate the capture from the
16156           // enclosing region. Therefore, the capture is not initially nested.
16157           if (IsTargetCap)
16158             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16159 
16160           if (IsTargetCap || IsOpenMPPrivateDecl) {
16161             Nested = !IsTargetCap;
16162             DeclRefType = DeclRefType.getUnqualifiedType();
16163             CaptureType = Context.getLValueReferenceType(DeclRefType);
16164             break;
16165           }
16166         }
16167       }
16168     }
16169     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16170       // No capture-default, and this is not an explicit capture
16171       // so cannot capture this variable.
16172       if (BuildAndDiagnose) {
16173         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16174         Diag(Var->getLocation(), diag::note_previous_decl)
16175           << Var->getDeclName();
16176         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16177           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16178                diag::note_lambda_decl);
16179         // FIXME: If we error out because an outer lambda can not implicitly
16180         // capture a variable that an inner lambda explicitly captures, we
16181         // should have the inner lambda do the explicit capture - because
16182         // it makes for cleaner diagnostics later.  This would purely be done
16183         // so that the diagnostic does not misleadingly claim that a variable
16184         // can not be captured by a lambda implicitly even though it is captured
16185         // explicitly.  Suggestion:
16186         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16187         //    at the function head
16188         //  - cache the StartingDeclContext - this must be a lambda
16189         //  - captureInLambda in the innermost lambda the variable.
16190       }
16191       return true;
16192     }
16193 
16194     FunctionScopesIndex--;
16195     DC = ParentDC;
16196     Explicit = false;
16197   } while (!VarDC->Equals(DC));
16198 
16199   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16200   // computing the type of the capture at each step, checking type-specific
16201   // requirements, and adding captures if requested.
16202   // If the variable had already been captured previously, we start capturing
16203   // at the lambda nested within that one.
16204   bool Invalid = false;
16205   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16206        ++I) {
16207     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16208 
16209     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16210     // certain types of variables (unnamed, variably modified types etc.)
16211     // so check for eligibility.
16212     if (!Invalid)
16213       Invalid =
16214           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16215 
16216     // After encountering an error, if we're actually supposed to capture, keep
16217     // capturing in nested contexts to suppress any follow-on diagnostics.
16218     if (Invalid && !BuildAndDiagnose)
16219       return true;
16220 
16221     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16222       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16223                                DeclRefType, Nested, *this, Invalid);
16224       Nested = true;
16225     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16226       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16227                                          CaptureType, DeclRefType, Nested,
16228                                          *this, Invalid);
16229       Nested = true;
16230     } else {
16231       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16232       Invalid =
16233           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16234                            DeclRefType, Nested, Kind, EllipsisLoc,
16235                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16236       Nested = true;
16237     }
16238 
16239     if (Invalid && !BuildAndDiagnose)
16240       return true;
16241   }
16242   return Invalid;
16243 }
16244 
16245 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16246                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16247   QualType CaptureType;
16248   QualType DeclRefType;
16249   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16250                             /*BuildAndDiagnose=*/true, CaptureType,
16251                             DeclRefType, nullptr);
16252 }
16253 
16254 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16255   QualType CaptureType;
16256   QualType DeclRefType;
16257   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16258                              /*BuildAndDiagnose=*/false, CaptureType,
16259                              DeclRefType, nullptr);
16260 }
16261 
16262 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16263   QualType CaptureType;
16264   QualType DeclRefType;
16265 
16266   // Determine whether we can capture this variable.
16267   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16268                          /*BuildAndDiagnose=*/false, CaptureType,
16269                          DeclRefType, nullptr))
16270     return QualType();
16271 
16272   return DeclRefType;
16273 }
16274 
16275 namespace {
16276 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16277 // The produced TemplateArgumentListInfo* points to data stored within this
16278 // object, so should only be used in contexts where the pointer will not be
16279 // used after the CopiedTemplateArgs object is destroyed.
16280 class CopiedTemplateArgs {
16281   bool HasArgs;
16282   TemplateArgumentListInfo TemplateArgStorage;
16283 public:
16284   template<typename RefExpr>
16285   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16286     if (HasArgs)
16287       E->copyTemplateArgumentsInto(TemplateArgStorage);
16288   }
16289   operator TemplateArgumentListInfo*()
16290 #ifdef __has_cpp_attribute
16291 #if __has_cpp_attribute(clang::lifetimebound)
16292   [[clang::lifetimebound]]
16293 #endif
16294 #endif
16295   {
16296     return HasArgs ? &TemplateArgStorage : nullptr;
16297   }
16298 };
16299 }
16300 
16301 /// Walk the set of potential results of an expression and mark them all as
16302 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16303 ///
16304 /// \return A new expression if we found any potential results, ExprEmpty() if
16305 ///         not, and ExprError() if we diagnosed an error.
16306 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16307                                                       NonOdrUseReason NOUR) {
16308   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16309   // an object that satisfies the requirements for appearing in a
16310   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16311   // is immediately applied."  This function handles the lvalue-to-rvalue
16312   // conversion part.
16313   //
16314   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16315   // transform it into the relevant kind of non-odr-use node and rebuild the
16316   // tree of nodes leading to it.
16317   //
16318   // This is a mini-TreeTransform that only transforms a restricted subset of
16319   // nodes (and only certain operands of them).
16320 
16321   // Rebuild a subexpression.
16322   auto Rebuild = [&](Expr *Sub) {
16323     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16324   };
16325 
16326   // Check whether a potential result satisfies the requirements of NOUR.
16327   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16328     // Any entity other than a VarDecl is always odr-used whenever it's named
16329     // in a potentially-evaluated expression.
16330     auto *VD = dyn_cast<VarDecl>(D);
16331     if (!VD)
16332       return true;
16333 
16334     // C++2a [basic.def.odr]p4:
16335     //   A variable x whose name appears as a potentially-evalauted expression
16336     //   e is odr-used by e unless
16337     //   -- x is a reference that is usable in constant expressions, or
16338     //   -- x is a variable of non-reference type that is usable in constant
16339     //      expressions and has no mutable subobjects, and e is an element of
16340     //      the set of potential results of an expression of
16341     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16342     //      conversion is applied, or
16343     //   -- x is a variable of non-reference type, and e is an element of the
16344     //      set of potential results of a discarded-value expression to which
16345     //      the lvalue-to-rvalue conversion is not applied
16346     //
16347     // We check the first bullet and the "potentially-evaluated" condition in
16348     // BuildDeclRefExpr. We check the type requirements in the second bullet
16349     // in CheckLValueToRValueConversionOperand below.
16350     switch (NOUR) {
16351     case NOUR_None:
16352     case NOUR_Unevaluated:
16353       llvm_unreachable("unexpected non-odr-use-reason");
16354 
16355     case NOUR_Constant:
16356       // Constant references were handled when they were built.
16357       if (VD->getType()->isReferenceType())
16358         return true;
16359       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16360         if (RD->hasMutableFields())
16361           return true;
16362       if (!VD->isUsableInConstantExpressions(S.Context))
16363         return true;
16364       break;
16365 
16366     case NOUR_Discarded:
16367       if (VD->getType()->isReferenceType())
16368         return true;
16369       break;
16370     }
16371     return false;
16372   };
16373 
16374   // Mark that this expression does not constitute an odr-use.
16375   auto MarkNotOdrUsed = [&] {
16376     S.MaybeODRUseExprs.erase(E);
16377     if (LambdaScopeInfo *LSI = S.getCurLambda())
16378       LSI->markVariableExprAsNonODRUsed(E);
16379   };
16380 
16381   // C++2a [basic.def.odr]p2:
16382   //   The set of potential results of an expression e is defined as follows:
16383   switch (E->getStmtClass()) {
16384   //   -- If e is an id-expression, ...
16385   case Expr::DeclRefExprClass: {
16386     auto *DRE = cast<DeclRefExpr>(E);
16387     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16388       break;
16389 
16390     // Rebuild as a non-odr-use DeclRefExpr.
16391     MarkNotOdrUsed();
16392     return DeclRefExpr::Create(
16393         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16394         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16395         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16396         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16397   }
16398 
16399   case Expr::FunctionParmPackExprClass: {
16400     auto *FPPE = cast<FunctionParmPackExpr>(E);
16401     // If any of the declarations in the pack is odr-used, then the expression
16402     // as a whole constitutes an odr-use.
16403     for (VarDecl *D : *FPPE)
16404       if (IsPotentialResultOdrUsed(D))
16405         return ExprEmpty();
16406 
16407     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16408     // nothing cares about whether we marked this as an odr-use, but it might
16409     // be useful for non-compiler tools.
16410     MarkNotOdrUsed();
16411     break;
16412   }
16413 
16414   //   -- If e is a subscripting operation with an array operand...
16415   case Expr::ArraySubscriptExprClass: {
16416     auto *ASE = cast<ArraySubscriptExpr>(E);
16417     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16418     if (!OldBase->getType()->isArrayType())
16419       break;
16420     ExprResult Base = Rebuild(OldBase);
16421     if (!Base.isUsable())
16422       return Base;
16423     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16424     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16425     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16426     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16427                                      ASE->getRBracketLoc());
16428   }
16429 
16430   case Expr::MemberExprClass: {
16431     auto *ME = cast<MemberExpr>(E);
16432     // -- If e is a class member access expression [...] naming a non-static
16433     //    data member...
16434     if (isa<FieldDecl>(ME->getMemberDecl())) {
16435       ExprResult Base = Rebuild(ME->getBase());
16436       if (!Base.isUsable())
16437         return Base;
16438       return MemberExpr::Create(
16439           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16440           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16441           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16442           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16443           ME->getObjectKind(), ME->isNonOdrUse());
16444     }
16445 
16446     if (ME->getMemberDecl()->isCXXInstanceMember())
16447       break;
16448 
16449     // -- If e is a class member access expression naming a static data member,
16450     //    ...
16451     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16452       break;
16453 
16454     // Rebuild as a non-odr-use MemberExpr.
16455     MarkNotOdrUsed();
16456     return MemberExpr::Create(
16457         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16458         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16459         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16460         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16461     return ExprEmpty();
16462   }
16463 
16464   case Expr::BinaryOperatorClass: {
16465     auto *BO = cast<BinaryOperator>(E);
16466     Expr *LHS = BO->getLHS();
16467     Expr *RHS = BO->getRHS();
16468     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16469     if (BO->getOpcode() == BO_PtrMemD) {
16470       ExprResult Sub = Rebuild(LHS);
16471       if (!Sub.isUsable())
16472         return Sub;
16473       LHS = Sub.get();
16474     //   -- If e is a comma expression, ...
16475     } else if (BO->getOpcode() == BO_Comma) {
16476       ExprResult Sub = Rebuild(RHS);
16477       if (!Sub.isUsable())
16478         return Sub;
16479       RHS = Sub.get();
16480     } else {
16481       break;
16482     }
16483     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16484                         LHS, RHS);
16485   }
16486 
16487   //   -- If e has the form (e1)...
16488   case Expr::ParenExprClass: {
16489     auto *PE = cast<ParenExpr>(E);
16490     ExprResult Sub = Rebuild(PE->getSubExpr());
16491     if (!Sub.isUsable())
16492       return Sub;
16493     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16494   }
16495 
16496   //   -- If e is a glvalue conditional expression, ...
16497   // We don't apply this to a binary conditional operator. FIXME: Should we?
16498   case Expr::ConditionalOperatorClass: {
16499     auto *CO = cast<ConditionalOperator>(E);
16500     ExprResult LHS = Rebuild(CO->getLHS());
16501     if (LHS.isInvalid())
16502       return ExprError();
16503     ExprResult RHS = Rebuild(CO->getRHS());
16504     if (RHS.isInvalid())
16505       return ExprError();
16506     if (!LHS.isUsable() && !RHS.isUsable())
16507       return ExprEmpty();
16508     if (!LHS.isUsable())
16509       LHS = CO->getLHS();
16510     if (!RHS.isUsable())
16511       RHS = CO->getRHS();
16512     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16513                                 CO->getCond(), LHS.get(), RHS.get());
16514   }
16515 
16516   // [Clang extension]
16517   //   -- If e has the form __extension__ e1...
16518   case Expr::UnaryOperatorClass: {
16519     auto *UO = cast<UnaryOperator>(E);
16520     if (UO->getOpcode() != UO_Extension)
16521       break;
16522     ExprResult Sub = Rebuild(UO->getSubExpr());
16523     if (!Sub.isUsable())
16524       return Sub;
16525     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16526                           Sub.get());
16527   }
16528 
16529   // [Clang extension]
16530   //   -- If e has the form _Generic(...), the set of potential results is the
16531   //      union of the sets of potential results of the associated expressions.
16532   case Expr::GenericSelectionExprClass: {
16533     auto *GSE = cast<GenericSelectionExpr>(E);
16534 
16535     SmallVector<Expr *, 4> AssocExprs;
16536     bool AnyChanged = false;
16537     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16538       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16539       if (AssocExpr.isInvalid())
16540         return ExprError();
16541       if (AssocExpr.isUsable()) {
16542         AssocExprs.push_back(AssocExpr.get());
16543         AnyChanged = true;
16544       } else {
16545         AssocExprs.push_back(OrigAssocExpr);
16546       }
16547     }
16548 
16549     return AnyChanged ? S.CreateGenericSelectionExpr(
16550                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16551                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16552                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16553                       : ExprEmpty();
16554   }
16555 
16556   // [Clang extension]
16557   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16558   //      results is the union of the sets of potential results of the
16559   //      second and third subexpressions.
16560   case Expr::ChooseExprClass: {
16561     auto *CE = cast<ChooseExpr>(E);
16562 
16563     ExprResult LHS = Rebuild(CE->getLHS());
16564     if (LHS.isInvalid())
16565       return ExprError();
16566 
16567     ExprResult RHS = Rebuild(CE->getLHS());
16568     if (RHS.isInvalid())
16569       return ExprError();
16570 
16571     if (!LHS.get() && !RHS.get())
16572       return ExprEmpty();
16573     if (!LHS.isUsable())
16574       LHS = CE->getLHS();
16575     if (!RHS.isUsable())
16576       RHS = CE->getRHS();
16577 
16578     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16579                              RHS.get(), CE->getRParenLoc());
16580   }
16581 
16582   // Step through non-syntactic nodes.
16583   case Expr::ConstantExprClass: {
16584     auto *CE = cast<ConstantExpr>(E);
16585     ExprResult Sub = Rebuild(CE->getSubExpr());
16586     if (!Sub.isUsable())
16587       return Sub;
16588     return ConstantExpr::Create(S.Context, Sub.get());
16589   }
16590 
16591   // We could mostly rely on the recursive rebuilding to rebuild implicit
16592   // casts, but not at the top level, so rebuild them here.
16593   case Expr::ImplicitCastExprClass: {
16594     auto *ICE = cast<ImplicitCastExpr>(E);
16595     // Only step through the narrow set of cast kinds we expect to encounter.
16596     // Anything else suggests we've left the region in which potential results
16597     // can be found.
16598     switch (ICE->getCastKind()) {
16599     case CK_NoOp:
16600     case CK_DerivedToBase:
16601     case CK_UncheckedDerivedToBase: {
16602       ExprResult Sub = Rebuild(ICE->getSubExpr());
16603       if (!Sub.isUsable())
16604         return Sub;
16605       CXXCastPath Path(ICE->path());
16606       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16607                                  ICE->getValueKind(), &Path);
16608     }
16609 
16610     default:
16611       break;
16612     }
16613     break;
16614   }
16615 
16616   default:
16617     break;
16618   }
16619 
16620   // Can't traverse through this node. Nothing to do.
16621   return ExprEmpty();
16622 }
16623 
16624 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16625   // Check whether the operand is or contains an object of non-trivial C union
16626   // type.
16627   if (E->getType().isVolatileQualified() &&
16628       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16629        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16630     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16631                           Sema::NTCUC_LValueToRValueVolatile,
16632                           NTCUK_Destruct|NTCUK_Copy);
16633 
16634   // C++2a [basic.def.odr]p4:
16635   //   [...] an expression of non-volatile-qualified non-class type to which
16636   //   the lvalue-to-rvalue conversion is applied [...]
16637   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16638     return E;
16639 
16640   ExprResult Result =
16641       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16642   if (Result.isInvalid())
16643     return ExprError();
16644   return Result.get() ? Result : E;
16645 }
16646 
16647 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16648   Res = CorrectDelayedTyposInExpr(Res);
16649 
16650   if (!Res.isUsable())
16651     return Res;
16652 
16653   // If a constant-expression is a reference to a variable where we delay
16654   // deciding whether it is an odr-use, just assume we will apply the
16655   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16656   // (a non-type template argument), we have special handling anyway.
16657   return CheckLValueToRValueConversionOperand(Res.get());
16658 }
16659 
16660 void Sema::CleanupVarDeclMarking() {
16661   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16662   // call.
16663   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16664   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16665 
16666   for (Expr *E : LocalMaybeODRUseExprs) {
16667     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16668       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16669                          DRE->getLocation(), *this);
16670     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16671       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16672                          *this);
16673     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16674       for (VarDecl *VD : *FP)
16675         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16676     } else {
16677       llvm_unreachable("Unexpected expression");
16678     }
16679   }
16680 
16681   assert(MaybeODRUseExprs.empty() &&
16682          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16683 }
16684 
16685 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16686                                     VarDecl *Var, Expr *E) {
16687   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16688           isa<FunctionParmPackExpr>(E)) &&
16689          "Invalid Expr argument to DoMarkVarDeclReferenced");
16690   Var->setReferenced();
16691 
16692   if (Var->isInvalidDecl())
16693     return;
16694 
16695   auto *MSI = Var->getMemberSpecializationInfo();
16696   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16697                                        : Var->getTemplateSpecializationKind();
16698 
16699   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16700   bool UsableInConstantExpr =
16701       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16702 
16703   // C++20 [expr.const]p12:
16704   //   A variable [...] is needed for constant evaluation if it is [...] a
16705   //   variable whose name appears as a potentially constant evaluated
16706   //   expression that is either a contexpr variable or is of non-volatile
16707   //   const-qualified integral type or of reference type
16708   bool NeededForConstantEvaluation =
16709       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16710 
16711   bool NeedDefinition =
16712       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16713 
16714   VarTemplateSpecializationDecl *VarSpec =
16715       dyn_cast<VarTemplateSpecializationDecl>(Var);
16716   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16717          "Can't instantiate a partial template specialization.");
16718 
16719   // If this might be a member specialization of a static data member, check
16720   // the specialization is visible. We already did the checks for variable
16721   // template specializations when we created them.
16722   if (NeedDefinition && TSK != TSK_Undeclared &&
16723       !isa<VarTemplateSpecializationDecl>(Var))
16724     SemaRef.checkSpecializationVisibility(Loc, Var);
16725 
16726   // Perform implicit instantiation of static data members, static data member
16727   // templates of class templates, and variable template specializations. Delay
16728   // instantiations of variable templates, except for those that could be used
16729   // in a constant expression.
16730   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16731     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16732     // instantiation declaration if a variable is usable in a constant
16733     // expression (among other cases).
16734     bool TryInstantiating =
16735         TSK == TSK_ImplicitInstantiation ||
16736         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16737 
16738     if (TryInstantiating) {
16739       SourceLocation PointOfInstantiation =
16740           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16741       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16742       if (FirstInstantiation) {
16743         PointOfInstantiation = Loc;
16744         if (MSI)
16745           MSI->setPointOfInstantiation(PointOfInstantiation);
16746         else
16747           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16748       }
16749 
16750       bool InstantiationDependent = false;
16751       bool IsNonDependent =
16752           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16753                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16754                   : true;
16755 
16756       // Do not instantiate specializations that are still type-dependent.
16757       if (IsNonDependent) {
16758         if (UsableInConstantExpr) {
16759           // Do not defer instantiations of variables that could be used in a
16760           // constant expression.
16761           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16762             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16763           });
16764         } else if (FirstInstantiation ||
16765                    isa<VarTemplateSpecializationDecl>(Var)) {
16766           // FIXME: For a specialization of a variable template, we don't
16767           // distinguish between "declaration and type implicitly instantiated"
16768           // and "implicit instantiation of definition requested", so we have
16769           // no direct way to avoid enqueueing the pending instantiation
16770           // multiple times.
16771           SemaRef.PendingInstantiations
16772               .push_back(std::make_pair(Var, PointOfInstantiation));
16773         }
16774       }
16775     }
16776   }
16777 
16778   // C++2a [basic.def.odr]p4:
16779   //   A variable x whose name appears as a potentially-evaluated expression e
16780   //   is odr-used by e unless
16781   //   -- x is a reference that is usable in constant expressions
16782   //   -- x is a variable of non-reference type that is usable in constant
16783   //      expressions and has no mutable subobjects [FIXME], and e is an
16784   //      element of the set of potential results of an expression of
16785   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16786   //      conversion is applied
16787   //   -- x is a variable of non-reference type, and e is an element of the set
16788   //      of potential results of a discarded-value expression to which the
16789   //      lvalue-to-rvalue conversion is not applied [FIXME]
16790   //
16791   // We check the first part of the second bullet here, and
16792   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16793   // FIXME: To get the third bullet right, we need to delay this even for
16794   // variables that are not usable in constant expressions.
16795 
16796   // If we already know this isn't an odr-use, there's nothing more to do.
16797   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16798     if (DRE->isNonOdrUse())
16799       return;
16800   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16801     if (ME->isNonOdrUse())
16802       return;
16803 
16804   switch (OdrUse) {
16805   case OdrUseContext::None:
16806     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16807            "missing non-odr-use marking for unevaluated decl ref");
16808     break;
16809 
16810   case OdrUseContext::FormallyOdrUsed:
16811     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16812     // behavior.
16813     break;
16814 
16815   case OdrUseContext::Used:
16816     // If we might later find that this expression isn't actually an odr-use,
16817     // delay the marking.
16818     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16819       SemaRef.MaybeODRUseExprs.insert(E);
16820     else
16821       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16822     break;
16823 
16824   case OdrUseContext::Dependent:
16825     // If this is a dependent context, we don't need to mark variables as
16826     // odr-used, but we may still need to track them for lambda capture.
16827     // FIXME: Do we also need to do this inside dependent typeid expressions
16828     // (which are modeled as unevaluated at this point)?
16829     const bool RefersToEnclosingScope =
16830         (SemaRef.CurContext != Var->getDeclContext() &&
16831          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16832     if (RefersToEnclosingScope) {
16833       LambdaScopeInfo *const LSI =
16834           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16835       if (LSI && (!LSI->CallOperator ||
16836                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16837         // If a variable could potentially be odr-used, defer marking it so
16838         // until we finish analyzing the full expression for any
16839         // lvalue-to-rvalue
16840         // or discarded value conversions that would obviate odr-use.
16841         // Add it to the list of potential captures that will be analyzed
16842         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16843         // unless the variable is a reference that was initialized by a constant
16844         // expression (this will never need to be captured or odr-used).
16845         //
16846         // FIXME: We can simplify this a lot after implementing P0588R1.
16847         assert(E && "Capture variable should be used in an expression.");
16848         if (!Var->getType()->isReferenceType() ||
16849             !Var->isUsableInConstantExpressions(SemaRef.Context))
16850           LSI->addPotentialCapture(E->IgnoreParens());
16851       }
16852     }
16853     break;
16854   }
16855 }
16856 
16857 /// Mark a variable referenced, and check whether it is odr-used
16858 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16859 /// used directly for normal expressions referring to VarDecl.
16860 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16861   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16862 }
16863 
16864 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16865                                Decl *D, Expr *E, bool MightBeOdrUse) {
16866   if (SemaRef.isInOpenMPDeclareTargetContext())
16867     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16868 
16869   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16870     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16871     return;
16872   }
16873 
16874   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16875 
16876   // If this is a call to a method via a cast, also mark the method in the
16877   // derived class used in case codegen can devirtualize the call.
16878   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16879   if (!ME)
16880     return;
16881   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16882   if (!MD)
16883     return;
16884   // Only attempt to devirtualize if this is truly a virtual call.
16885   bool IsVirtualCall = MD->isVirtual() &&
16886                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16887   if (!IsVirtualCall)
16888     return;
16889 
16890   // If it's possible to devirtualize the call, mark the called function
16891   // referenced.
16892   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16893       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16894   if (DM)
16895     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16896 }
16897 
16898 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16899 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16900   // TODO: update this with DR# once a defect report is filed.
16901   // C++11 defect. The address of a pure member should not be an ODR use, even
16902   // if it's a qualified reference.
16903   bool OdrUse = true;
16904   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16905     if (Method->isVirtual() &&
16906         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16907       OdrUse = false;
16908   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16909 }
16910 
16911 /// Perform reference-marking and odr-use handling for a MemberExpr.
16912 void Sema::MarkMemberReferenced(MemberExpr *E) {
16913   // C++11 [basic.def.odr]p2:
16914   //   A non-overloaded function whose name appears as a potentially-evaluated
16915   //   expression or a member of a set of candidate functions, if selected by
16916   //   overload resolution when referred to from a potentially-evaluated
16917   //   expression, is odr-used, unless it is a pure virtual function and its
16918   //   name is not explicitly qualified.
16919   bool MightBeOdrUse = true;
16920   if (E->performsVirtualDispatch(getLangOpts())) {
16921     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16922       if (Method->isPure())
16923         MightBeOdrUse = false;
16924   }
16925   SourceLocation Loc =
16926       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16927   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16928 }
16929 
16930 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16931 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16932   for (VarDecl *VD : *E)
16933     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16934 }
16935 
16936 /// Perform marking for a reference to an arbitrary declaration.  It
16937 /// marks the declaration referenced, and performs odr-use checking for
16938 /// functions and variables. This method should not be used when building a
16939 /// normal expression which refers to a variable.
16940 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16941                                  bool MightBeOdrUse) {
16942   if (MightBeOdrUse) {
16943     if (auto *VD = dyn_cast<VarDecl>(D)) {
16944       MarkVariableReferenced(Loc, VD);
16945       return;
16946     }
16947   }
16948   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16949     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16950     return;
16951   }
16952   D->setReferenced();
16953 }
16954 
16955 namespace {
16956   // Mark all of the declarations used by a type as referenced.
16957   // FIXME: Not fully implemented yet! We need to have a better understanding
16958   // of when we're entering a context we should not recurse into.
16959   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16960   // TreeTransforms rebuilding the type in a new context. Rather than
16961   // duplicating the TreeTransform logic, we should consider reusing it here.
16962   // Currently that causes problems when rebuilding LambdaExprs.
16963   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16964     Sema &S;
16965     SourceLocation Loc;
16966 
16967   public:
16968     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16969 
16970     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16971 
16972     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16973   };
16974 }
16975 
16976 bool MarkReferencedDecls::TraverseTemplateArgument(
16977     const TemplateArgument &Arg) {
16978   {
16979     // A non-type template argument is a constant-evaluated context.
16980     EnterExpressionEvaluationContext Evaluated(
16981         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16982     if (Arg.getKind() == TemplateArgument::Declaration) {
16983       if (Decl *D = Arg.getAsDecl())
16984         S.MarkAnyDeclReferenced(Loc, D, true);
16985     } else if (Arg.getKind() == TemplateArgument::Expression) {
16986       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16987     }
16988   }
16989 
16990   return Inherited::TraverseTemplateArgument(Arg);
16991 }
16992 
16993 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16994   MarkReferencedDecls Marker(*this, Loc);
16995   Marker.TraverseType(T);
16996 }
16997 
16998 namespace {
16999   /// Helper class that marks all of the declarations referenced by
17000   /// potentially-evaluated subexpressions as "referenced".
17001   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
17002     Sema &S;
17003     bool SkipLocalVariables;
17004 
17005   public:
17006     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
17007 
17008     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17009       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
17010 
17011     void VisitDeclRefExpr(DeclRefExpr *E) {
17012       // If we were asked not to visit local variables, don't.
17013       if (SkipLocalVariables) {
17014         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17015           if (VD->hasLocalStorage())
17016             return;
17017       }
17018 
17019       S.MarkDeclRefReferenced(E);
17020     }
17021 
17022     void VisitMemberExpr(MemberExpr *E) {
17023       S.MarkMemberReferenced(E);
17024       Inherited::VisitMemberExpr(E);
17025     }
17026 
17027     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
17028       S.MarkFunctionReferenced(
17029           E->getBeginLoc(),
17030           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
17031       Visit(E->getSubExpr());
17032     }
17033 
17034     void VisitCXXNewExpr(CXXNewExpr *E) {
17035       if (E->getOperatorNew())
17036         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
17037       if (E->getOperatorDelete())
17038         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17039       Inherited::VisitCXXNewExpr(E);
17040     }
17041 
17042     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
17043       if (E->getOperatorDelete())
17044         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17045       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
17046       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
17047         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
17048         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
17049       }
17050 
17051       Inherited::VisitCXXDeleteExpr(E);
17052     }
17053 
17054     void VisitCXXConstructExpr(CXXConstructExpr *E) {
17055       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
17056       Inherited::VisitCXXConstructExpr(E);
17057     }
17058 
17059     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
17060       Visit(E->getExpr());
17061     }
17062   };
17063 }
17064 
17065 /// Mark any declarations that appear within this expression or any
17066 /// potentially-evaluated subexpressions as "referenced".
17067 ///
17068 /// \param SkipLocalVariables If true, don't mark local variables as
17069 /// 'referenced'.
17070 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17071                                             bool SkipLocalVariables) {
17072   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17073 }
17074 
17075 /// Emit a diagnostic that describes an effect on the run-time behavior
17076 /// of the program being compiled.
17077 ///
17078 /// This routine emits the given diagnostic when the code currently being
17079 /// type-checked is "potentially evaluated", meaning that there is a
17080 /// possibility that the code will actually be executable. Code in sizeof()
17081 /// expressions, code used only during overload resolution, etc., are not
17082 /// potentially evaluated. This routine will suppress such diagnostics or,
17083 /// in the absolutely nutty case of potentially potentially evaluated
17084 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17085 /// later.
17086 ///
17087 /// This routine should be used for all diagnostics that describe the run-time
17088 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17089 /// Failure to do so will likely result in spurious diagnostics or failures
17090 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17091 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17092                                const PartialDiagnostic &PD) {
17093   switch (ExprEvalContexts.back().Context) {
17094   case ExpressionEvaluationContext::Unevaluated:
17095   case ExpressionEvaluationContext::UnevaluatedList:
17096   case ExpressionEvaluationContext::UnevaluatedAbstract:
17097   case ExpressionEvaluationContext::DiscardedStatement:
17098     // The argument will never be evaluated, so don't complain.
17099     break;
17100 
17101   case ExpressionEvaluationContext::ConstantEvaluated:
17102     // Relevant diagnostics should be produced by constant evaluation.
17103     break;
17104 
17105   case ExpressionEvaluationContext::PotentiallyEvaluated:
17106   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17107     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17108       FunctionScopes.back()->PossiblyUnreachableDiags.
17109         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17110       return true;
17111     }
17112 
17113     // The initializer of a constexpr variable or of the first declaration of a
17114     // static data member is not syntactically a constant evaluated constant,
17115     // but nonetheless is always required to be a constant expression, so we
17116     // can skip diagnosing.
17117     // FIXME: Using the mangling context here is a hack.
17118     if (auto *VD = dyn_cast_or_null<VarDecl>(
17119             ExprEvalContexts.back().ManglingContextDecl)) {
17120       if (VD->isConstexpr() ||
17121           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17122         break;
17123       // FIXME: For any other kind of variable, we should build a CFG for its
17124       // initializer and check whether the context in question is reachable.
17125     }
17126 
17127     Diag(Loc, PD);
17128     return true;
17129   }
17130 
17131   return false;
17132 }
17133 
17134 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17135                                const PartialDiagnostic &PD) {
17136   return DiagRuntimeBehavior(
17137       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17138 }
17139 
17140 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17141                                CallExpr *CE, FunctionDecl *FD) {
17142   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17143     return false;
17144 
17145   // If we're inside a decltype's expression, don't check for a valid return
17146   // type or construct temporaries until we know whether this is the last call.
17147   if (ExprEvalContexts.back().ExprContext ==
17148       ExpressionEvaluationContextRecord::EK_Decltype) {
17149     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17150     return false;
17151   }
17152 
17153   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17154     FunctionDecl *FD;
17155     CallExpr *CE;
17156 
17157   public:
17158     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17159       : FD(FD), CE(CE) { }
17160 
17161     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17162       if (!FD) {
17163         S.Diag(Loc, diag::err_call_incomplete_return)
17164           << T << CE->getSourceRange();
17165         return;
17166       }
17167 
17168       S.Diag(Loc, diag::err_call_function_incomplete_return)
17169         << CE->getSourceRange() << FD->getDeclName() << T;
17170       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17171           << FD->getDeclName();
17172     }
17173   } Diagnoser(FD, CE);
17174 
17175   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17176     return true;
17177 
17178   return false;
17179 }
17180 
17181 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17182 // will prevent this condition from triggering, which is what we want.
17183 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17184   SourceLocation Loc;
17185 
17186   unsigned diagnostic = diag::warn_condition_is_assignment;
17187   bool IsOrAssign = false;
17188 
17189   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17190     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17191       return;
17192 
17193     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17194 
17195     // Greylist some idioms by putting them into a warning subcategory.
17196     if (ObjCMessageExpr *ME
17197           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17198       Selector Sel = ME->getSelector();
17199 
17200       // self = [<foo> init...]
17201       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17202         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17203 
17204       // <foo> = [<bar> nextObject]
17205       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17206         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17207     }
17208 
17209     Loc = Op->getOperatorLoc();
17210   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17211     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17212       return;
17213 
17214     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17215     Loc = Op->getOperatorLoc();
17216   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17217     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17218   else {
17219     // Not an assignment.
17220     return;
17221   }
17222 
17223   Diag(Loc, diagnostic) << E->getSourceRange();
17224 
17225   SourceLocation Open = E->getBeginLoc();
17226   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17227   Diag(Loc, diag::note_condition_assign_silence)
17228         << FixItHint::CreateInsertion(Open, "(")
17229         << FixItHint::CreateInsertion(Close, ")");
17230 
17231   if (IsOrAssign)
17232     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17233       << FixItHint::CreateReplacement(Loc, "!=");
17234   else
17235     Diag(Loc, diag::note_condition_assign_to_comparison)
17236       << FixItHint::CreateReplacement(Loc, "==");
17237 }
17238 
17239 /// Redundant parentheses over an equality comparison can indicate
17240 /// that the user intended an assignment used as condition.
17241 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17242   // Don't warn if the parens came from a macro.
17243   SourceLocation parenLoc = ParenE->getBeginLoc();
17244   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17245     return;
17246   // Don't warn for dependent expressions.
17247   if (ParenE->isTypeDependent())
17248     return;
17249 
17250   Expr *E = ParenE->IgnoreParens();
17251 
17252   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17253     if (opE->getOpcode() == BO_EQ &&
17254         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17255                                                            == Expr::MLV_Valid) {
17256       SourceLocation Loc = opE->getOperatorLoc();
17257 
17258       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17259       SourceRange ParenERange = ParenE->getSourceRange();
17260       Diag(Loc, diag::note_equality_comparison_silence)
17261         << FixItHint::CreateRemoval(ParenERange.getBegin())
17262         << FixItHint::CreateRemoval(ParenERange.getEnd());
17263       Diag(Loc, diag::note_equality_comparison_to_assign)
17264         << FixItHint::CreateReplacement(Loc, "=");
17265     }
17266 }
17267 
17268 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17269                                        bool IsConstexpr) {
17270   DiagnoseAssignmentAsCondition(E);
17271   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17272     DiagnoseEqualityWithExtraParens(parenE);
17273 
17274   ExprResult result = CheckPlaceholderExpr(E);
17275   if (result.isInvalid()) return ExprError();
17276   E = result.get();
17277 
17278   if (!E->isTypeDependent()) {
17279     if (getLangOpts().CPlusPlus)
17280       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17281 
17282     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17283     if (ERes.isInvalid())
17284       return ExprError();
17285     E = ERes.get();
17286 
17287     QualType T = E->getType();
17288     if (!T->isScalarType()) { // C99 6.8.4.1p1
17289       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17290         << T << E->getSourceRange();
17291       return ExprError();
17292     }
17293     CheckBoolLikeConversion(E, Loc);
17294   }
17295 
17296   return E;
17297 }
17298 
17299 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17300                                            Expr *SubExpr, ConditionKind CK) {
17301   // Empty conditions are valid in for-statements.
17302   if (!SubExpr)
17303     return ConditionResult();
17304 
17305   ExprResult Cond;
17306   switch (CK) {
17307   case ConditionKind::Boolean:
17308     Cond = CheckBooleanCondition(Loc, SubExpr);
17309     break;
17310 
17311   case ConditionKind::ConstexprIf:
17312     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17313     break;
17314 
17315   case ConditionKind::Switch:
17316     Cond = CheckSwitchCondition(Loc, SubExpr);
17317     break;
17318   }
17319   if (Cond.isInvalid())
17320     return ConditionError();
17321 
17322   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17323   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17324   if (!FullExpr.get())
17325     return ConditionError();
17326 
17327   return ConditionResult(*this, nullptr, FullExpr,
17328                          CK == ConditionKind::ConstexprIf);
17329 }
17330 
17331 namespace {
17332   /// A visitor for rebuilding a call to an __unknown_any expression
17333   /// to have an appropriate type.
17334   struct RebuildUnknownAnyFunction
17335     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17336 
17337     Sema &S;
17338 
17339     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17340 
17341     ExprResult VisitStmt(Stmt *S) {
17342       llvm_unreachable("unexpected statement!");
17343     }
17344 
17345     ExprResult VisitExpr(Expr *E) {
17346       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17347         << E->getSourceRange();
17348       return ExprError();
17349     }
17350 
17351     /// Rebuild an expression which simply semantically wraps another
17352     /// expression which it shares the type and value kind of.
17353     template <class T> ExprResult rebuildSugarExpr(T *E) {
17354       ExprResult SubResult = Visit(E->getSubExpr());
17355       if (SubResult.isInvalid()) return ExprError();
17356 
17357       Expr *SubExpr = SubResult.get();
17358       E->setSubExpr(SubExpr);
17359       E->setType(SubExpr->getType());
17360       E->setValueKind(SubExpr->getValueKind());
17361       assert(E->getObjectKind() == OK_Ordinary);
17362       return E;
17363     }
17364 
17365     ExprResult VisitParenExpr(ParenExpr *E) {
17366       return rebuildSugarExpr(E);
17367     }
17368 
17369     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17370       return rebuildSugarExpr(E);
17371     }
17372 
17373     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17374       ExprResult SubResult = Visit(E->getSubExpr());
17375       if (SubResult.isInvalid()) return ExprError();
17376 
17377       Expr *SubExpr = SubResult.get();
17378       E->setSubExpr(SubExpr);
17379       E->setType(S.Context.getPointerType(SubExpr->getType()));
17380       assert(E->getValueKind() == VK_RValue);
17381       assert(E->getObjectKind() == OK_Ordinary);
17382       return E;
17383     }
17384 
17385     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17386       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17387 
17388       E->setType(VD->getType());
17389 
17390       assert(E->getValueKind() == VK_RValue);
17391       if (S.getLangOpts().CPlusPlus &&
17392           !(isa<CXXMethodDecl>(VD) &&
17393             cast<CXXMethodDecl>(VD)->isInstance()))
17394         E->setValueKind(VK_LValue);
17395 
17396       return E;
17397     }
17398 
17399     ExprResult VisitMemberExpr(MemberExpr *E) {
17400       return resolveDecl(E, E->getMemberDecl());
17401     }
17402 
17403     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17404       return resolveDecl(E, E->getDecl());
17405     }
17406   };
17407 }
17408 
17409 /// Given a function expression of unknown-any type, try to rebuild it
17410 /// to have a function type.
17411 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17412   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17413   if (Result.isInvalid()) return ExprError();
17414   return S.DefaultFunctionArrayConversion(Result.get());
17415 }
17416 
17417 namespace {
17418   /// A visitor for rebuilding an expression of type __unknown_anytype
17419   /// into one which resolves the type directly on the referring
17420   /// expression.  Strict preservation of the original source
17421   /// structure is not a goal.
17422   struct RebuildUnknownAnyExpr
17423     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17424 
17425     Sema &S;
17426 
17427     /// The current destination type.
17428     QualType DestType;
17429 
17430     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17431       : S(S), DestType(CastType) {}
17432 
17433     ExprResult VisitStmt(Stmt *S) {
17434       llvm_unreachable("unexpected statement!");
17435     }
17436 
17437     ExprResult VisitExpr(Expr *E) {
17438       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17439         << E->getSourceRange();
17440       return ExprError();
17441     }
17442 
17443     ExprResult VisitCallExpr(CallExpr *E);
17444     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17445 
17446     /// Rebuild an expression which simply semantically wraps another
17447     /// expression which it shares the type and value kind of.
17448     template <class T> ExprResult rebuildSugarExpr(T *E) {
17449       ExprResult SubResult = Visit(E->getSubExpr());
17450       if (SubResult.isInvalid()) return ExprError();
17451       Expr *SubExpr = SubResult.get();
17452       E->setSubExpr(SubExpr);
17453       E->setType(SubExpr->getType());
17454       E->setValueKind(SubExpr->getValueKind());
17455       assert(E->getObjectKind() == OK_Ordinary);
17456       return E;
17457     }
17458 
17459     ExprResult VisitParenExpr(ParenExpr *E) {
17460       return rebuildSugarExpr(E);
17461     }
17462 
17463     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17464       return rebuildSugarExpr(E);
17465     }
17466 
17467     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17468       const PointerType *Ptr = DestType->getAs<PointerType>();
17469       if (!Ptr) {
17470         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17471           << E->getSourceRange();
17472         return ExprError();
17473       }
17474 
17475       if (isa<CallExpr>(E->getSubExpr())) {
17476         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17477           << E->getSourceRange();
17478         return ExprError();
17479       }
17480 
17481       assert(E->getValueKind() == VK_RValue);
17482       assert(E->getObjectKind() == OK_Ordinary);
17483       E->setType(DestType);
17484 
17485       // Build the sub-expression as if it were an object of the pointee type.
17486       DestType = Ptr->getPointeeType();
17487       ExprResult SubResult = Visit(E->getSubExpr());
17488       if (SubResult.isInvalid()) return ExprError();
17489       E->setSubExpr(SubResult.get());
17490       return E;
17491     }
17492 
17493     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17494 
17495     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17496 
17497     ExprResult VisitMemberExpr(MemberExpr *E) {
17498       return resolveDecl(E, E->getMemberDecl());
17499     }
17500 
17501     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17502       return resolveDecl(E, E->getDecl());
17503     }
17504   };
17505 }
17506 
17507 /// Rebuilds a call expression which yielded __unknown_anytype.
17508 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17509   Expr *CalleeExpr = E->getCallee();
17510 
17511   enum FnKind {
17512     FK_MemberFunction,
17513     FK_FunctionPointer,
17514     FK_BlockPointer
17515   };
17516 
17517   FnKind Kind;
17518   QualType CalleeType = CalleeExpr->getType();
17519   if (CalleeType == S.Context.BoundMemberTy) {
17520     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17521     Kind = FK_MemberFunction;
17522     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17523   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17524     CalleeType = Ptr->getPointeeType();
17525     Kind = FK_FunctionPointer;
17526   } else {
17527     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17528     Kind = FK_BlockPointer;
17529   }
17530   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17531 
17532   // Verify that this is a legal result type of a function.
17533   if (DestType->isArrayType() || DestType->isFunctionType()) {
17534     unsigned diagID = diag::err_func_returning_array_function;
17535     if (Kind == FK_BlockPointer)
17536       diagID = diag::err_block_returning_array_function;
17537 
17538     S.Diag(E->getExprLoc(), diagID)
17539       << DestType->isFunctionType() << DestType;
17540     return ExprError();
17541   }
17542 
17543   // Otherwise, go ahead and set DestType as the call's result.
17544   E->setType(DestType.getNonLValueExprType(S.Context));
17545   E->setValueKind(Expr::getValueKindForType(DestType));
17546   assert(E->getObjectKind() == OK_Ordinary);
17547 
17548   // Rebuild the function type, replacing the result type with DestType.
17549   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17550   if (Proto) {
17551     // __unknown_anytype(...) is a special case used by the debugger when
17552     // it has no idea what a function's signature is.
17553     //
17554     // We want to build this call essentially under the K&R
17555     // unprototyped rules, but making a FunctionNoProtoType in C++
17556     // would foul up all sorts of assumptions.  However, we cannot
17557     // simply pass all arguments as variadic arguments, nor can we
17558     // portably just call the function under a non-variadic type; see
17559     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17560     // However, it turns out that in practice it is generally safe to
17561     // call a function declared as "A foo(B,C,D);" under the prototype
17562     // "A foo(B,C,D,...);".  The only known exception is with the
17563     // Windows ABI, where any variadic function is implicitly cdecl
17564     // regardless of its normal CC.  Therefore we change the parameter
17565     // types to match the types of the arguments.
17566     //
17567     // This is a hack, but it is far superior to moving the
17568     // corresponding target-specific code from IR-gen to Sema/AST.
17569 
17570     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17571     SmallVector<QualType, 8> ArgTypes;
17572     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17573       ArgTypes.reserve(E->getNumArgs());
17574       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17575         Expr *Arg = E->getArg(i);
17576         QualType ArgType = Arg->getType();
17577         if (E->isLValue()) {
17578           ArgType = S.Context.getLValueReferenceType(ArgType);
17579         } else if (E->isXValue()) {
17580           ArgType = S.Context.getRValueReferenceType(ArgType);
17581         }
17582         ArgTypes.push_back(ArgType);
17583       }
17584       ParamTypes = ArgTypes;
17585     }
17586     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17587                                          Proto->getExtProtoInfo());
17588   } else {
17589     DestType = S.Context.getFunctionNoProtoType(DestType,
17590                                                 FnType->getExtInfo());
17591   }
17592 
17593   // Rebuild the appropriate pointer-to-function type.
17594   switch (Kind) {
17595   case FK_MemberFunction:
17596     // Nothing to do.
17597     break;
17598 
17599   case FK_FunctionPointer:
17600     DestType = S.Context.getPointerType(DestType);
17601     break;
17602 
17603   case FK_BlockPointer:
17604     DestType = S.Context.getBlockPointerType(DestType);
17605     break;
17606   }
17607 
17608   // Finally, we can recurse.
17609   ExprResult CalleeResult = Visit(CalleeExpr);
17610   if (!CalleeResult.isUsable()) return ExprError();
17611   E->setCallee(CalleeResult.get());
17612 
17613   // Bind a temporary if necessary.
17614   return S.MaybeBindToTemporary(E);
17615 }
17616 
17617 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17618   // Verify that this is a legal result type of a call.
17619   if (DestType->isArrayType() || DestType->isFunctionType()) {
17620     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17621       << DestType->isFunctionType() << DestType;
17622     return ExprError();
17623   }
17624 
17625   // Rewrite the method result type if available.
17626   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17627     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17628     Method->setReturnType(DestType);
17629   }
17630 
17631   // Change the type of the message.
17632   E->setType(DestType.getNonReferenceType());
17633   E->setValueKind(Expr::getValueKindForType(DestType));
17634 
17635   return S.MaybeBindToTemporary(E);
17636 }
17637 
17638 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17639   // The only case we should ever see here is a function-to-pointer decay.
17640   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17641     assert(E->getValueKind() == VK_RValue);
17642     assert(E->getObjectKind() == OK_Ordinary);
17643 
17644     E->setType(DestType);
17645 
17646     // Rebuild the sub-expression as the pointee (function) type.
17647     DestType = DestType->castAs<PointerType>()->getPointeeType();
17648 
17649     ExprResult Result = Visit(E->getSubExpr());
17650     if (!Result.isUsable()) return ExprError();
17651 
17652     E->setSubExpr(Result.get());
17653     return E;
17654   } else if (E->getCastKind() == CK_LValueToRValue) {
17655     assert(E->getValueKind() == VK_RValue);
17656     assert(E->getObjectKind() == OK_Ordinary);
17657 
17658     assert(isa<BlockPointerType>(E->getType()));
17659 
17660     E->setType(DestType);
17661 
17662     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17663     DestType = S.Context.getLValueReferenceType(DestType);
17664 
17665     ExprResult Result = Visit(E->getSubExpr());
17666     if (!Result.isUsable()) return ExprError();
17667 
17668     E->setSubExpr(Result.get());
17669     return E;
17670   } else {
17671     llvm_unreachable("Unhandled cast type!");
17672   }
17673 }
17674 
17675 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17676   ExprValueKind ValueKind = VK_LValue;
17677   QualType Type = DestType;
17678 
17679   // We know how to make this work for certain kinds of decls:
17680 
17681   //  - functions
17682   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17683     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17684       DestType = Ptr->getPointeeType();
17685       ExprResult Result = resolveDecl(E, VD);
17686       if (Result.isInvalid()) return ExprError();
17687       return S.ImpCastExprToType(Result.get(), Type,
17688                                  CK_FunctionToPointerDecay, VK_RValue);
17689     }
17690 
17691     if (!Type->isFunctionType()) {
17692       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17693         << VD << E->getSourceRange();
17694       return ExprError();
17695     }
17696     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17697       // We must match the FunctionDecl's type to the hack introduced in
17698       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17699       // type. See the lengthy commentary in that routine.
17700       QualType FDT = FD->getType();
17701       const FunctionType *FnType = FDT->castAs<FunctionType>();
17702       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17703       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17704       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17705         SourceLocation Loc = FD->getLocation();
17706         FunctionDecl *NewFD = FunctionDecl::Create(
17707             S.Context, FD->getDeclContext(), Loc, Loc,
17708             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17709             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17710             /*ConstexprKind*/ CSK_unspecified);
17711 
17712         if (FD->getQualifier())
17713           NewFD->setQualifierInfo(FD->getQualifierLoc());
17714 
17715         SmallVector<ParmVarDecl*, 16> Params;
17716         for (const auto &AI : FT->param_types()) {
17717           ParmVarDecl *Param =
17718             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17719           Param->setScopeInfo(0, Params.size());
17720           Params.push_back(Param);
17721         }
17722         NewFD->setParams(Params);
17723         DRE->setDecl(NewFD);
17724         VD = DRE->getDecl();
17725       }
17726     }
17727 
17728     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17729       if (MD->isInstance()) {
17730         ValueKind = VK_RValue;
17731         Type = S.Context.BoundMemberTy;
17732       }
17733 
17734     // Function references aren't l-values in C.
17735     if (!S.getLangOpts().CPlusPlus)
17736       ValueKind = VK_RValue;
17737 
17738   //  - variables
17739   } else if (isa<VarDecl>(VD)) {
17740     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17741       Type = RefTy->getPointeeType();
17742     } else if (Type->isFunctionType()) {
17743       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17744         << VD << E->getSourceRange();
17745       return ExprError();
17746     }
17747 
17748   //  - nothing else
17749   } else {
17750     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17751       << VD << E->getSourceRange();
17752     return ExprError();
17753   }
17754 
17755   // Modifying the declaration like this is friendly to IR-gen but
17756   // also really dangerous.
17757   VD->setType(DestType);
17758   E->setType(Type);
17759   E->setValueKind(ValueKind);
17760   return E;
17761 }
17762 
17763 /// Check a cast of an unknown-any type.  We intentionally only
17764 /// trigger this for C-style casts.
17765 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17766                                      Expr *CastExpr, CastKind &CastKind,
17767                                      ExprValueKind &VK, CXXCastPath &Path) {
17768   // The type we're casting to must be either void or complete.
17769   if (!CastType->isVoidType() &&
17770       RequireCompleteType(TypeRange.getBegin(), CastType,
17771                           diag::err_typecheck_cast_to_incomplete))
17772     return ExprError();
17773 
17774   // Rewrite the casted expression from scratch.
17775   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17776   if (!result.isUsable()) return ExprError();
17777 
17778   CastExpr = result.get();
17779   VK = CastExpr->getValueKind();
17780   CastKind = CK_NoOp;
17781 
17782   return CastExpr;
17783 }
17784 
17785 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17786   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17787 }
17788 
17789 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17790                                     Expr *arg, QualType &paramType) {
17791   // If the syntactic form of the argument is not an explicit cast of
17792   // any sort, just do default argument promotion.
17793   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17794   if (!castArg) {
17795     ExprResult result = DefaultArgumentPromotion(arg);
17796     if (result.isInvalid()) return ExprError();
17797     paramType = result.get()->getType();
17798     return result;
17799   }
17800 
17801   // Otherwise, use the type that was written in the explicit cast.
17802   assert(!arg->hasPlaceholderType());
17803   paramType = castArg->getTypeAsWritten();
17804 
17805   // Copy-initialize a parameter of that type.
17806   InitializedEntity entity =
17807     InitializedEntity::InitializeParameter(Context, paramType,
17808                                            /*consumed*/ false);
17809   return PerformCopyInitialization(entity, callLoc, arg);
17810 }
17811 
17812 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17813   Expr *orig = E;
17814   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17815   while (true) {
17816     E = E->IgnoreParenImpCasts();
17817     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17818       E = call->getCallee();
17819       diagID = diag::err_uncasted_call_of_unknown_any;
17820     } else {
17821       break;
17822     }
17823   }
17824 
17825   SourceLocation loc;
17826   NamedDecl *d;
17827   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17828     loc = ref->getLocation();
17829     d = ref->getDecl();
17830   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17831     loc = mem->getMemberLoc();
17832     d = mem->getMemberDecl();
17833   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17834     diagID = diag::err_uncasted_call_of_unknown_any;
17835     loc = msg->getSelectorStartLoc();
17836     d = msg->getMethodDecl();
17837     if (!d) {
17838       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17839         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17840         << orig->getSourceRange();
17841       return ExprError();
17842     }
17843   } else {
17844     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17845       << E->getSourceRange();
17846     return ExprError();
17847   }
17848 
17849   S.Diag(loc, diagID) << d << orig->getSourceRange();
17850 
17851   // Never recoverable.
17852   return ExprError();
17853 }
17854 
17855 /// Check for operands with placeholder types and complain if found.
17856 /// Returns ExprError() if there was an error and no recovery was possible.
17857 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17858   if (!getLangOpts().CPlusPlus) {
17859     // C cannot handle TypoExpr nodes on either side of a binop because it
17860     // doesn't handle dependent types properly, so make sure any TypoExprs have
17861     // been dealt with before checking the operands.
17862     ExprResult Result = CorrectDelayedTyposInExpr(E);
17863     if (!Result.isUsable()) return ExprError();
17864     E = Result.get();
17865   }
17866 
17867   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17868   if (!placeholderType) return E;
17869 
17870   switch (placeholderType->getKind()) {
17871 
17872   // Overloaded expressions.
17873   case BuiltinType::Overload: {
17874     // Try to resolve a single function template specialization.
17875     // This is obligatory.
17876     ExprResult Result = E;
17877     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17878       return Result;
17879 
17880     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17881     // leaves Result unchanged on failure.
17882     Result = E;
17883     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17884       return Result;
17885 
17886     // If that failed, try to recover with a call.
17887     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17888                          /*complain*/ true);
17889     return Result;
17890   }
17891 
17892   // Bound member functions.
17893   case BuiltinType::BoundMember: {
17894     ExprResult result = E;
17895     const Expr *BME = E->IgnoreParens();
17896     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17897     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17898     if (isa<CXXPseudoDestructorExpr>(BME)) {
17899       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17900     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17901       if (ME->getMemberNameInfo().getName().getNameKind() ==
17902           DeclarationName::CXXDestructorName)
17903         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17904     }
17905     tryToRecoverWithCall(result, PD,
17906                          /*complain*/ true);
17907     return result;
17908   }
17909 
17910   // ARC unbridged casts.
17911   case BuiltinType::ARCUnbridgedCast: {
17912     Expr *realCast = stripARCUnbridgedCast(E);
17913     diagnoseARCUnbridgedCast(realCast);
17914     return realCast;
17915   }
17916 
17917   // Expressions of unknown type.
17918   case BuiltinType::UnknownAny:
17919     return diagnoseUnknownAnyExpr(*this, E);
17920 
17921   // Pseudo-objects.
17922   case BuiltinType::PseudoObject:
17923     return checkPseudoObjectRValue(E);
17924 
17925   case BuiltinType::BuiltinFn: {
17926     // Accept __noop without parens by implicitly converting it to a call expr.
17927     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17928     if (DRE) {
17929       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17930       if (FD->getBuiltinID() == Builtin::BI__noop) {
17931         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17932                               CK_BuiltinFnToFnPtr)
17933                 .get();
17934         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17935                                 VK_RValue, SourceLocation());
17936       }
17937     }
17938 
17939     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17940     return ExprError();
17941   }
17942 
17943   // Expressions of unknown type.
17944   case BuiltinType::OMPArraySection:
17945     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17946     return ExprError();
17947 
17948   // Everything else should be impossible.
17949 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17950   case BuiltinType::Id:
17951 #include "clang/Basic/OpenCLImageTypes.def"
17952 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17953   case BuiltinType::Id:
17954 #include "clang/Basic/OpenCLExtensionTypes.def"
17955 #define SVE_TYPE(Name, Id, SingletonId) \
17956   case BuiltinType::Id:
17957 #include "clang/Basic/AArch64SVEACLETypes.def"
17958 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17959 #define PLACEHOLDER_TYPE(Id, SingletonId)
17960 #include "clang/AST/BuiltinTypes.def"
17961     break;
17962   }
17963 
17964   llvm_unreachable("invalid placeholder type!");
17965 }
17966 
17967 bool Sema::CheckCaseExpression(Expr *E) {
17968   if (E->isTypeDependent())
17969     return true;
17970   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17971     return E->getType()->isIntegralOrEnumerationType();
17972   return false;
17973 }
17974 
17975 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17976 ExprResult
17977 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17978   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17979          "Unknown Objective-C Boolean value!");
17980   QualType BoolT = Context.ObjCBuiltinBoolTy;
17981   if (!Context.getBOOLDecl()) {
17982     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17983                         Sema::LookupOrdinaryName);
17984     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17985       NamedDecl *ND = Result.getFoundDecl();
17986       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17987         Context.setBOOLDecl(TD);
17988     }
17989   }
17990   if (Context.getBOOLDecl())
17991     BoolT = Context.getBOOLType();
17992   return new (Context)
17993       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17994 }
17995 
17996 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17997     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17998     SourceLocation RParen) {
17999 
18000   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18001 
18002   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18003     return Spec.getPlatform() == Platform;
18004   });
18005 
18006   VersionTuple Version;
18007   if (Spec != AvailSpecs.end())
18008     Version = Spec->getVersion();
18009 
18010   // The use of `@available` in the enclosing function should be analyzed to
18011   // warn when it's used inappropriately (i.e. not if(@available)).
18012   if (getCurFunctionOrMethodDecl())
18013     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18014   else if (getCurBlock() || getCurLambda())
18015     getCurFunction()->HasPotentialAvailabilityViolations = true;
18016 
18017   return new (Context)
18018       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18019 }
18020