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);
7624 }
7625 
7626 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7627 /// expression, either using a built-in or overloaded operator,
7628 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7629 /// expression.
7630 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7631                                    Expr **RHSExprs) {
7632   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7633   E = E->IgnoreImpCasts();
7634   E = E->IgnoreConversionOperator();
7635   E = E->IgnoreImpCasts();
7636   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7637     E = MTE->GetTemporaryExpr();
7638     E = E->IgnoreImpCasts();
7639   }
7640 
7641   // Built-in binary operator.
7642   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7643     if (IsArithmeticOp(OP->getOpcode())) {
7644       *Opcode = OP->getOpcode();
7645       *RHSExprs = OP->getRHS();
7646       return true;
7647     }
7648   }
7649 
7650   // Overloaded operator.
7651   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7652     if (Call->getNumArgs() != 2)
7653       return false;
7654 
7655     // Make sure this is really a binary operator that is safe to pass into
7656     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7657     OverloadedOperatorKind OO = Call->getOperator();
7658     if (OO < OO_Plus || OO > OO_Arrow ||
7659         OO == OO_PlusPlus || OO == OO_MinusMinus)
7660       return false;
7661 
7662     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7663     if (IsArithmeticOp(OpKind)) {
7664       *Opcode = OpKind;
7665       *RHSExprs = Call->getArg(1);
7666       return true;
7667     }
7668   }
7669 
7670   return false;
7671 }
7672 
7673 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7674 /// or is a logical expression such as (x==y) which has int type, but is
7675 /// commonly interpreted as boolean.
7676 static bool ExprLooksBoolean(Expr *E) {
7677   E = E->IgnoreParenImpCasts();
7678 
7679   if (E->getType()->isBooleanType())
7680     return true;
7681   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7682     return OP->isComparisonOp() || OP->isLogicalOp();
7683   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7684     return OP->getOpcode() == UO_LNot;
7685   if (E->getType()->isPointerType())
7686     return true;
7687   // FIXME: What about overloaded operator calls returning "unspecified boolean
7688   // type"s (commonly pointer-to-members)?
7689 
7690   return false;
7691 }
7692 
7693 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7694 /// and binary operator are mixed in a way that suggests the programmer assumed
7695 /// the conditional operator has higher precedence, for example:
7696 /// "int x = a + someBinaryCondition ? 1 : 2".
7697 static void DiagnoseConditionalPrecedence(Sema &Self,
7698                                           SourceLocation OpLoc,
7699                                           Expr *Condition,
7700                                           Expr *LHSExpr,
7701                                           Expr *RHSExpr) {
7702   BinaryOperatorKind CondOpcode;
7703   Expr *CondRHS;
7704 
7705   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7706     return;
7707   if (!ExprLooksBoolean(CondRHS))
7708     return;
7709 
7710   // The condition is an arithmetic binary expression, with a right-
7711   // hand side that looks boolean, so warn.
7712 
7713   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7714       << Condition->getSourceRange()
7715       << BinaryOperator::getOpcodeStr(CondOpcode);
7716 
7717   SuggestParentheses(
7718       Self, OpLoc,
7719       Self.PDiag(diag::note_precedence_silence)
7720           << BinaryOperator::getOpcodeStr(CondOpcode),
7721       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7722 
7723   SuggestParentheses(Self, OpLoc,
7724                      Self.PDiag(diag::note_precedence_conditional_first),
7725                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7726 }
7727 
7728 /// Compute the nullability of a conditional expression.
7729 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7730                                               QualType LHSTy, QualType RHSTy,
7731                                               ASTContext &Ctx) {
7732   if (!ResTy->isAnyPointerType())
7733     return ResTy;
7734 
7735   auto GetNullability = [&Ctx](QualType Ty) {
7736     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7737     if (Kind)
7738       return *Kind;
7739     return NullabilityKind::Unspecified;
7740   };
7741 
7742   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7743   NullabilityKind MergedKind;
7744 
7745   // Compute nullability of a binary conditional expression.
7746   if (IsBin) {
7747     if (LHSKind == NullabilityKind::NonNull)
7748       MergedKind = NullabilityKind::NonNull;
7749     else
7750       MergedKind = RHSKind;
7751   // Compute nullability of a normal conditional expression.
7752   } else {
7753     if (LHSKind == NullabilityKind::Nullable ||
7754         RHSKind == NullabilityKind::Nullable)
7755       MergedKind = NullabilityKind::Nullable;
7756     else if (LHSKind == NullabilityKind::NonNull)
7757       MergedKind = RHSKind;
7758     else if (RHSKind == NullabilityKind::NonNull)
7759       MergedKind = LHSKind;
7760     else
7761       MergedKind = NullabilityKind::Unspecified;
7762   }
7763 
7764   // Return if ResTy already has the correct nullability.
7765   if (GetNullability(ResTy) == MergedKind)
7766     return ResTy;
7767 
7768   // Strip all nullability from ResTy.
7769   while (ResTy->getNullability(Ctx))
7770     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7771 
7772   // Create a new AttributedType with the new nullability kind.
7773   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7774   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7775 }
7776 
7777 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7778 /// in the case of a the GNU conditional expr extension.
7779 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7780                                     SourceLocation ColonLoc,
7781                                     Expr *CondExpr, Expr *LHSExpr,
7782                                     Expr *RHSExpr) {
7783   if (!getLangOpts().CPlusPlus) {
7784     // C cannot handle TypoExpr nodes in the condition because it
7785     // doesn't handle dependent types properly, so make sure any TypoExprs have
7786     // been dealt with before checking the operands.
7787     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7788     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7789     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7790 
7791     if (!CondResult.isUsable())
7792       return ExprError();
7793 
7794     if (LHSExpr) {
7795       if (!LHSResult.isUsable())
7796         return ExprError();
7797     }
7798 
7799     if (!RHSResult.isUsable())
7800       return ExprError();
7801 
7802     CondExpr = CondResult.get();
7803     LHSExpr = LHSResult.get();
7804     RHSExpr = RHSResult.get();
7805   }
7806 
7807   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7808   // was the condition.
7809   OpaqueValueExpr *opaqueValue = nullptr;
7810   Expr *commonExpr = nullptr;
7811   if (!LHSExpr) {
7812     commonExpr = CondExpr;
7813     // Lower out placeholder types first.  This is important so that we don't
7814     // try to capture a placeholder. This happens in few cases in C++; such
7815     // as Objective-C++'s dictionary subscripting syntax.
7816     if (commonExpr->hasPlaceholderType()) {
7817       ExprResult result = CheckPlaceholderExpr(commonExpr);
7818       if (!result.isUsable()) return ExprError();
7819       commonExpr = result.get();
7820     }
7821     // We usually want to apply unary conversions *before* saving, except
7822     // in the special case of a C++ l-value conditional.
7823     if (!(getLangOpts().CPlusPlus
7824           && !commonExpr->isTypeDependent()
7825           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7826           && commonExpr->isGLValue()
7827           && commonExpr->isOrdinaryOrBitFieldObject()
7828           && RHSExpr->isOrdinaryOrBitFieldObject()
7829           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7830       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7831       if (commonRes.isInvalid())
7832         return ExprError();
7833       commonExpr = commonRes.get();
7834     }
7835 
7836     // If the common expression is a class or array prvalue, materialize it
7837     // so that we can safely refer to it multiple times.
7838     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7839                                    commonExpr->getType()->isArrayType())) {
7840       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7841       if (MatExpr.isInvalid())
7842         return ExprError();
7843       commonExpr = MatExpr.get();
7844     }
7845 
7846     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7847                                                 commonExpr->getType(),
7848                                                 commonExpr->getValueKind(),
7849                                                 commonExpr->getObjectKind(),
7850                                                 commonExpr);
7851     LHSExpr = CondExpr = opaqueValue;
7852   }
7853 
7854   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7855   ExprValueKind VK = VK_RValue;
7856   ExprObjectKind OK = OK_Ordinary;
7857   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7858   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7859                                              VK, OK, QuestionLoc);
7860   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7861       RHS.isInvalid())
7862     return ExprError();
7863 
7864   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7865                                 RHS.get());
7866 
7867   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7868 
7869   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7870                                          Context);
7871 
7872   if (!commonExpr)
7873     return new (Context)
7874         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7875                             RHS.get(), result, VK, OK);
7876 
7877   return new (Context) BinaryConditionalOperator(
7878       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7879       ColonLoc, result, VK, OK);
7880 }
7881 
7882 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7883 // being closely modeled after the C99 spec:-). The odd characteristic of this
7884 // routine is it effectively iqnores the qualifiers on the top level pointee.
7885 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7886 // FIXME: add a couple examples in this comment.
7887 static Sema::AssignConvertType
7888 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7889   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7890   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7891 
7892   // get the "pointed to" type (ignoring qualifiers at the top level)
7893   const Type *lhptee, *rhptee;
7894   Qualifiers lhq, rhq;
7895   std::tie(lhptee, lhq) =
7896       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7897   std::tie(rhptee, rhq) =
7898       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7899 
7900   Sema::AssignConvertType ConvTy = Sema::Compatible;
7901 
7902   // C99 6.5.16.1p1: This following citation is common to constraints
7903   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7904   // qualifiers of the type *pointed to* by the right;
7905 
7906   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7907   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7908       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7909     // Ignore lifetime for further calculation.
7910     lhq.removeObjCLifetime();
7911     rhq.removeObjCLifetime();
7912   }
7913 
7914   if (!lhq.compatiblyIncludes(rhq)) {
7915     // Treat address-space mismatches as fatal.
7916     if (!lhq.isAddressSpaceSupersetOf(rhq))
7917       return Sema::IncompatiblePointerDiscardsQualifiers;
7918 
7919     // It's okay to add or remove GC or lifetime qualifiers when converting to
7920     // and from void*.
7921     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7922                         .compatiblyIncludes(
7923                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7924              && (lhptee->isVoidType() || rhptee->isVoidType()))
7925       ; // keep old
7926 
7927     // Treat lifetime mismatches as fatal.
7928     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7929       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7930 
7931     // For GCC/MS compatibility, other qualifier mismatches are treated
7932     // as still compatible in C.
7933     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7934   }
7935 
7936   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7937   // incomplete type and the other is a pointer to a qualified or unqualified
7938   // version of void...
7939   if (lhptee->isVoidType()) {
7940     if (rhptee->isIncompleteOrObjectType())
7941       return ConvTy;
7942 
7943     // As an extension, we allow cast to/from void* to function pointer.
7944     assert(rhptee->isFunctionType());
7945     return Sema::FunctionVoidPointer;
7946   }
7947 
7948   if (rhptee->isVoidType()) {
7949     if (lhptee->isIncompleteOrObjectType())
7950       return ConvTy;
7951 
7952     // As an extension, we allow cast to/from void* to function pointer.
7953     assert(lhptee->isFunctionType());
7954     return Sema::FunctionVoidPointer;
7955   }
7956 
7957   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7958   // unqualified versions of compatible types, ...
7959   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7960   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7961     // Check if the pointee types are compatible ignoring the sign.
7962     // We explicitly check for char so that we catch "char" vs
7963     // "unsigned char" on systems where "char" is unsigned.
7964     if (lhptee->isCharType())
7965       ltrans = S.Context.UnsignedCharTy;
7966     else if (lhptee->hasSignedIntegerRepresentation())
7967       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7968 
7969     if (rhptee->isCharType())
7970       rtrans = S.Context.UnsignedCharTy;
7971     else if (rhptee->hasSignedIntegerRepresentation())
7972       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7973 
7974     if (ltrans == rtrans) {
7975       // Types are compatible ignoring the sign. Qualifier incompatibility
7976       // takes priority over sign incompatibility because the sign
7977       // warning can be disabled.
7978       if (ConvTy != Sema::Compatible)
7979         return ConvTy;
7980 
7981       return Sema::IncompatiblePointerSign;
7982     }
7983 
7984     // If we are a multi-level pointer, it's possible that our issue is simply
7985     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7986     // the eventual target type is the same and the pointers have the same
7987     // level of indirection, this must be the issue.
7988     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7989       do {
7990         std::tie(lhptee, lhq) =
7991           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7992         std::tie(rhptee, rhq) =
7993           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7994 
7995         // Inconsistent address spaces at this point is invalid, even if the
7996         // address spaces would be compatible.
7997         // FIXME: This doesn't catch address space mismatches for pointers of
7998         // different nesting levels, like:
7999         //   __local int *** a;
8000         //   int ** b = a;
8001         // It's not clear how to actually determine when such pointers are
8002         // invalidly incompatible.
8003         if (lhq.getAddressSpace() != rhq.getAddressSpace())
8004           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8005 
8006       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8007 
8008       if (lhptee == rhptee)
8009         return Sema::IncompatibleNestedPointerQualifiers;
8010     }
8011 
8012     // General pointer incompatibility takes priority over qualifiers.
8013     return Sema::IncompatiblePointer;
8014   }
8015   if (!S.getLangOpts().CPlusPlus &&
8016       S.IsFunctionConversion(ltrans, rtrans, ltrans))
8017     return Sema::IncompatiblePointer;
8018   return ConvTy;
8019 }
8020 
8021 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8022 /// block pointer types are compatible or whether a block and normal pointer
8023 /// are compatible. It is more restrict than comparing two function pointer
8024 // types.
8025 static Sema::AssignConvertType
8026 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8027                                     QualType RHSType) {
8028   assert(LHSType.isCanonical() && "LHS not canonicalized!");
8029   assert(RHSType.isCanonical() && "RHS not canonicalized!");
8030 
8031   QualType lhptee, rhptee;
8032 
8033   // get the "pointed to" type (ignoring qualifiers at the top level)
8034   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8035   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8036 
8037   // In C++, the types have to match exactly.
8038   if (S.getLangOpts().CPlusPlus)
8039     return Sema::IncompatibleBlockPointer;
8040 
8041   Sema::AssignConvertType ConvTy = Sema::Compatible;
8042 
8043   // For blocks we enforce that qualifiers are identical.
8044   Qualifiers LQuals = lhptee.getLocalQualifiers();
8045   Qualifiers RQuals = rhptee.getLocalQualifiers();
8046   if (S.getLangOpts().OpenCL) {
8047     LQuals.removeAddressSpace();
8048     RQuals.removeAddressSpace();
8049   }
8050   if (LQuals != RQuals)
8051     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8052 
8053   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8054   // assignment.
8055   // The current behavior is similar to C++ lambdas. A block might be
8056   // assigned to a variable iff its return type and parameters are compatible
8057   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8058   // an assignment. Presumably it should behave in way that a function pointer
8059   // assignment does in C, so for each parameter and return type:
8060   //  * CVR and address space of LHS should be a superset of CVR and address
8061   //  space of RHS.
8062   //  * unqualified types should be compatible.
8063   if (S.getLangOpts().OpenCL) {
8064     if (!S.Context.typesAreBlockPointerCompatible(
8065             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8066             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8067       return Sema::IncompatibleBlockPointer;
8068   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8069     return Sema::IncompatibleBlockPointer;
8070 
8071   return ConvTy;
8072 }
8073 
8074 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8075 /// for assignment compatibility.
8076 static Sema::AssignConvertType
8077 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8078                                    QualType RHSType) {
8079   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8080   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8081 
8082   if (LHSType->isObjCBuiltinType()) {
8083     // Class is not compatible with ObjC object pointers.
8084     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8085         !RHSType->isObjCQualifiedClassType())
8086       return Sema::IncompatiblePointer;
8087     return Sema::Compatible;
8088   }
8089   if (RHSType->isObjCBuiltinType()) {
8090     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8091         !LHSType->isObjCQualifiedClassType())
8092       return Sema::IncompatiblePointer;
8093     return Sema::Compatible;
8094   }
8095   QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8096   QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8097 
8098   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8099       // make an exception for id<P>
8100       !LHSType->isObjCQualifiedIdType())
8101     return Sema::CompatiblePointerDiscardsQualifiers;
8102 
8103   if (S.Context.typesAreCompatible(LHSType, RHSType))
8104     return Sema::Compatible;
8105   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8106     return Sema::IncompatibleObjCQualifiedId;
8107   return Sema::IncompatiblePointer;
8108 }
8109 
8110 Sema::AssignConvertType
8111 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8112                                  QualType LHSType, QualType RHSType) {
8113   // Fake up an opaque expression.  We don't actually care about what
8114   // cast operations are required, so if CheckAssignmentConstraints
8115   // adds casts to this they'll be wasted, but fortunately that doesn't
8116   // usually happen on valid code.
8117   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8118   ExprResult RHSPtr = &RHSExpr;
8119   CastKind K;
8120 
8121   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8122 }
8123 
8124 /// This helper function returns true if QT is a vector type that has element
8125 /// type ElementType.
8126 static bool isVector(QualType QT, QualType ElementType) {
8127   if (const VectorType *VT = QT->getAs<VectorType>())
8128     return VT->getElementType() == ElementType;
8129   return false;
8130 }
8131 
8132 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8133 /// has code to accommodate several GCC extensions when type checking
8134 /// pointers. Here are some objectionable examples that GCC considers warnings:
8135 ///
8136 ///  int a, *pint;
8137 ///  short *pshort;
8138 ///  struct foo *pfoo;
8139 ///
8140 ///  pint = pshort; // warning: assignment from incompatible pointer type
8141 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8142 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8143 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8144 ///
8145 /// As a result, the code for dealing with pointers is more complex than the
8146 /// C99 spec dictates.
8147 ///
8148 /// Sets 'Kind' for any result kind except Incompatible.
8149 Sema::AssignConvertType
8150 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8151                                  CastKind &Kind, bool ConvertRHS) {
8152   QualType RHSType = RHS.get()->getType();
8153   QualType OrigLHSType = LHSType;
8154 
8155   // Get canonical types.  We're not formatting these types, just comparing
8156   // them.
8157   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8158   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8159 
8160   // Common case: no conversion required.
8161   if (LHSType == RHSType) {
8162     Kind = CK_NoOp;
8163     return Compatible;
8164   }
8165 
8166   // If we have an atomic type, try a non-atomic assignment, then just add an
8167   // atomic qualification step.
8168   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8169     Sema::AssignConvertType result =
8170       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8171     if (result != Compatible)
8172       return result;
8173     if (Kind != CK_NoOp && ConvertRHS)
8174       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8175     Kind = CK_NonAtomicToAtomic;
8176     return Compatible;
8177   }
8178 
8179   // If the left-hand side is a reference type, then we are in a
8180   // (rare!) case where we've allowed the use of references in C,
8181   // e.g., as a parameter type in a built-in function. In this case,
8182   // just make sure that the type referenced is compatible with the
8183   // right-hand side type. The caller is responsible for adjusting
8184   // LHSType so that the resulting expression does not have reference
8185   // type.
8186   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8187     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8188       Kind = CK_LValueBitCast;
8189       return Compatible;
8190     }
8191     return Incompatible;
8192   }
8193 
8194   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8195   // to the same ExtVector type.
8196   if (LHSType->isExtVectorType()) {
8197     if (RHSType->isExtVectorType())
8198       return Incompatible;
8199     if (RHSType->isArithmeticType()) {
8200       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8201       if (ConvertRHS)
8202         RHS = prepareVectorSplat(LHSType, RHS.get());
8203       Kind = CK_VectorSplat;
8204       return Compatible;
8205     }
8206   }
8207 
8208   // Conversions to or from vector type.
8209   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8210     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8211       // Allow assignments of an AltiVec vector type to an equivalent GCC
8212       // vector type and vice versa
8213       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8214         Kind = CK_BitCast;
8215         return Compatible;
8216       }
8217 
8218       // If we are allowing lax vector conversions, and LHS and RHS are both
8219       // vectors, the total size only needs to be the same. This is a bitcast;
8220       // no bits are changed but the result type is different.
8221       if (isLaxVectorConversion(RHSType, LHSType)) {
8222         Kind = CK_BitCast;
8223         return IncompatibleVectors;
8224       }
8225     }
8226 
8227     // When the RHS comes from another lax conversion (e.g. binops between
8228     // scalars and vectors) the result is canonicalized as a vector. When the
8229     // LHS is also a vector, the lax is allowed by the condition above. Handle
8230     // the case where LHS is a scalar.
8231     if (LHSType->isScalarType()) {
8232       const VectorType *VecType = RHSType->getAs<VectorType>();
8233       if (VecType && VecType->getNumElements() == 1 &&
8234           isLaxVectorConversion(RHSType, LHSType)) {
8235         ExprResult *VecExpr = &RHS;
8236         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8237         Kind = CK_BitCast;
8238         return Compatible;
8239       }
8240     }
8241 
8242     return Incompatible;
8243   }
8244 
8245   // Diagnose attempts to convert between __float128 and long double where
8246   // such conversions currently can't be handled.
8247   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8248     return Incompatible;
8249 
8250   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8251   // discards the imaginary part.
8252   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8253       !LHSType->getAs<ComplexType>())
8254     return Incompatible;
8255 
8256   // Arithmetic conversions.
8257   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8258       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8259     if (ConvertRHS)
8260       Kind = PrepareScalarCast(RHS, LHSType);
8261     return Compatible;
8262   }
8263 
8264   // Conversions to normal pointers.
8265   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8266     // U* -> T*
8267     if (isa<PointerType>(RHSType)) {
8268       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8269       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8270       if (AddrSpaceL != AddrSpaceR)
8271         Kind = CK_AddressSpaceConversion;
8272       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8273         Kind = CK_NoOp;
8274       else
8275         Kind = CK_BitCast;
8276       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8277     }
8278 
8279     // int -> T*
8280     if (RHSType->isIntegerType()) {
8281       Kind = CK_IntegralToPointer; // FIXME: null?
8282       return IntToPointer;
8283     }
8284 
8285     // C pointers are not compatible with ObjC object pointers,
8286     // with two exceptions:
8287     if (isa<ObjCObjectPointerType>(RHSType)) {
8288       //  - conversions to void*
8289       if (LHSPointer->getPointeeType()->isVoidType()) {
8290         Kind = CK_BitCast;
8291         return Compatible;
8292       }
8293 
8294       //  - conversions from 'Class' to the redefinition type
8295       if (RHSType->isObjCClassType() &&
8296           Context.hasSameType(LHSType,
8297                               Context.getObjCClassRedefinitionType())) {
8298         Kind = CK_BitCast;
8299         return Compatible;
8300       }
8301 
8302       Kind = CK_BitCast;
8303       return IncompatiblePointer;
8304     }
8305 
8306     // U^ -> void*
8307     if (RHSType->getAs<BlockPointerType>()) {
8308       if (LHSPointer->getPointeeType()->isVoidType()) {
8309         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8310         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8311                                 ->getPointeeType()
8312                                 .getAddressSpace();
8313         Kind =
8314             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8315         return Compatible;
8316       }
8317     }
8318 
8319     return Incompatible;
8320   }
8321 
8322   // Conversions to block pointers.
8323   if (isa<BlockPointerType>(LHSType)) {
8324     // U^ -> T^
8325     if (RHSType->isBlockPointerType()) {
8326       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8327                               ->getPointeeType()
8328                               .getAddressSpace();
8329       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8330                               ->getPointeeType()
8331                               .getAddressSpace();
8332       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8333       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8334     }
8335 
8336     // int or null -> T^
8337     if (RHSType->isIntegerType()) {
8338       Kind = CK_IntegralToPointer; // FIXME: null
8339       return IntToBlockPointer;
8340     }
8341 
8342     // id -> T^
8343     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8344       Kind = CK_AnyPointerToBlockPointerCast;
8345       return Compatible;
8346     }
8347 
8348     // void* -> T^
8349     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8350       if (RHSPT->getPointeeType()->isVoidType()) {
8351         Kind = CK_AnyPointerToBlockPointerCast;
8352         return Compatible;
8353       }
8354 
8355     return Incompatible;
8356   }
8357 
8358   // Conversions to Objective-C pointers.
8359   if (isa<ObjCObjectPointerType>(LHSType)) {
8360     // A* -> B*
8361     if (RHSType->isObjCObjectPointerType()) {
8362       Kind = CK_BitCast;
8363       Sema::AssignConvertType result =
8364         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8365       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8366           result == Compatible &&
8367           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8368         result = IncompatibleObjCWeakRef;
8369       return result;
8370     }
8371 
8372     // int or null -> A*
8373     if (RHSType->isIntegerType()) {
8374       Kind = CK_IntegralToPointer; // FIXME: null
8375       return IntToPointer;
8376     }
8377 
8378     // In general, C pointers are not compatible with ObjC object pointers,
8379     // with two exceptions:
8380     if (isa<PointerType>(RHSType)) {
8381       Kind = CK_CPointerToObjCPointerCast;
8382 
8383       //  - conversions from 'void*'
8384       if (RHSType->isVoidPointerType()) {
8385         return Compatible;
8386       }
8387 
8388       //  - conversions to 'Class' from its redefinition type
8389       if (LHSType->isObjCClassType() &&
8390           Context.hasSameType(RHSType,
8391                               Context.getObjCClassRedefinitionType())) {
8392         return Compatible;
8393       }
8394 
8395       return IncompatiblePointer;
8396     }
8397 
8398     // Only under strict condition T^ is compatible with an Objective-C pointer.
8399     if (RHSType->isBlockPointerType() &&
8400         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8401       if (ConvertRHS)
8402         maybeExtendBlockObject(RHS);
8403       Kind = CK_BlockPointerToObjCPointerCast;
8404       return Compatible;
8405     }
8406 
8407     return Incompatible;
8408   }
8409 
8410   // Conversions from pointers that are not covered by the above.
8411   if (isa<PointerType>(RHSType)) {
8412     // T* -> _Bool
8413     if (LHSType == Context.BoolTy) {
8414       Kind = CK_PointerToBoolean;
8415       return Compatible;
8416     }
8417 
8418     // T* -> int
8419     if (LHSType->isIntegerType()) {
8420       Kind = CK_PointerToIntegral;
8421       return PointerToInt;
8422     }
8423 
8424     return Incompatible;
8425   }
8426 
8427   // Conversions from Objective-C pointers that are not covered by the above.
8428   if (isa<ObjCObjectPointerType>(RHSType)) {
8429     // T* -> _Bool
8430     if (LHSType == Context.BoolTy) {
8431       Kind = CK_PointerToBoolean;
8432       return Compatible;
8433     }
8434 
8435     // T* -> int
8436     if (LHSType->isIntegerType()) {
8437       Kind = CK_PointerToIntegral;
8438       return PointerToInt;
8439     }
8440 
8441     return Incompatible;
8442   }
8443 
8444   // struct A -> struct B
8445   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8446     if (Context.typesAreCompatible(LHSType, RHSType)) {
8447       Kind = CK_NoOp;
8448       return Compatible;
8449     }
8450   }
8451 
8452   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8453     Kind = CK_IntToOCLSampler;
8454     return Compatible;
8455   }
8456 
8457   return Incompatible;
8458 }
8459 
8460 /// Constructs a transparent union from an expression that is
8461 /// used to initialize the transparent union.
8462 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8463                                       ExprResult &EResult, QualType UnionType,
8464                                       FieldDecl *Field) {
8465   // Build an initializer list that designates the appropriate member
8466   // of the transparent union.
8467   Expr *E = EResult.get();
8468   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8469                                                    E, SourceLocation());
8470   Initializer->setType(UnionType);
8471   Initializer->setInitializedFieldInUnion(Field);
8472 
8473   // Build a compound literal constructing a value of the transparent
8474   // union type from this initializer list.
8475   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8476   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8477                                         VK_RValue, Initializer, false);
8478 }
8479 
8480 Sema::AssignConvertType
8481 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8482                                                ExprResult &RHS) {
8483   QualType RHSType = RHS.get()->getType();
8484 
8485   // If the ArgType is a Union type, we want to handle a potential
8486   // transparent_union GCC extension.
8487   const RecordType *UT = ArgType->getAsUnionType();
8488   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8489     return Incompatible;
8490 
8491   // The field to initialize within the transparent union.
8492   RecordDecl *UD = UT->getDecl();
8493   FieldDecl *InitField = nullptr;
8494   // It's compatible if the expression matches any of the fields.
8495   for (auto *it : UD->fields()) {
8496     if (it->getType()->isPointerType()) {
8497       // If the transparent union contains a pointer type, we allow:
8498       // 1) void pointer
8499       // 2) null pointer constant
8500       if (RHSType->isPointerType())
8501         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8502           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8503           InitField = it;
8504           break;
8505         }
8506 
8507       if (RHS.get()->isNullPointerConstant(Context,
8508                                            Expr::NPC_ValueDependentIsNull)) {
8509         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8510                                 CK_NullToPointer);
8511         InitField = it;
8512         break;
8513       }
8514     }
8515 
8516     CastKind Kind;
8517     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8518           == Compatible) {
8519       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8520       InitField = it;
8521       break;
8522     }
8523   }
8524 
8525   if (!InitField)
8526     return Incompatible;
8527 
8528   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8529   return Compatible;
8530 }
8531 
8532 Sema::AssignConvertType
8533 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8534                                        bool Diagnose,
8535                                        bool DiagnoseCFAudited,
8536                                        bool ConvertRHS) {
8537   // We need to be able to tell the caller whether we diagnosed a problem, if
8538   // they ask us to issue diagnostics.
8539   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8540 
8541   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8542   // we can't avoid *all* modifications at the moment, so we need some somewhere
8543   // to put the updated value.
8544   ExprResult LocalRHS = CallerRHS;
8545   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8546 
8547   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8548     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8549       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8550           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8551         Diag(RHS.get()->getExprLoc(),
8552              diag::warn_noderef_to_dereferenceable_pointer)
8553             << RHS.get()->getSourceRange();
8554       }
8555     }
8556   }
8557 
8558   if (getLangOpts().CPlusPlus) {
8559     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8560       // C++ 5.17p3: If the left operand is not of class type, the
8561       // expression is implicitly converted (C++ 4) to the
8562       // cv-unqualified type of the left operand.
8563       QualType RHSType = RHS.get()->getType();
8564       if (Diagnose) {
8565         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8566                                         AA_Assigning);
8567       } else {
8568         ImplicitConversionSequence ICS =
8569             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8570                                   /*SuppressUserConversions=*/false,
8571                                   /*AllowExplicit=*/false,
8572                                   /*InOverloadResolution=*/false,
8573                                   /*CStyle=*/false,
8574                                   /*AllowObjCWritebackConversion=*/false);
8575         if (ICS.isFailure())
8576           return Incompatible;
8577         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8578                                         ICS, AA_Assigning);
8579       }
8580       if (RHS.isInvalid())
8581         return Incompatible;
8582       Sema::AssignConvertType result = Compatible;
8583       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8584           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8585         result = IncompatibleObjCWeakRef;
8586       return result;
8587     }
8588 
8589     // FIXME: Currently, we fall through and treat C++ classes like C
8590     // structures.
8591     // FIXME: We also fall through for atomics; not sure what should
8592     // happen there, though.
8593   } else if (RHS.get()->getType() == Context.OverloadTy) {
8594     // As a set of extensions to C, we support overloading on functions. These
8595     // functions need to be resolved here.
8596     DeclAccessPair DAP;
8597     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8598             RHS.get(), LHSType, /*Complain=*/false, DAP))
8599       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8600     else
8601       return Incompatible;
8602   }
8603 
8604   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8605   // a null pointer constant.
8606   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8607        LHSType->isBlockPointerType()) &&
8608       RHS.get()->isNullPointerConstant(Context,
8609                                        Expr::NPC_ValueDependentIsNull)) {
8610     if (Diagnose || ConvertRHS) {
8611       CastKind Kind;
8612       CXXCastPath Path;
8613       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8614                              /*IgnoreBaseAccess=*/false, Diagnose);
8615       if (ConvertRHS)
8616         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8617     }
8618     return Compatible;
8619   }
8620 
8621   // OpenCL queue_t type assignment.
8622   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8623                                  Context, Expr::NPC_ValueDependentIsNull)) {
8624     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8625     return Compatible;
8626   }
8627 
8628   // This check seems unnatural, however it is necessary to ensure the proper
8629   // conversion of functions/arrays. If the conversion were done for all
8630   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8631   // expressions that suppress this implicit conversion (&, sizeof).
8632   //
8633   // Suppress this for references: C++ 8.5.3p5.
8634   if (!LHSType->isReferenceType()) {
8635     // FIXME: We potentially allocate here even if ConvertRHS is false.
8636     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8637     if (RHS.isInvalid())
8638       return Incompatible;
8639   }
8640   CastKind Kind;
8641   Sema::AssignConvertType result =
8642     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8643 
8644   // C99 6.5.16.1p2: The value of the right operand is converted to the
8645   // type of the assignment expression.
8646   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8647   // so that we can use references in built-in functions even in C.
8648   // The getNonReferenceType() call makes sure that the resulting expression
8649   // does not have reference type.
8650   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8651     QualType Ty = LHSType.getNonLValueExprType(Context);
8652     Expr *E = RHS.get();
8653 
8654     // Check for various Objective-C errors. If we are not reporting
8655     // diagnostics and just checking for errors, e.g., during overload
8656     // resolution, return Incompatible to indicate the failure.
8657     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8658         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8659                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8660       if (!Diagnose)
8661         return Incompatible;
8662     }
8663     if (getLangOpts().ObjC &&
8664         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8665                                            E->getType(), E, Diagnose) ||
8666          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8667       if (!Diagnose)
8668         return Incompatible;
8669       // Replace the expression with a corrected version and continue so we
8670       // can find further errors.
8671       RHS = E;
8672       return Compatible;
8673     }
8674 
8675     if (ConvertRHS)
8676       RHS = ImpCastExprToType(E, Ty, Kind);
8677   }
8678 
8679   return result;
8680 }
8681 
8682 namespace {
8683 /// The original operand to an operator, prior to the application of the usual
8684 /// arithmetic conversions and converting the arguments of a builtin operator
8685 /// candidate.
8686 struct OriginalOperand {
8687   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8688     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8689       Op = MTE->GetTemporaryExpr();
8690     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8691       Op = BTE->getSubExpr();
8692     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8693       Orig = ICE->getSubExprAsWritten();
8694       Conversion = ICE->getConversionFunction();
8695     }
8696   }
8697 
8698   QualType getType() const { return Orig->getType(); }
8699 
8700   Expr *Orig;
8701   NamedDecl *Conversion;
8702 };
8703 }
8704 
8705 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8706                                ExprResult &RHS) {
8707   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8708 
8709   Diag(Loc, diag::err_typecheck_invalid_operands)
8710     << OrigLHS.getType() << OrigRHS.getType()
8711     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8712 
8713   // If a user-defined conversion was applied to either of the operands prior
8714   // to applying the built-in operator rules, tell the user about it.
8715   if (OrigLHS.Conversion) {
8716     Diag(OrigLHS.Conversion->getLocation(),
8717          diag::note_typecheck_invalid_operands_converted)
8718       << 0 << LHS.get()->getType();
8719   }
8720   if (OrigRHS.Conversion) {
8721     Diag(OrigRHS.Conversion->getLocation(),
8722          diag::note_typecheck_invalid_operands_converted)
8723       << 1 << RHS.get()->getType();
8724   }
8725 
8726   return QualType();
8727 }
8728 
8729 // Diagnose cases where a scalar was implicitly converted to a vector and
8730 // diagnose the underlying types. Otherwise, diagnose the error
8731 // as invalid vector logical operands for non-C++ cases.
8732 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8733                                             ExprResult &RHS) {
8734   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8735   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8736 
8737   bool LHSNatVec = LHSType->isVectorType();
8738   bool RHSNatVec = RHSType->isVectorType();
8739 
8740   if (!(LHSNatVec && RHSNatVec)) {
8741     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8742     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8743     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8744         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8745         << Vector->getSourceRange();
8746     return QualType();
8747   }
8748 
8749   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8750       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8751       << RHS.get()->getSourceRange();
8752 
8753   return QualType();
8754 }
8755 
8756 /// Try to convert a value of non-vector type to a vector type by converting
8757 /// the type to the element type of the vector and then performing a splat.
8758 /// If the language is OpenCL, we only use conversions that promote scalar
8759 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8760 /// for float->int.
8761 ///
8762 /// OpenCL V2.0 6.2.6.p2:
8763 /// An error shall occur if any scalar operand type has greater rank
8764 /// than the type of the vector element.
8765 ///
8766 /// \param scalar - if non-null, actually perform the conversions
8767 /// \return true if the operation fails (but without diagnosing the failure)
8768 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8769                                      QualType scalarTy,
8770                                      QualType vectorEltTy,
8771                                      QualType vectorTy,
8772                                      unsigned &DiagID) {
8773   // The conversion to apply to the scalar before splatting it,
8774   // if necessary.
8775   CastKind scalarCast = CK_NoOp;
8776 
8777   if (vectorEltTy->isIntegralType(S.Context)) {
8778     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8779         (scalarTy->isIntegerType() &&
8780          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8781       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8782       return true;
8783     }
8784     if (!scalarTy->isIntegralType(S.Context))
8785       return true;
8786     scalarCast = CK_IntegralCast;
8787   } else if (vectorEltTy->isRealFloatingType()) {
8788     if (scalarTy->isRealFloatingType()) {
8789       if (S.getLangOpts().OpenCL &&
8790           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8791         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8792         return true;
8793       }
8794       scalarCast = CK_FloatingCast;
8795     }
8796     else if (scalarTy->isIntegralType(S.Context))
8797       scalarCast = CK_IntegralToFloating;
8798     else
8799       return true;
8800   } else {
8801     return true;
8802   }
8803 
8804   // Adjust scalar if desired.
8805   if (scalar) {
8806     if (scalarCast != CK_NoOp)
8807       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8808     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8809   }
8810   return false;
8811 }
8812 
8813 /// Convert vector E to a vector with the same number of elements but different
8814 /// element type.
8815 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8816   const auto *VecTy = E->getType()->getAs<VectorType>();
8817   assert(VecTy && "Expression E must be a vector");
8818   QualType NewVecTy = S.Context.getVectorType(ElementType,
8819                                               VecTy->getNumElements(),
8820                                               VecTy->getVectorKind());
8821 
8822   // Look through the implicit cast. Return the subexpression if its type is
8823   // NewVecTy.
8824   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8825     if (ICE->getSubExpr()->getType() == NewVecTy)
8826       return ICE->getSubExpr();
8827 
8828   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8829   return S.ImpCastExprToType(E, NewVecTy, Cast);
8830 }
8831 
8832 /// Test if a (constant) integer Int can be casted to another integer type
8833 /// IntTy without losing precision.
8834 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8835                                       QualType OtherIntTy) {
8836   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8837 
8838   // Reject cases where the value of the Int is unknown as that would
8839   // possibly cause truncation, but accept cases where the scalar can be
8840   // demoted without loss of precision.
8841   Expr::EvalResult EVResult;
8842   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8843   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8844   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8845   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8846 
8847   if (CstInt) {
8848     // If the scalar is constant and is of a higher order and has more active
8849     // bits that the vector element type, reject it.
8850     llvm::APSInt Result = EVResult.Val.getInt();
8851     unsigned NumBits = IntSigned
8852                            ? (Result.isNegative() ? Result.getMinSignedBits()
8853                                                   : Result.getActiveBits())
8854                            : Result.getActiveBits();
8855     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8856       return true;
8857 
8858     // If the signedness of the scalar type and the vector element type
8859     // differs and the number of bits is greater than that of the vector
8860     // element reject it.
8861     return (IntSigned != OtherIntSigned &&
8862             NumBits > S.Context.getIntWidth(OtherIntTy));
8863   }
8864 
8865   // Reject cases where the value of the scalar is not constant and it's
8866   // order is greater than that of the vector element type.
8867   return (Order < 0);
8868 }
8869 
8870 /// Test if a (constant) integer Int can be casted to floating point type
8871 /// FloatTy without losing precision.
8872 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8873                                      QualType FloatTy) {
8874   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8875 
8876   // Determine if the integer constant can be expressed as a floating point
8877   // number of the appropriate type.
8878   Expr::EvalResult EVResult;
8879   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8880 
8881   uint64_t Bits = 0;
8882   if (CstInt) {
8883     // Reject constants that would be truncated if they were converted to
8884     // the floating point type. Test by simple to/from conversion.
8885     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8886     //        could be avoided if there was a convertFromAPInt method
8887     //        which could signal back if implicit truncation occurred.
8888     llvm::APSInt Result = EVResult.Val.getInt();
8889     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8890     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8891                            llvm::APFloat::rmTowardZero);
8892     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8893                              !IntTy->hasSignedIntegerRepresentation());
8894     bool Ignored = false;
8895     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8896                            &Ignored);
8897     if (Result != ConvertBack)
8898       return true;
8899   } else {
8900     // Reject types that cannot be fully encoded into the mantissa of
8901     // the float.
8902     Bits = S.Context.getTypeSize(IntTy);
8903     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8904         S.Context.getFloatTypeSemantics(FloatTy));
8905     if (Bits > FloatPrec)
8906       return true;
8907   }
8908 
8909   return false;
8910 }
8911 
8912 /// Attempt to convert and splat Scalar into a vector whose types matches
8913 /// Vector following GCC conversion rules. The rule is that implicit
8914 /// conversion can occur when Scalar can be casted to match Vector's element
8915 /// type without causing truncation of Scalar.
8916 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8917                                         ExprResult *Vector) {
8918   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8919   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8920   const VectorType *VT = VectorTy->getAs<VectorType>();
8921 
8922   assert(!isa<ExtVectorType>(VT) &&
8923          "ExtVectorTypes should not be handled here!");
8924 
8925   QualType VectorEltTy = VT->getElementType();
8926 
8927   // Reject cases where the vector element type or the scalar element type are
8928   // not integral or floating point types.
8929   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8930     return true;
8931 
8932   // The conversion to apply to the scalar before splatting it,
8933   // if necessary.
8934   CastKind ScalarCast = CK_NoOp;
8935 
8936   // Accept cases where the vector elements are integers and the scalar is
8937   // an integer.
8938   // FIXME: Notionally if the scalar was a floating point value with a precise
8939   //        integral representation, we could cast it to an appropriate integer
8940   //        type and then perform the rest of the checks here. GCC will perform
8941   //        this conversion in some cases as determined by the input language.
8942   //        We should accept it on a language independent basis.
8943   if (VectorEltTy->isIntegralType(S.Context) &&
8944       ScalarTy->isIntegralType(S.Context) &&
8945       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8946 
8947     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8948       return true;
8949 
8950     ScalarCast = CK_IntegralCast;
8951   } else if (VectorEltTy->isRealFloatingType()) {
8952     if (ScalarTy->isRealFloatingType()) {
8953 
8954       // Reject cases where the scalar type is not a constant and has a higher
8955       // Order than the vector element type.
8956       llvm::APFloat Result(0.0);
8957       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8958       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8959       if (!CstScalar && Order < 0)
8960         return true;
8961 
8962       // If the scalar cannot be safely casted to the vector element type,
8963       // reject it.
8964       if (CstScalar) {
8965         bool Truncated = false;
8966         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8967                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8968         if (Truncated)
8969           return true;
8970       }
8971 
8972       ScalarCast = CK_FloatingCast;
8973     } else if (ScalarTy->isIntegralType(S.Context)) {
8974       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8975         return true;
8976 
8977       ScalarCast = CK_IntegralToFloating;
8978     } else
8979       return true;
8980   }
8981 
8982   // Adjust scalar if desired.
8983   if (Scalar) {
8984     if (ScalarCast != CK_NoOp)
8985       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8986     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8987   }
8988   return false;
8989 }
8990 
8991 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8992                                    SourceLocation Loc, bool IsCompAssign,
8993                                    bool AllowBothBool,
8994                                    bool AllowBoolConversions) {
8995   if (!IsCompAssign) {
8996     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8997     if (LHS.isInvalid())
8998       return QualType();
8999   }
9000   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9001   if (RHS.isInvalid())
9002     return QualType();
9003 
9004   // For conversion purposes, we ignore any qualifiers.
9005   // For example, "const float" and "float" are equivalent.
9006   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9007   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9008 
9009   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9010   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9011   assert(LHSVecType || RHSVecType);
9012 
9013   // AltiVec-style "vector bool op vector bool" combinations are allowed
9014   // for some operators but not others.
9015   if (!AllowBothBool &&
9016       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9017       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9018     return InvalidOperands(Loc, LHS, RHS);
9019 
9020   // If the vector types are identical, return.
9021   if (Context.hasSameType(LHSType, RHSType))
9022     return LHSType;
9023 
9024   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9025   if (LHSVecType && RHSVecType &&
9026       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9027     if (isa<ExtVectorType>(LHSVecType)) {
9028       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9029       return LHSType;
9030     }
9031 
9032     if (!IsCompAssign)
9033       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9034     return RHSType;
9035   }
9036 
9037   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9038   // can be mixed, with the result being the non-bool type.  The non-bool
9039   // operand must have integer element type.
9040   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9041       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9042       (Context.getTypeSize(LHSVecType->getElementType()) ==
9043        Context.getTypeSize(RHSVecType->getElementType()))) {
9044     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9045         LHSVecType->getElementType()->isIntegerType() &&
9046         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9047       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9048       return LHSType;
9049     }
9050     if (!IsCompAssign &&
9051         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9052         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9053         RHSVecType->getElementType()->isIntegerType()) {
9054       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9055       return RHSType;
9056     }
9057   }
9058 
9059   // If there's a vector type and a scalar, try to convert the scalar to
9060   // the vector element type and splat.
9061   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9062   if (!RHSVecType) {
9063     if (isa<ExtVectorType>(LHSVecType)) {
9064       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9065                                     LHSVecType->getElementType(), LHSType,
9066                                     DiagID))
9067         return LHSType;
9068     } else {
9069       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9070         return LHSType;
9071     }
9072   }
9073   if (!LHSVecType) {
9074     if (isa<ExtVectorType>(RHSVecType)) {
9075       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9076                                     LHSType, RHSVecType->getElementType(),
9077                                     RHSType, DiagID))
9078         return RHSType;
9079     } else {
9080       if (LHS.get()->getValueKind() == VK_LValue ||
9081           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9082         return RHSType;
9083     }
9084   }
9085 
9086   // FIXME: The code below also handles conversion between vectors and
9087   // non-scalars, we should break this down into fine grained specific checks
9088   // and emit proper diagnostics.
9089   QualType VecType = LHSVecType ? LHSType : RHSType;
9090   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9091   QualType OtherType = LHSVecType ? RHSType : LHSType;
9092   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9093   if (isLaxVectorConversion(OtherType, VecType)) {
9094     // If we're allowing lax vector conversions, only the total (data) size
9095     // needs to be the same. For non compound assignment, if one of the types is
9096     // scalar, the result is always the vector type.
9097     if (!IsCompAssign) {
9098       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9099       return VecType;
9100     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9101     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9102     // type. Note that this is already done by non-compound assignments in
9103     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9104     // <1 x T> -> T. The result is also a vector type.
9105     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9106                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9107       ExprResult *RHSExpr = &RHS;
9108       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9109       return VecType;
9110     }
9111   }
9112 
9113   // Okay, the expression is invalid.
9114 
9115   // If there's a non-vector, non-real operand, diagnose that.
9116   if ((!RHSVecType && !RHSType->isRealType()) ||
9117       (!LHSVecType && !LHSType->isRealType())) {
9118     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9119       << LHSType << RHSType
9120       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9121     return QualType();
9122   }
9123 
9124   // OpenCL V1.1 6.2.6.p1:
9125   // If the operands are of more than one vector type, then an error shall
9126   // occur. Implicit conversions between vector types are not permitted, per
9127   // section 6.2.1.
9128   if (getLangOpts().OpenCL &&
9129       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9130       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9131     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9132                                                            << RHSType;
9133     return QualType();
9134   }
9135 
9136 
9137   // If there is a vector type that is not a ExtVector and a scalar, we reach
9138   // this point if scalar could not be converted to the vector's element type
9139   // without truncation.
9140   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9141       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9142     QualType Scalar = LHSVecType ? RHSType : LHSType;
9143     QualType Vector = LHSVecType ? LHSType : RHSType;
9144     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9145     Diag(Loc,
9146          diag::err_typecheck_vector_not_convertable_implict_truncation)
9147         << ScalarOrVector << Scalar << Vector;
9148 
9149     return QualType();
9150   }
9151 
9152   // Otherwise, use the generic diagnostic.
9153   Diag(Loc, DiagID)
9154     << LHSType << RHSType
9155     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9156   return QualType();
9157 }
9158 
9159 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9160 // expression.  These are mainly cases where the null pointer is used as an
9161 // integer instead of a pointer.
9162 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9163                                 SourceLocation Loc, bool IsCompare) {
9164   // The canonical way to check for a GNU null is with isNullPointerConstant,
9165   // but we use a bit of a hack here for speed; this is a relatively
9166   // hot path, and isNullPointerConstant is slow.
9167   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9168   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9169 
9170   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9171 
9172   // Avoid analyzing cases where the result will either be invalid (and
9173   // diagnosed as such) or entirely valid and not something to warn about.
9174   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9175       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9176     return;
9177 
9178   // Comparison operations would not make sense with a null pointer no matter
9179   // what the other expression is.
9180   if (!IsCompare) {
9181     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9182         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9183         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9184     return;
9185   }
9186 
9187   // The rest of the operations only make sense with a null pointer
9188   // if the other expression is a pointer.
9189   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9190       NonNullType->canDecayToPointerType())
9191     return;
9192 
9193   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9194       << LHSNull /* LHS is NULL */ << NonNullType
9195       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9196 }
9197 
9198 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9199                                           SourceLocation Loc) {
9200   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9201   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9202   if (!LUE || !RUE)
9203     return;
9204   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9205       RUE->getKind() != UETT_SizeOf)
9206     return;
9207 
9208   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9209   QualType LHSTy = LHSArg->getType();
9210   QualType RHSTy;
9211 
9212   if (RUE->isArgumentType())
9213     RHSTy = RUE->getArgumentType();
9214   else
9215     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9216 
9217   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9218     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9219       return;
9220 
9221     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9222     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9223       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9224         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9225             << LHSArgDecl;
9226     }
9227   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9228     QualType ArrayElemTy = ArrayTy->getElementType();
9229     if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9230         ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9231         ArrayElemTy->isCharType() ||
9232         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9233       return;
9234     S.Diag(Loc, diag::warn_division_sizeof_array)
9235         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9236     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9237       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9238         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9239             << LHSArgDecl;
9240     }
9241 
9242     S.Diag(Loc, diag::note_precedence_silence) << RHS;
9243   }
9244 }
9245 
9246 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9247                                                ExprResult &RHS,
9248                                                SourceLocation Loc, bool IsDiv) {
9249   // Check for division/remainder by zero.
9250   Expr::EvalResult RHSValue;
9251   if (!RHS.get()->isValueDependent() &&
9252       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9253       RHSValue.Val.getInt() == 0)
9254     S.DiagRuntimeBehavior(Loc, RHS.get(),
9255                           S.PDiag(diag::warn_remainder_division_by_zero)
9256                             << IsDiv << RHS.get()->getSourceRange());
9257 }
9258 
9259 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9260                                            SourceLocation Loc,
9261                                            bool IsCompAssign, bool IsDiv) {
9262   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9263 
9264   if (LHS.get()->getType()->isVectorType() ||
9265       RHS.get()->getType()->isVectorType())
9266     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9267                                /*AllowBothBool*/getLangOpts().AltiVec,
9268                                /*AllowBoolConversions*/false);
9269 
9270   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9271   if (LHS.isInvalid() || RHS.isInvalid())
9272     return QualType();
9273 
9274 
9275   if (compType.isNull() || !compType->isArithmeticType())
9276     return InvalidOperands(Loc, LHS, RHS);
9277   if (IsDiv) {
9278     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9279     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9280   }
9281   return compType;
9282 }
9283 
9284 QualType Sema::CheckRemainderOperands(
9285   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9286   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9287 
9288   if (LHS.get()->getType()->isVectorType() ||
9289       RHS.get()->getType()->isVectorType()) {
9290     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9291         RHS.get()->getType()->hasIntegerRepresentation())
9292       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9293                                  /*AllowBothBool*/getLangOpts().AltiVec,
9294                                  /*AllowBoolConversions*/false);
9295     return InvalidOperands(Loc, LHS, RHS);
9296   }
9297 
9298   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9299   if (LHS.isInvalid() || RHS.isInvalid())
9300     return QualType();
9301 
9302   if (compType.isNull() || !compType->isIntegerType())
9303     return InvalidOperands(Loc, LHS, RHS);
9304   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9305   return compType;
9306 }
9307 
9308 /// Diagnose invalid arithmetic on two void pointers.
9309 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9310                                                 Expr *LHSExpr, Expr *RHSExpr) {
9311   S.Diag(Loc, S.getLangOpts().CPlusPlus
9312                 ? diag::err_typecheck_pointer_arith_void_type
9313                 : diag::ext_gnu_void_ptr)
9314     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9315                             << RHSExpr->getSourceRange();
9316 }
9317 
9318 /// Diagnose invalid arithmetic on a void pointer.
9319 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9320                                             Expr *Pointer) {
9321   S.Diag(Loc, S.getLangOpts().CPlusPlus
9322                 ? diag::err_typecheck_pointer_arith_void_type
9323                 : diag::ext_gnu_void_ptr)
9324     << 0 /* one pointer */ << Pointer->getSourceRange();
9325 }
9326 
9327 /// Diagnose invalid arithmetic on a null pointer.
9328 ///
9329 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9330 /// idiom, which we recognize as a GNU extension.
9331 ///
9332 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9333                                             Expr *Pointer, bool IsGNUIdiom) {
9334   if (IsGNUIdiom)
9335     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9336       << Pointer->getSourceRange();
9337   else
9338     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9339       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9340 }
9341 
9342 /// Diagnose invalid arithmetic on two function pointers.
9343 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9344                                                     Expr *LHS, Expr *RHS) {
9345   assert(LHS->getType()->isAnyPointerType());
9346   assert(RHS->getType()->isAnyPointerType());
9347   S.Diag(Loc, S.getLangOpts().CPlusPlus
9348                 ? diag::err_typecheck_pointer_arith_function_type
9349                 : diag::ext_gnu_ptr_func_arith)
9350     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9351     // We only show the second type if it differs from the first.
9352     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9353                                                    RHS->getType())
9354     << RHS->getType()->getPointeeType()
9355     << LHS->getSourceRange() << RHS->getSourceRange();
9356 }
9357 
9358 /// Diagnose invalid arithmetic on a function pointer.
9359 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9360                                                 Expr *Pointer) {
9361   assert(Pointer->getType()->isAnyPointerType());
9362   S.Diag(Loc, S.getLangOpts().CPlusPlus
9363                 ? diag::err_typecheck_pointer_arith_function_type
9364                 : diag::ext_gnu_ptr_func_arith)
9365     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9366     << 0 /* one pointer, so only one type */
9367     << Pointer->getSourceRange();
9368 }
9369 
9370 /// Emit error if Operand is incomplete pointer type
9371 ///
9372 /// \returns True if pointer has incomplete type
9373 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9374                                                  Expr *Operand) {
9375   QualType ResType = Operand->getType();
9376   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9377     ResType = ResAtomicType->getValueType();
9378 
9379   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9380   QualType PointeeTy = ResType->getPointeeType();
9381   return S.RequireCompleteType(Loc, PointeeTy,
9382                                diag::err_typecheck_arithmetic_incomplete_type,
9383                                PointeeTy, Operand->getSourceRange());
9384 }
9385 
9386 /// Check the validity of an arithmetic pointer operand.
9387 ///
9388 /// If the operand has pointer type, this code will check for pointer types
9389 /// which are invalid in arithmetic operations. These will be diagnosed
9390 /// appropriately, including whether or not the use is supported as an
9391 /// extension.
9392 ///
9393 /// \returns True when the operand is valid to use (even if as an extension).
9394 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9395                                             Expr *Operand) {
9396   QualType ResType = Operand->getType();
9397   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9398     ResType = ResAtomicType->getValueType();
9399 
9400   if (!ResType->isAnyPointerType()) return true;
9401 
9402   QualType PointeeTy = ResType->getPointeeType();
9403   if (PointeeTy->isVoidType()) {
9404     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9405     return !S.getLangOpts().CPlusPlus;
9406   }
9407   if (PointeeTy->isFunctionType()) {
9408     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9409     return !S.getLangOpts().CPlusPlus;
9410   }
9411 
9412   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9413 
9414   return true;
9415 }
9416 
9417 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9418 /// operands.
9419 ///
9420 /// This routine will diagnose any invalid arithmetic on pointer operands much
9421 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9422 /// for emitting a single diagnostic even for operations where both LHS and RHS
9423 /// are (potentially problematic) pointers.
9424 ///
9425 /// \returns True when the operand is valid to use (even if as an extension).
9426 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9427                                                 Expr *LHSExpr, Expr *RHSExpr) {
9428   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9429   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9430   if (!isLHSPointer && !isRHSPointer) return true;
9431 
9432   QualType LHSPointeeTy, RHSPointeeTy;
9433   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9434   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9435 
9436   // if both are pointers check if operation is valid wrt address spaces
9437   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9438     const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9439     const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9440     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9441       S.Diag(Loc,
9442              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9443           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9444           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9445       return false;
9446     }
9447   }
9448 
9449   // Check for arithmetic on pointers to incomplete types.
9450   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9451   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9452   if (isLHSVoidPtr || isRHSVoidPtr) {
9453     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9454     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9455     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9456 
9457     return !S.getLangOpts().CPlusPlus;
9458   }
9459 
9460   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9461   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9462   if (isLHSFuncPtr || isRHSFuncPtr) {
9463     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9464     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9465                                                                 RHSExpr);
9466     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9467 
9468     return !S.getLangOpts().CPlusPlus;
9469   }
9470 
9471   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9472     return false;
9473   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9474     return false;
9475 
9476   return true;
9477 }
9478 
9479 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9480 /// literal.
9481 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9482                                   Expr *LHSExpr, Expr *RHSExpr) {
9483   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9484   Expr* IndexExpr = RHSExpr;
9485   if (!StrExpr) {
9486     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9487     IndexExpr = LHSExpr;
9488   }
9489 
9490   bool IsStringPlusInt = StrExpr &&
9491       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9492   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9493     return;
9494 
9495   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9496   Self.Diag(OpLoc, diag::warn_string_plus_int)
9497       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9498 
9499   // Only print a fixit for "str" + int, not for int + "str".
9500   if (IndexExpr == RHSExpr) {
9501     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9502     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9503         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9504         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9505         << FixItHint::CreateInsertion(EndLoc, "]");
9506   } else
9507     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9508 }
9509 
9510 /// Emit a warning when adding a char literal to a string.
9511 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9512                                    Expr *LHSExpr, Expr *RHSExpr) {
9513   const Expr *StringRefExpr = LHSExpr;
9514   const CharacterLiteral *CharExpr =
9515       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9516 
9517   if (!CharExpr) {
9518     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9519     StringRefExpr = RHSExpr;
9520   }
9521 
9522   if (!CharExpr || !StringRefExpr)
9523     return;
9524 
9525   const QualType StringType = StringRefExpr->getType();
9526 
9527   // Return if not a PointerType.
9528   if (!StringType->isAnyPointerType())
9529     return;
9530 
9531   // Return if not a CharacterType.
9532   if (!StringType->getPointeeType()->isAnyCharacterType())
9533     return;
9534 
9535   ASTContext &Ctx = Self.getASTContext();
9536   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9537 
9538   const QualType CharType = CharExpr->getType();
9539   if (!CharType->isAnyCharacterType() &&
9540       CharType->isIntegerType() &&
9541       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9542     Self.Diag(OpLoc, diag::warn_string_plus_char)
9543         << DiagRange << Ctx.CharTy;
9544   } else {
9545     Self.Diag(OpLoc, diag::warn_string_plus_char)
9546         << DiagRange << CharExpr->getType();
9547   }
9548 
9549   // Only print a fixit for str + char, not for char + str.
9550   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9551     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9552     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9553         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9554         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9555         << FixItHint::CreateInsertion(EndLoc, "]");
9556   } else {
9557     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9558   }
9559 }
9560 
9561 /// Emit error when two pointers are incompatible.
9562 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9563                                            Expr *LHSExpr, Expr *RHSExpr) {
9564   assert(LHSExpr->getType()->isAnyPointerType());
9565   assert(RHSExpr->getType()->isAnyPointerType());
9566   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9567     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9568     << RHSExpr->getSourceRange();
9569 }
9570 
9571 // C99 6.5.6
9572 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9573                                      SourceLocation Loc, BinaryOperatorKind Opc,
9574                                      QualType* CompLHSTy) {
9575   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9576 
9577   if (LHS.get()->getType()->isVectorType() ||
9578       RHS.get()->getType()->isVectorType()) {
9579     QualType compType = CheckVectorOperands(
9580         LHS, RHS, Loc, CompLHSTy,
9581         /*AllowBothBool*/getLangOpts().AltiVec,
9582         /*AllowBoolConversions*/getLangOpts().ZVector);
9583     if (CompLHSTy) *CompLHSTy = compType;
9584     return compType;
9585   }
9586 
9587   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9588   if (LHS.isInvalid() || RHS.isInvalid())
9589     return QualType();
9590 
9591   // Diagnose "string literal" '+' int and string '+' "char literal".
9592   if (Opc == BO_Add) {
9593     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9594     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9595   }
9596 
9597   // handle the common case first (both operands are arithmetic).
9598   if (!compType.isNull() && compType->isArithmeticType()) {
9599     if (CompLHSTy) *CompLHSTy = compType;
9600     return compType;
9601   }
9602 
9603   // Type-checking.  Ultimately the pointer's going to be in PExp;
9604   // note that we bias towards the LHS being the pointer.
9605   Expr *PExp = LHS.get(), *IExp = RHS.get();
9606 
9607   bool isObjCPointer;
9608   if (PExp->getType()->isPointerType()) {
9609     isObjCPointer = false;
9610   } else if (PExp->getType()->isObjCObjectPointerType()) {
9611     isObjCPointer = true;
9612   } else {
9613     std::swap(PExp, IExp);
9614     if (PExp->getType()->isPointerType()) {
9615       isObjCPointer = false;
9616     } else if (PExp->getType()->isObjCObjectPointerType()) {
9617       isObjCPointer = true;
9618     } else {
9619       return InvalidOperands(Loc, LHS, RHS);
9620     }
9621   }
9622   assert(PExp->getType()->isAnyPointerType());
9623 
9624   if (!IExp->getType()->isIntegerType())
9625     return InvalidOperands(Loc, LHS, RHS);
9626 
9627   // Adding to a null pointer results in undefined behavior.
9628   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9629           Context, Expr::NPC_ValueDependentIsNotNull)) {
9630     // In C++ adding zero to a null pointer is defined.
9631     Expr::EvalResult KnownVal;
9632     if (!getLangOpts().CPlusPlus ||
9633         (!IExp->isValueDependent() &&
9634          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9635           KnownVal.Val.getInt() != 0))) {
9636       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9637       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9638           Context, BO_Add, PExp, IExp);
9639       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9640     }
9641   }
9642 
9643   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9644     return QualType();
9645 
9646   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9647     return QualType();
9648 
9649   // Check array bounds for pointer arithemtic
9650   CheckArrayAccess(PExp, IExp);
9651 
9652   if (CompLHSTy) {
9653     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9654     if (LHSTy.isNull()) {
9655       LHSTy = LHS.get()->getType();
9656       if (LHSTy->isPromotableIntegerType())
9657         LHSTy = Context.getPromotedIntegerType(LHSTy);
9658     }
9659     *CompLHSTy = LHSTy;
9660   }
9661 
9662   return PExp->getType();
9663 }
9664 
9665 // C99 6.5.6
9666 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9667                                         SourceLocation Loc,
9668                                         QualType* CompLHSTy) {
9669   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9670 
9671   if (LHS.get()->getType()->isVectorType() ||
9672       RHS.get()->getType()->isVectorType()) {
9673     QualType compType = CheckVectorOperands(
9674         LHS, RHS, Loc, CompLHSTy,
9675         /*AllowBothBool*/getLangOpts().AltiVec,
9676         /*AllowBoolConversions*/getLangOpts().ZVector);
9677     if (CompLHSTy) *CompLHSTy = compType;
9678     return compType;
9679   }
9680 
9681   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9682   if (LHS.isInvalid() || RHS.isInvalid())
9683     return QualType();
9684 
9685   // Enforce type constraints: C99 6.5.6p3.
9686 
9687   // Handle the common case first (both operands are arithmetic).
9688   if (!compType.isNull() && compType->isArithmeticType()) {
9689     if (CompLHSTy) *CompLHSTy = compType;
9690     return compType;
9691   }
9692 
9693   // Either ptr - int   or   ptr - ptr.
9694   if (LHS.get()->getType()->isAnyPointerType()) {
9695     QualType lpointee = LHS.get()->getType()->getPointeeType();
9696 
9697     // Diagnose bad cases where we step over interface counts.
9698     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9699         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9700       return QualType();
9701 
9702     // The result type of a pointer-int computation is the pointer type.
9703     if (RHS.get()->getType()->isIntegerType()) {
9704       // Subtracting from a null pointer should produce a warning.
9705       // The last argument to the diagnose call says this doesn't match the
9706       // GNU int-to-pointer idiom.
9707       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9708                                            Expr::NPC_ValueDependentIsNotNull)) {
9709         // In C++ adding zero to a null pointer is defined.
9710         Expr::EvalResult KnownVal;
9711         if (!getLangOpts().CPlusPlus ||
9712             (!RHS.get()->isValueDependent() &&
9713              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9714               KnownVal.Val.getInt() != 0))) {
9715           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9716         }
9717       }
9718 
9719       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9720         return QualType();
9721 
9722       // Check array bounds for pointer arithemtic
9723       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9724                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9725 
9726       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9727       return LHS.get()->getType();
9728     }
9729 
9730     // Handle pointer-pointer subtractions.
9731     if (const PointerType *RHSPTy
9732           = RHS.get()->getType()->getAs<PointerType>()) {
9733       QualType rpointee = RHSPTy->getPointeeType();
9734 
9735       if (getLangOpts().CPlusPlus) {
9736         // Pointee types must be the same: C++ [expr.add]
9737         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9738           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9739         }
9740       } else {
9741         // Pointee types must be compatible C99 6.5.6p3
9742         if (!Context.typesAreCompatible(
9743                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9744                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9745           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9746           return QualType();
9747         }
9748       }
9749 
9750       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9751                                                LHS.get(), RHS.get()))
9752         return QualType();
9753 
9754       // FIXME: Add warnings for nullptr - ptr.
9755 
9756       // The pointee type may have zero size.  As an extension, a structure or
9757       // union may have zero size or an array may have zero length.  In this
9758       // case subtraction does not make sense.
9759       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9760         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9761         if (ElementSize.isZero()) {
9762           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9763             << rpointee.getUnqualifiedType()
9764             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9765         }
9766       }
9767 
9768       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9769       return Context.getPointerDiffType();
9770     }
9771   }
9772 
9773   return InvalidOperands(Loc, LHS, RHS);
9774 }
9775 
9776 static bool isScopedEnumerationType(QualType T) {
9777   if (const EnumType *ET = T->getAs<EnumType>())
9778     return ET->getDecl()->isScoped();
9779   return false;
9780 }
9781 
9782 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9783                                    SourceLocation Loc, BinaryOperatorKind Opc,
9784                                    QualType LHSType) {
9785   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9786   // so skip remaining warnings as we don't want to modify values within Sema.
9787   if (S.getLangOpts().OpenCL)
9788     return;
9789 
9790   // Check right/shifter operand
9791   Expr::EvalResult RHSResult;
9792   if (RHS.get()->isValueDependent() ||
9793       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9794     return;
9795   llvm::APSInt Right = RHSResult.Val.getInt();
9796 
9797   if (Right.isNegative()) {
9798     S.DiagRuntimeBehavior(Loc, RHS.get(),
9799                           S.PDiag(diag::warn_shift_negative)
9800                             << RHS.get()->getSourceRange());
9801     return;
9802   }
9803   llvm::APInt LeftBits(Right.getBitWidth(),
9804                        S.Context.getTypeSize(LHS.get()->getType()));
9805   if (Right.uge(LeftBits)) {
9806     S.DiagRuntimeBehavior(Loc, RHS.get(),
9807                           S.PDiag(diag::warn_shift_gt_typewidth)
9808                             << RHS.get()->getSourceRange());
9809     return;
9810   }
9811   if (Opc != BO_Shl)
9812     return;
9813 
9814   // When left shifting an ICE which is signed, we can check for overflow which
9815   // according to C++ standards prior to C++2a has undefined behavior
9816   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9817   // more than the maximum value representable in the result type, so never
9818   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9819   // expression is still probably a bug.)
9820   Expr::EvalResult LHSResult;
9821   if (LHS.get()->isValueDependent() ||
9822       LHSType->hasUnsignedIntegerRepresentation() ||
9823       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9824     return;
9825   llvm::APSInt Left = LHSResult.Val.getInt();
9826 
9827   // If LHS does not have a signed type and non-negative value
9828   // then, the behavior is undefined before C++2a. Warn about it.
9829   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9830       !S.getLangOpts().CPlusPlus2a) {
9831     S.DiagRuntimeBehavior(Loc, LHS.get(),
9832                           S.PDiag(diag::warn_shift_lhs_negative)
9833                             << LHS.get()->getSourceRange());
9834     return;
9835   }
9836 
9837   llvm::APInt ResultBits =
9838       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9839   if (LeftBits.uge(ResultBits))
9840     return;
9841   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9842   Result = Result.shl(Right);
9843 
9844   // Print the bit representation of the signed integer as an unsigned
9845   // hexadecimal number.
9846   SmallString<40> HexResult;
9847   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9848 
9849   // If we are only missing a sign bit, this is less likely to result in actual
9850   // bugs -- if the result is cast back to an unsigned type, it will have the
9851   // expected value. Thus we place this behind a different warning that can be
9852   // turned off separately if needed.
9853   if (LeftBits == ResultBits - 1) {
9854     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9855         << HexResult << LHSType
9856         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9857     return;
9858   }
9859 
9860   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9861     << HexResult.str() << Result.getMinSignedBits() << LHSType
9862     << Left.getBitWidth() << LHS.get()->getSourceRange()
9863     << RHS.get()->getSourceRange();
9864 }
9865 
9866 /// Return the resulting type when a vector is shifted
9867 ///        by a scalar or vector shift amount.
9868 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9869                                  SourceLocation Loc, bool IsCompAssign) {
9870   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9871   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9872       !LHS.get()->getType()->isVectorType()) {
9873     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9874       << RHS.get()->getType() << LHS.get()->getType()
9875       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9876     return QualType();
9877   }
9878 
9879   if (!IsCompAssign) {
9880     LHS = S.UsualUnaryConversions(LHS.get());
9881     if (LHS.isInvalid()) return QualType();
9882   }
9883 
9884   RHS = S.UsualUnaryConversions(RHS.get());
9885   if (RHS.isInvalid()) return QualType();
9886 
9887   QualType LHSType = LHS.get()->getType();
9888   // Note that LHS might be a scalar because the routine calls not only in
9889   // OpenCL case.
9890   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9891   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9892 
9893   // Note that RHS might not be a vector.
9894   QualType RHSType = RHS.get()->getType();
9895   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9896   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9897 
9898   // The operands need to be integers.
9899   if (!LHSEleType->isIntegerType()) {
9900     S.Diag(Loc, diag::err_typecheck_expect_int)
9901       << LHS.get()->getType() << LHS.get()->getSourceRange();
9902     return QualType();
9903   }
9904 
9905   if (!RHSEleType->isIntegerType()) {
9906     S.Diag(Loc, diag::err_typecheck_expect_int)
9907       << RHS.get()->getType() << RHS.get()->getSourceRange();
9908     return QualType();
9909   }
9910 
9911   if (!LHSVecTy) {
9912     assert(RHSVecTy);
9913     if (IsCompAssign)
9914       return RHSType;
9915     if (LHSEleType != RHSEleType) {
9916       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9917       LHSEleType = RHSEleType;
9918     }
9919     QualType VecTy =
9920         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9921     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9922     LHSType = VecTy;
9923   } else if (RHSVecTy) {
9924     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9925     // are applied component-wise. So if RHS is a vector, then ensure
9926     // that the number of elements is the same as LHS...
9927     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9928       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9929         << LHS.get()->getType() << RHS.get()->getType()
9930         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9931       return QualType();
9932     }
9933     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9934       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9935       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9936       if (LHSBT != RHSBT &&
9937           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9938         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9939             << LHS.get()->getType() << RHS.get()->getType()
9940             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9941       }
9942     }
9943   } else {
9944     // ...else expand RHS to match the number of elements in LHS.
9945     QualType VecTy =
9946       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9947     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9948   }
9949 
9950   return LHSType;
9951 }
9952 
9953 // C99 6.5.7
9954 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9955                                   SourceLocation Loc, BinaryOperatorKind Opc,
9956                                   bool IsCompAssign) {
9957   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9958 
9959   // Vector shifts promote their scalar inputs to vector type.
9960   if (LHS.get()->getType()->isVectorType() ||
9961       RHS.get()->getType()->isVectorType()) {
9962     if (LangOpts.ZVector) {
9963       // The shift operators for the z vector extensions work basically
9964       // like general shifts, except that neither the LHS nor the RHS is
9965       // allowed to be a "vector bool".
9966       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9967         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9968           return InvalidOperands(Loc, LHS, RHS);
9969       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9970         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9971           return InvalidOperands(Loc, LHS, RHS);
9972     }
9973     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9974   }
9975 
9976   // Shifts don't perform usual arithmetic conversions, they just do integer
9977   // promotions on each operand. C99 6.5.7p3
9978 
9979   // For the LHS, do usual unary conversions, but then reset them away
9980   // if this is a compound assignment.
9981   ExprResult OldLHS = LHS;
9982   LHS = UsualUnaryConversions(LHS.get());
9983   if (LHS.isInvalid())
9984     return QualType();
9985   QualType LHSType = LHS.get()->getType();
9986   if (IsCompAssign) LHS = OldLHS;
9987 
9988   // The RHS is simpler.
9989   RHS = UsualUnaryConversions(RHS.get());
9990   if (RHS.isInvalid())
9991     return QualType();
9992   QualType RHSType = RHS.get()->getType();
9993 
9994   // C99 6.5.7p2: Each of the operands shall have integer type.
9995   if (!LHSType->hasIntegerRepresentation() ||
9996       !RHSType->hasIntegerRepresentation())
9997     return InvalidOperands(Loc, LHS, RHS);
9998 
9999   // C++0x: Don't allow scoped enums. FIXME: Use something better than
10000   // hasIntegerRepresentation() above instead of this.
10001   if (isScopedEnumerationType(LHSType) ||
10002       isScopedEnumerationType(RHSType)) {
10003     return InvalidOperands(Loc, LHS, RHS);
10004   }
10005   // Sanity-check shift operands
10006   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10007 
10008   // "The type of the result is that of the promoted left operand."
10009   return LHSType;
10010 }
10011 
10012 /// If two different enums are compared, raise a warning.
10013 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
10014                                 Expr *RHS) {
10015   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
10016   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
10017 
10018   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
10019   if (!LHSEnumType)
10020     return;
10021   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
10022   if (!RHSEnumType)
10023     return;
10024 
10025   // Ignore anonymous enums.
10026   if (!LHSEnumType->getDecl()->getIdentifier() &&
10027       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
10028     return;
10029   if (!RHSEnumType->getDecl()->getIdentifier() &&
10030       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
10031     return;
10032 
10033   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
10034     return;
10035 
10036   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
10037       << LHSStrippedType << RHSStrippedType
10038       << LHS->getSourceRange() << RHS->getSourceRange();
10039 }
10040 
10041 /// Diagnose bad pointer comparisons.
10042 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10043                                               ExprResult &LHS, ExprResult &RHS,
10044                                               bool IsError) {
10045   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10046                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10047     << LHS.get()->getType() << RHS.get()->getType()
10048     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10049 }
10050 
10051 /// Returns false if the pointers are converted to a composite type,
10052 /// true otherwise.
10053 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10054                                            ExprResult &LHS, ExprResult &RHS) {
10055   // C++ [expr.rel]p2:
10056   //   [...] Pointer conversions (4.10) and qualification
10057   //   conversions (4.4) are performed on pointer operands (or on
10058   //   a pointer operand and a null pointer constant) to bring
10059   //   them to their composite pointer type. [...]
10060   //
10061   // C++ [expr.eq]p1 uses the same notion for (in)equality
10062   // comparisons of pointers.
10063 
10064   QualType LHSType = LHS.get()->getType();
10065   QualType RHSType = RHS.get()->getType();
10066   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10067          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10068 
10069   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10070   if (T.isNull()) {
10071     if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10072         (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10073       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10074     else
10075       S.InvalidOperands(Loc, LHS, RHS);
10076     return true;
10077   }
10078 
10079   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
10080   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
10081   return false;
10082 }
10083 
10084 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10085                                                     ExprResult &LHS,
10086                                                     ExprResult &RHS,
10087                                                     bool IsError) {
10088   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10089                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10090     << LHS.get()->getType() << RHS.get()->getType()
10091     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10092 }
10093 
10094 static bool isObjCObjectLiteral(ExprResult &E) {
10095   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10096   case Stmt::ObjCArrayLiteralClass:
10097   case Stmt::ObjCDictionaryLiteralClass:
10098   case Stmt::ObjCStringLiteralClass:
10099   case Stmt::ObjCBoxedExprClass:
10100     return true;
10101   default:
10102     // Note that ObjCBoolLiteral is NOT an object literal!
10103     return false;
10104   }
10105 }
10106 
10107 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10108   const ObjCObjectPointerType *Type =
10109     LHS->getType()->getAs<ObjCObjectPointerType>();
10110 
10111   // If this is not actually an Objective-C object, bail out.
10112   if (!Type)
10113     return false;
10114 
10115   // Get the LHS object's interface type.
10116   QualType InterfaceType = Type->getPointeeType();
10117 
10118   // If the RHS isn't an Objective-C object, bail out.
10119   if (!RHS->getType()->isObjCObjectPointerType())
10120     return false;
10121 
10122   // Try to find the -isEqual: method.
10123   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10124   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10125                                                       InterfaceType,
10126                                                       /*IsInstance=*/true);
10127   if (!Method) {
10128     if (Type->isObjCIdType()) {
10129       // For 'id', just check the global pool.
10130       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10131                                                   /*receiverId=*/true);
10132     } else {
10133       // Check protocols.
10134       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10135                                              /*IsInstance=*/true);
10136     }
10137   }
10138 
10139   if (!Method)
10140     return false;
10141 
10142   QualType T = Method->parameters()[0]->getType();
10143   if (!T->isObjCObjectPointerType())
10144     return false;
10145 
10146   QualType R = Method->getReturnType();
10147   if (!R->isScalarType())
10148     return false;
10149 
10150   return true;
10151 }
10152 
10153 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10154   FromE = FromE->IgnoreParenImpCasts();
10155   switch (FromE->getStmtClass()) {
10156     default:
10157       break;
10158     case Stmt::ObjCStringLiteralClass:
10159       // "string literal"
10160       return LK_String;
10161     case Stmt::ObjCArrayLiteralClass:
10162       // "array literal"
10163       return LK_Array;
10164     case Stmt::ObjCDictionaryLiteralClass:
10165       // "dictionary literal"
10166       return LK_Dictionary;
10167     case Stmt::BlockExprClass:
10168       return LK_Block;
10169     case Stmt::ObjCBoxedExprClass: {
10170       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10171       switch (Inner->getStmtClass()) {
10172         case Stmt::IntegerLiteralClass:
10173         case Stmt::FloatingLiteralClass:
10174         case Stmt::CharacterLiteralClass:
10175         case Stmt::ObjCBoolLiteralExprClass:
10176         case Stmt::CXXBoolLiteralExprClass:
10177           // "numeric literal"
10178           return LK_Numeric;
10179         case Stmt::ImplicitCastExprClass: {
10180           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10181           // Boolean literals can be represented by implicit casts.
10182           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10183             return LK_Numeric;
10184           break;
10185         }
10186         default:
10187           break;
10188       }
10189       return LK_Boxed;
10190     }
10191   }
10192   return LK_None;
10193 }
10194 
10195 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10196                                           ExprResult &LHS, ExprResult &RHS,
10197                                           BinaryOperator::Opcode Opc){
10198   Expr *Literal;
10199   Expr *Other;
10200   if (isObjCObjectLiteral(LHS)) {
10201     Literal = LHS.get();
10202     Other = RHS.get();
10203   } else {
10204     Literal = RHS.get();
10205     Other = LHS.get();
10206   }
10207 
10208   // Don't warn on comparisons against nil.
10209   Other = Other->IgnoreParenCasts();
10210   if (Other->isNullPointerConstant(S.getASTContext(),
10211                                    Expr::NPC_ValueDependentIsNotNull))
10212     return;
10213 
10214   // This should be kept in sync with warn_objc_literal_comparison.
10215   // LK_String should always be after the other literals, since it has its own
10216   // warning flag.
10217   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10218   assert(LiteralKind != Sema::LK_Block);
10219   if (LiteralKind == Sema::LK_None) {
10220     llvm_unreachable("Unknown Objective-C object literal kind");
10221   }
10222 
10223   if (LiteralKind == Sema::LK_String)
10224     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10225       << Literal->getSourceRange();
10226   else
10227     S.Diag(Loc, diag::warn_objc_literal_comparison)
10228       << LiteralKind << Literal->getSourceRange();
10229 
10230   if (BinaryOperator::isEqualityOp(Opc) &&
10231       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10232     SourceLocation Start = LHS.get()->getBeginLoc();
10233     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10234     CharSourceRange OpRange =
10235       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10236 
10237     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10238       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10239       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10240       << FixItHint::CreateInsertion(End, "]");
10241   }
10242 }
10243 
10244 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10245 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10246                                            ExprResult &RHS, SourceLocation Loc,
10247                                            BinaryOperatorKind Opc) {
10248   // Check that left hand side is !something.
10249   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10250   if (!UO || UO->getOpcode() != UO_LNot) return;
10251 
10252   // Only check if the right hand side is non-bool arithmetic type.
10253   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10254 
10255   // Make sure that the something in !something is not bool.
10256   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10257   if (SubExpr->isKnownToHaveBooleanValue()) return;
10258 
10259   // Emit warning.
10260   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10261   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10262       << Loc << IsBitwiseOp;
10263 
10264   // First note suggest !(x < y)
10265   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10266   SourceLocation FirstClose = RHS.get()->getEndLoc();
10267   FirstClose = S.getLocForEndOfToken(FirstClose);
10268   if (FirstClose.isInvalid())
10269     FirstOpen = SourceLocation();
10270   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10271       << IsBitwiseOp
10272       << FixItHint::CreateInsertion(FirstOpen, "(")
10273       << FixItHint::CreateInsertion(FirstClose, ")");
10274 
10275   // Second note suggests (!x) < y
10276   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10277   SourceLocation SecondClose = LHS.get()->getEndLoc();
10278   SecondClose = S.getLocForEndOfToken(SecondClose);
10279   if (SecondClose.isInvalid())
10280     SecondOpen = SourceLocation();
10281   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10282       << FixItHint::CreateInsertion(SecondOpen, "(")
10283       << FixItHint::CreateInsertion(SecondClose, ")");
10284 }
10285 
10286 // Returns true if E refers to a non-weak array.
10287 static bool checkForArray(const Expr *E) {
10288   const ValueDecl *D = nullptr;
10289   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10290     D = DR->getDecl();
10291   } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10292     if (Mem->isImplicitAccess())
10293       D = Mem->getMemberDecl();
10294   }
10295   if (!D)
10296     return false;
10297   return D->getType()->isArrayType() && !D->isWeak();
10298 }
10299 
10300 /// Diagnose some forms of syntactically-obvious tautological comparison.
10301 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10302                                            Expr *LHS, Expr *RHS,
10303                                            BinaryOperatorKind Opc) {
10304   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10305   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10306 
10307   QualType LHSType = LHS->getType();
10308   QualType RHSType = RHS->getType();
10309   if (LHSType->hasFloatingRepresentation() ||
10310       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10311       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10312       S.inTemplateInstantiation())
10313     return;
10314 
10315   // Comparisons between two array types are ill-formed for operator<=>, so
10316   // we shouldn't emit any additional warnings about it.
10317   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10318     return;
10319 
10320   // For non-floating point types, check for self-comparisons of the form
10321   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10322   // often indicate logic errors in the program.
10323   //
10324   // NOTE: Don't warn about comparison expressions resulting from macro
10325   // expansion. Also don't warn about comparisons which are only self
10326   // comparisons within a template instantiation. The warnings should catch
10327   // obvious cases in the definition of the template anyways. The idea is to
10328   // warn when the typed comparison operator will always evaluate to the same
10329   // result.
10330 
10331   // Used for indexing into %select in warn_comparison_always
10332   enum {
10333     AlwaysConstant,
10334     AlwaysTrue,
10335     AlwaysFalse,
10336     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10337   };
10338 
10339   if (Expr::isSameComparisonOperand(LHS, RHS)) {
10340     unsigned Result;
10341     switch (Opc) {
10342     case BO_EQ: case BO_LE: case BO_GE:
10343       Result = AlwaysTrue;
10344       break;
10345     case BO_NE: case BO_LT: case BO_GT:
10346       Result = AlwaysFalse;
10347       break;
10348     case BO_Cmp:
10349       Result = AlwaysEqual;
10350       break;
10351     default:
10352       Result = AlwaysConstant;
10353       break;
10354     }
10355     S.DiagRuntimeBehavior(Loc, nullptr,
10356                           S.PDiag(diag::warn_comparison_always)
10357                               << 0 /*self-comparison*/
10358                               << Result);
10359   } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10360     // What is it always going to evaluate to?
10361     unsigned Result;
10362     switch(Opc) {
10363     case BO_EQ: // e.g. array1 == array2
10364       Result = AlwaysFalse;
10365       break;
10366     case BO_NE: // e.g. array1 != array2
10367       Result = AlwaysTrue;
10368       break;
10369     default: // e.g. array1 <= array2
10370       // The best we can say is 'a constant'
10371       Result = AlwaysConstant;
10372       break;
10373     }
10374     S.DiagRuntimeBehavior(Loc, nullptr,
10375                           S.PDiag(diag::warn_comparison_always)
10376                               << 1 /*array comparison*/
10377                               << Result);
10378   }
10379 
10380   if (isa<CastExpr>(LHSStripped))
10381     LHSStripped = LHSStripped->IgnoreParenCasts();
10382   if (isa<CastExpr>(RHSStripped))
10383     RHSStripped = RHSStripped->IgnoreParenCasts();
10384 
10385   // Warn about comparisons against a string constant (unless the other
10386   // operand is null); the user probably wants strcmp.
10387   Expr *LiteralString = nullptr;
10388   Expr *LiteralStringStripped = nullptr;
10389   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10390       !RHSStripped->isNullPointerConstant(S.Context,
10391                                           Expr::NPC_ValueDependentIsNull)) {
10392     LiteralString = LHS;
10393     LiteralStringStripped = LHSStripped;
10394   } else if ((isa<StringLiteral>(RHSStripped) ||
10395               isa<ObjCEncodeExpr>(RHSStripped)) &&
10396              !LHSStripped->isNullPointerConstant(S.Context,
10397                                           Expr::NPC_ValueDependentIsNull)) {
10398     LiteralString = RHS;
10399     LiteralStringStripped = RHSStripped;
10400   }
10401 
10402   if (LiteralString) {
10403     S.DiagRuntimeBehavior(Loc, nullptr,
10404                           S.PDiag(diag::warn_stringcompare)
10405                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10406                               << LiteralString->getSourceRange());
10407   }
10408 }
10409 
10410 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10411   switch (CK) {
10412   default: {
10413 #ifndef NDEBUG
10414     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10415                  << "\n";
10416 #endif
10417     llvm_unreachable("unhandled cast kind");
10418   }
10419   case CK_UserDefinedConversion:
10420     return ICK_Identity;
10421   case CK_LValueToRValue:
10422     return ICK_Lvalue_To_Rvalue;
10423   case CK_ArrayToPointerDecay:
10424     return ICK_Array_To_Pointer;
10425   case CK_FunctionToPointerDecay:
10426     return ICK_Function_To_Pointer;
10427   case CK_IntegralCast:
10428     return ICK_Integral_Conversion;
10429   case CK_FloatingCast:
10430     return ICK_Floating_Conversion;
10431   case CK_IntegralToFloating:
10432   case CK_FloatingToIntegral:
10433     return ICK_Floating_Integral;
10434   case CK_IntegralComplexCast:
10435   case CK_FloatingComplexCast:
10436   case CK_FloatingComplexToIntegralComplex:
10437   case CK_IntegralComplexToFloatingComplex:
10438     return ICK_Complex_Conversion;
10439   case CK_FloatingComplexToReal:
10440   case CK_FloatingRealToComplex:
10441   case CK_IntegralComplexToReal:
10442   case CK_IntegralRealToComplex:
10443     return ICK_Complex_Real;
10444   }
10445 }
10446 
10447 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10448                                              QualType FromType,
10449                                              SourceLocation Loc) {
10450   // Check for a narrowing implicit conversion.
10451   StandardConversionSequence SCS;
10452   SCS.setAsIdentityConversion();
10453   SCS.setToType(0, FromType);
10454   SCS.setToType(1, ToType);
10455   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10456     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10457 
10458   APValue PreNarrowingValue;
10459   QualType PreNarrowingType;
10460   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10461                                PreNarrowingType,
10462                                /*IgnoreFloatToIntegralConversion*/ true)) {
10463   case NK_Dependent_Narrowing:
10464     // Implicit conversion to a narrower type, but the expression is
10465     // value-dependent so we can't tell whether it's actually narrowing.
10466   case NK_Not_Narrowing:
10467     return false;
10468 
10469   case NK_Constant_Narrowing:
10470     // Implicit conversion to a narrower type, and the value is not a constant
10471     // expression.
10472     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10473         << /*Constant*/ 1
10474         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10475     return true;
10476 
10477   case NK_Variable_Narrowing:
10478     // Implicit conversion to a narrower type, and the value is not a constant
10479     // expression.
10480   case NK_Type_Narrowing:
10481     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10482         << /*Constant*/ 0 << FromType << ToType;
10483     // TODO: It's not a constant expression, but what if the user intended it
10484     // to be? Can we produce notes to help them figure out why it isn't?
10485     return true;
10486   }
10487   llvm_unreachable("unhandled case in switch");
10488 }
10489 
10490 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10491                                                          ExprResult &LHS,
10492                                                          ExprResult &RHS,
10493                                                          SourceLocation Loc) {
10494   using CCT = ComparisonCategoryType;
10495 
10496   QualType LHSType = LHS.get()->getType();
10497   QualType RHSType = RHS.get()->getType();
10498   // Dig out the original argument type and expression before implicit casts
10499   // were applied. These are the types/expressions we need to check the
10500   // [expr.spaceship] requirements against.
10501   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10502   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10503   QualType LHSStrippedType = LHSStripped.get()->getType();
10504   QualType RHSStrippedType = RHSStripped.get()->getType();
10505 
10506   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10507   // other is not, the program is ill-formed.
10508   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10509     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10510     return QualType();
10511   }
10512 
10513   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10514                     RHSStrippedType->isEnumeralType();
10515   if (NumEnumArgs == 1) {
10516     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10517     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10518     if (OtherTy->hasFloatingRepresentation()) {
10519       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10520       return QualType();
10521     }
10522   }
10523   if (NumEnumArgs == 2) {
10524     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10525     // type E, the operator yields the result of converting the operands
10526     // to the underlying type of E and applying <=> to the converted operands.
10527     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10528       S.InvalidOperands(Loc, LHS, RHS);
10529       return QualType();
10530     }
10531     QualType IntType =
10532         LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10533     assert(IntType->isArithmeticType());
10534 
10535     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10536     // promote the boolean type, and all other promotable integer types, to
10537     // avoid this.
10538     if (IntType->isPromotableIntegerType())
10539       IntType = S.Context.getPromotedIntegerType(IntType);
10540 
10541     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10542     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10543     LHSType = RHSType = IntType;
10544   }
10545 
10546   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10547   // usual arithmetic conversions are applied to the operands.
10548   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10549   if (LHS.isInvalid() || RHS.isInvalid())
10550     return QualType();
10551   if (Type.isNull())
10552     return S.InvalidOperands(Loc, LHS, RHS);
10553   assert(Type->isArithmeticType() || Type->isEnumeralType());
10554 
10555   bool HasNarrowing = checkThreeWayNarrowingConversion(
10556       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10557   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10558                                                    RHS.get()->getBeginLoc());
10559   if (HasNarrowing)
10560     return QualType();
10561 
10562   assert(!Type.isNull() && "composite type for <=> has not been set");
10563 
10564   auto TypeKind = [&]() {
10565     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10566       if (CT->getElementType()->hasFloatingRepresentation())
10567         return CCT::WeakEquality;
10568       return CCT::StrongEquality;
10569     }
10570     if (Type->isIntegralOrEnumerationType())
10571       return CCT::StrongOrdering;
10572     if (Type->hasFloatingRepresentation())
10573       return CCT::PartialOrdering;
10574     llvm_unreachable("other types are unimplemented");
10575   }();
10576 
10577   return S.CheckComparisonCategoryType(TypeKind, Loc);
10578 }
10579 
10580 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10581                                                  ExprResult &RHS,
10582                                                  SourceLocation Loc,
10583                                                  BinaryOperatorKind Opc) {
10584   if (Opc == BO_Cmp)
10585     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10586 
10587   // C99 6.5.8p3 / C99 6.5.9p4
10588   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10589   if (LHS.isInvalid() || RHS.isInvalid())
10590     return QualType();
10591   if (Type.isNull())
10592     return S.InvalidOperands(Loc, LHS, RHS);
10593   assert(Type->isArithmeticType() || Type->isEnumeralType());
10594 
10595   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10596 
10597   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10598     return S.InvalidOperands(Loc, LHS, RHS);
10599 
10600   // Check for comparisons of floating point operands using != and ==.
10601   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10602     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10603 
10604   // The result of comparisons is 'bool' in C++, 'int' in C.
10605   return S.Context.getLogicalOperationType();
10606 }
10607 
10608 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10609   if (!NullE.get()->getType()->isAnyPointerType())
10610     return;
10611   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10612   if (!E.get()->getType()->isAnyPointerType() &&
10613       E.get()->isNullPointerConstant(Context,
10614                                      Expr::NPC_ValueDependentIsNotNull) ==
10615         Expr::NPCK_ZeroExpression) {
10616     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10617       if (CL->getValue() == 0)
10618         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10619             << NullValue
10620             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10621                                             NullValue ? "NULL" : "(void *)0");
10622     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10623         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10624         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10625         if (T == Context.CharTy)
10626           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10627               << NullValue
10628               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10629                                               NullValue ? "NULL" : "(void *)0");
10630       }
10631   }
10632 }
10633 
10634 // C99 6.5.8, C++ [expr.rel]
10635 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10636                                     SourceLocation Loc,
10637                                     BinaryOperatorKind Opc) {
10638   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10639   bool IsThreeWay = Opc == BO_Cmp;
10640   auto IsAnyPointerType = [](ExprResult E) {
10641     QualType Ty = E.get()->getType();
10642     return Ty->isPointerType() || Ty->isMemberPointerType();
10643   };
10644 
10645   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10646   // type, array-to-pointer, ..., conversions are performed on both operands to
10647   // bring them to their composite type.
10648   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10649   // any type-related checks.
10650   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10651     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10652     if (LHS.isInvalid())
10653       return QualType();
10654     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10655     if (RHS.isInvalid())
10656       return QualType();
10657   } else {
10658     LHS = DefaultLvalueConversion(LHS.get());
10659     if (LHS.isInvalid())
10660       return QualType();
10661     RHS = DefaultLvalueConversion(RHS.get());
10662     if (RHS.isInvalid())
10663       return QualType();
10664   }
10665 
10666   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10667   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10668     CheckPtrComparisonWithNullChar(LHS, RHS);
10669     CheckPtrComparisonWithNullChar(RHS, LHS);
10670   }
10671 
10672   // Handle vector comparisons separately.
10673   if (LHS.get()->getType()->isVectorType() ||
10674       RHS.get()->getType()->isVectorType())
10675     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10676 
10677   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10678   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10679 
10680   QualType LHSType = LHS.get()->getType();
10681   QualType RHSType = RHS.get()->getType();
10682   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10683       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10684     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10685 
10686   const Expr::NullPointerConstantKind LHSNullKind =
10687       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10688   const Expr::NullPointerConstantKind RHSNullKind =
10689       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10690   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10691   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10692 
10693   auto computeResultTy = [&]() {
10694     if (Opc != BO_Cmp)
10695       return Context.getLogicalOperationType();
10696     assert(getLangOpts().CPlusPlus);
10697     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10698 
10699     QualType CompositeTy = LHS.get()->getType();
10700     assert(!CompositeTy->isReferenceType());
10701 
10702     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10703       return CheckComparisonCategoryType(Kind, Loc);
10704     };
10705 
10706     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10707     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10708     // result is of type std::strong_equality
10709     if (CompositeTy->isFunctionPointerType() ||
10710         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10711       // FIXME: consider making the function pointer case produce
10712       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10713       // and direction polls
10714       return buildResultTy(ComparisonCategoryType::StrongEquality);
10715 
10716     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10717     // pointer type, p <=> q is of type std::strong_ordering.
10718     if (CompositeTy->isPointerType()) {
10719       // P0946R0: Comparisons between a null pointer constant and an object
10720       // pointer result in std::strong_equality
10721       if (LHSIsNull != RHSIsNull)
10722         return buildResultTy(ComparisonCategoryType::StrongEquality);
10723       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10724     }
10725     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10726     // TODO: Extend support for operator<=> to ObjC types.
10727     return InvalidOperands(Loc, LHS, RHS);
10728   };
10729 
10730 
10731   if (!IsRelational && LHSIsNull != RHSIsNull) {
10732     bool IsEquality = Opc == BO_EQ;
10733     if (RHSIsNull)
10734       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10735                                    RHS.get()->getSourceRange());
10736     else
10737       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10738                                    LHS.get()->getSourceRange());
10739   }
10740 
10741   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10742       (RHSType->isIntegerType() && !RHSIsNull)) {
10743     // Skip normal pointer conversion checks in this case; we have better
10744     // diagnostics for this below.
10745   } else if (getLangOpts().CPlusPlus) {
10746     // Equality comparison of a function pointer to a void pointer is invalid,
10747     // but we allow it as an extension.
10748     // FIXME: If we really want to allow this, should it be part of composite
10749     // pointer type computation so it works in conditionals too?
10750     if (!IsRelational &&
10751         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10752          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10753       // This is a gcc extension compatibility comparison.
10754       // In a SFINAE context, we treat this as a hard error to maintain
10755       // conformance with the C++ standard.
10756       diagnoseFunctionPointerToVoidComparison(
10757           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10758 
10759       if (isSFINAEContext())
10760         return QualType();
10761 
10762       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10763       return computeResultTy();
10764     }
10765 
10766     // C++ [expr.eq]p2:
10767     //   If at least one operand is a pointer [...] bring them to their
10768     //   composite pointer type.
10769     // C++ [expr.spaceship]p6
10770     //  If at least one of the operands is of pointer type, [...] bring them
10771     //  to their composite pointer type.
10772     // C++ [expr.rel]p2:
10773     //   If both operands are pointers, [...] bring them to their composite
10774     //   pointer type.
10775     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10776             (IsRelational ? 2 : 1) &&
10777         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10778                                          RHSType->isObjCObjectPointerType()))) {
10779       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10780         return QualType();
10781       return computeResultTy();
10782     }
10783   } else if (LHSType->isPointerType() &&
10784              RHSType->isPointerType()) { // C99 6.5.8p2
10785     // All of the following pointer-related warnings are GCC extensions, except
10786     // when handling null pointer constants.
10787     QualType LCanPointeeTy =
10788       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10789     QualType RCanPointeeTy =
10790       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10791 
10792     // C99 6.5.9p2 and C99 6.5.8p2
10793     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10794                                    RCanPointeeTy.getUnqualifiedType())) {
10795       // Valid unless a relational comparison of function pointers
10796       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10797         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10798           << LHSType << RHSType << LHS.get()->getSourceRange()
10799           << RHS.get()->getSourceRange();
10800       }
10801     } else if (!IsRelational &&
10802                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10803       // Valid unless comparison between non-null pointer and function pointer
10804       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10805           && !LHSIsNull && !RHSIsNull)
10806         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10807                                                 /*isError*/false);
10808     } else {
10809       // Invalid
10810       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10811     }
10812     if (LCanPointeeTy != RCanPointeeTy) {
10813       // Treat NULL constant as a special case in OpenCL.
10814       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10815         const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10816         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10817           Diag(Loc,
10818                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10819               << LHSType << RHSType << 0 /* comparison */
10820               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10821         }
10822       }
10823       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10824       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10825       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10826                                                : CK_BitCast;
10827       if (LHSIsNull && !RHSIsNull)
10828         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10829       else
10830         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10831     }
10832     return computeResultTy();
10833   }
10834 
10835   if (getLangOpts().CPlusPlus) {
10836     // C++ [expr.eq]p4:
10837     //   Two operands of type std::nullptr_t or one operand of type
10838     //   std::nullptr_t and the other a null pointer constant compare equal.
10839     if (!IsRelational && LHSIsNull && RHSIsNull) {
10840       if (LHSType->isNullPtrType()) {
10841         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10842         return computeResultTy();
10843       }
10844       if (RHSType->isNullPtrType()) {
10845         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10846         return computeResultTy();
10847       }
10848     }
10849 
10850     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10851     // These aren't covered by the composite pointer type rules.
10852     if (!IsRelational && RHSType->isNullPtrType() &&
10853         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10854       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10855       return computeResultTy();
10856     }
10857     if (!IsRelational && LHSType->isNullPtrType() &&
10858         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10859       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10860       return computeResultTy();
10861     }
10862 
10863     if (IsRelational &&
10864         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10865          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10866       // HACK: Relational comparison of nullptr_t against a pointer type is
10867       // invalid per DR583, but we allow it within std::less<> and friends,
10868       // since otherwise common uses of it break.
10869       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10870       // friends to have std::nullptr_t overload candidates.
10871       DeclContext *DC = CurContext;
10872       if (isa<FunctionDecl>(DC))
10873         DC = DC->getParent();
10874       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10875         if (CTSD->isInStdNamespace() &&
10876             llvm::StringSwitch<bool>(CTSD->getName())
10877                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10878                 .Default(false)) {
10879           if (RHSType->isNullPtrType())
10880             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10881           else
10882             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10883           return computeResultTy();
10884         }
10885       }
10886     }
10887 
10888     // C++ [expr.eq]p2:
10889     //   If at least one operand is a pointer to member, [...] bring them to
10890     //   their composite pointer type.
10891     if (!IsRelational &&
10892         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10893       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10894         return QualType();
10895       else
10896         return computeResultTy();
10897     }
10898   }
10899 
10900   // Handle block pointer types.
10901   if (!IsRelational && LHSType->isBlockPointerType() &&
10902       RHSType->isBlockPointerType()) {
10903     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10904     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10905 
10906     if (!LHSIsNull && !RHSIsNull &&
10907         !Context.typesAreCompatible(lpointee, rpointee)) {
10908       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10909         << LHSType << RHSType << LHS.get()->getSourceRange()
10910         << RHS.get()->getSourceRange();
10911     }
10912     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10913     return computeResultTy();
10914   }
10915 
10916   // Allow block pointers to be compared with null pointer constants.
10917   if (!IsRelational
10918       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10919           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10920     if (!LHSIsNull && !RHSIsNull) {
10921       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10922              ->getPointeeType()->isVoidType())
10923             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10924                 ->getPointeeType()->isVoidType())))
10925         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10926           << LHSType << RHSType << LHS.get()->getSourceRange()
10927           << RHS.get()->getSourceRange();
10928     }
10929     if (LHSIsNull && !RHSIsNull)
10930       LHS = ImpCastExprToType(LHS.get(), RHSType,
10931                               RHSType->isPointerType() ? CK_BitCast
10932                                 : CK_AnyPointerToBlockPointerCast);
10933     else
10934       RHS = ImpCastExprToType(RHS.get(), LHSType,
10935                               LHSType->isPointerType() ? CK_BitCast
10936                                 : CK_AnyPointerToBlockPointerCast);
10937     return computeResultTy();
10938   }
10939 
10940   if (LHSType->isObjCObjectPointerType() ||
10941       RHSType->isObjCObjectPointerType()) {
10942     const PointerType *LPT = LHSType->getAs<PointerType>();
10943     const PointerType *RPT = RHSType->getAs<PointerType>();
10944     if (LPT || RPT) {
10945       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10946       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10947 
10948       if (!LPtrToVoid && !RPtrToVoid &&
10949           !Context.typesAreCompatible(LHSType, RHSType)) {
10950         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10951                                           /*isError*/false);
10952       }
10953       if (LHSIsNull && !RHSIsNull) {
10954         Expr *E = LHS.get();
10955         if (getLangOpts().ObjCAutoRefCount)
10956           CheckObjCConversion(SourceRange(), RHSType, E,
10957                               CCK_ImplicitConversion);
10958         LHS = ImpCastExprToType(E, RHSType,
10959                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10960       }
10961       else {
10962         Expr *E = RHS.get();
10963         if (getLangOpts().ObjCAutoRefCount)
10964           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10965                               /*Diagnose=*/true,
10966                               /*DiagnoseCFAudited=*/false, Opc);
10967         RHS = ImpCastExprToType(E, LHSType,
10968                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10969       }
10970       return computeResultTy();
10971     }
10972     if (LHSType->isObjCObjectPointerType() &&
10973         RHSType->isObjCObjectPointerType()) {
10974       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10975         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10976                                           /*isError*/false);
10977       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10978         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10979 
10980       if (LHSIsNull && !RHSIsNull)
10981         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10982       else
10983         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10984       return computeResultTy();
10985     }
10986 
10987     if (!IsRelational && LHSType->isBlockPointerType() &&
10988         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10989       LHS = ImpCastExprToType(LHS.get(), RHSType,
10990                               CK_BlockPointerToObjCPointerCast);
10991       return computeResultTy();
10992     } else if (!IsRelational &&
10993                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10994                RHSType->isBlockPointerType()) {
10995       RHS = ImpCastExprToType(RHS.get(), LHSType,
10996                               CK_BlockPointerToObjCPointerCast);
10997       return computeResultTy();
10998     }
10999   }
11000   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11001       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11002     unsigned DiagID = 0;
11003     bool isError = false;
11004     if (LangOpts.DebuggerSupport) {
11005       // Under a debugger, allow the comparison of pointers to integers,
11006       // since users tend to want to compare addresses.
11007     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11008                (RHSIsNull && RHSType->isIntegerType())) {
11009       if (IsRelational) {
11010         isError = getLangOpts().CPlusPlus;
11011         DiagID =
11012           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11013                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11014       }
11015     } else if (getLangOpts().CPlusPlus) {
11016       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11017       isError = true;
11018     } else if (IsRelational)
11019       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11020     else
11021       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11022 
11023     if (DiagID) {
11024       Diag(Loc, DiagID)
11025         << LHSType << RHSType << LHS.get()->getSourceRange()
11026         << RHS.get()->getSourceRange();
11027       if (isError)
11028         return QualType();
11029     }
11030 
11031     if (LHSType->isIntegerType())
11032       LHS = ImpCastExprToType(LHS.get(), RHSType,
11033                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11034     else
11035       RHS = ImpCastExprToType(RHS.get(), LHSType,
11036                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11037     return computeResultTy();
11038   }
11039 
11040   // Handle block pointers.
11041   if (!IsRelational && RHSIsNull
11042       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11043     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11044     return computeResultTy();
11045   }
11046   if (!IsRelational && LHSIsNull
11047       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11048     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11049     return computeResultTy();
11050   }
11051 
11052   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11053     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11054       return computeResultTy();
11055     }
11056 
11057     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11058       return computeResultTy();
11059     }
11060 
11061     if (LHSIsNull && RHSType->isQueueT()) {
11062       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11063       return computeResultTy();
11064     }
11065 
11066     if (LHSType->isQueueT() && RHSIsNull) {
11067       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11068       return computeResultTy();
11069     }
11070   }
11071 
11072   return InvalidOperands(Loc, LHS, RHS);
11073 }
11074 
11075 // Return a signed ext_vector_type that is of identical size and number of
11076 // elements. For floating point vectors, return an integer type of identical
11077 // size and number of elements. In the non ext_vector_type case, search from
11078 // the largest type to the smallest type to avoid cases where long long == long,
11079 // where long gets picked over long long.
11080 QualType Sema::GetSignedVectorType(QualType V) {
11081   const VectorType *VTy = V->castAs<VectorType>();
11082   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11083 
11084   if (isa<ExtVectorType>(VTy)) {
11085     if (TypeSize == Context.getTypeSize(Context.CharTy))
11086       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11087     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11088       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11089     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11090       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11091     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11092       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11093     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11094            "Unhandled vector element size in vector compare");
11095     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11096   }
11097 
11098   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11099     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11100                                  VectorType::GenericVector);
11101   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11102     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11103                                  VectorType::GenericVector);
11104   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11105     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11106                                  VectorType::GenericVector);
11107   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11108     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11109                                  VectorType::GenericVector);
11110   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11111          "Unhandled vector element size in vector compare");
11112   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11113                                VectorType::GenericVector);
11114 }
11115 
11116 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11117 /// operates on extended vector types.  Instead of producing an IntTy result,
11118 /// like a scalar comparison, a vector comparison produces a vector of integer
11119 /// types.
11120 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11121                                           SourceLocation Loc,
11122                                           BinaryOperatorKind Opc) {
11123   // Check to make sure we're operating on vectors of the same type and width,
11124   // Allowing one side to be a scalar of element type.
11125   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11126                               /*AllowBothBool*/true,
11127                               /*AllowBoolConversions*/getLangOpts().ZVector);
11128   if (vType.isNull())
11129     return vType;
11130 
11131   QualType LHSType = LHS.get()->getType();
11132 
11133   // If AltiVec, the comparison results in a numeric type, i.e.
11134   // bool for C++, int for C
11135   if (getLangOpts().AltiVec &&
11136       vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11137     return Context.getLogicalOperationType();
11138 
11139   // For non-floating point types, check for self-comparisons of the form
11140   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11141   // often indicate logic errors in the program.
11142   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11143 
11144   // Check for comparisons of floating point operands using != and ==.
11145   if (BinaryOperator::isEqualityOp(Opc) &&
11146       LHSType->hasFloatingRepresentation()) {
11147     assert(RHS.get()->getType()->hasFloatingRepresentation());
11148     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11149   }
11150 
11151   // Return a signed type for the vector.
11152   return GetSignedVectorType(vType);
11153 }
11154 
11155 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11156                                     const ExprResult &XorRHS,
11157                                     const SourceLocation Loc) {
11158   // Do not diagnose macros.
11159   if (Loc.isMacroID())
11160     return;
11161 
11162   bool Negative = false;
11163   bool ExplicitPlus = false;
11164   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11165   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11166 
11167   if (!LHSInt)
11168     return;
11169   if (!RHSInt) {
11170     // Check negative literals.
11171     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11172       UnaryOperatorKind Opc = UO->getOpcode();
11173       if (Opc != UO_Minus && Opc != UO_Plus)
11174         return;
11175       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11176       if (!RHSInt)
11177         return;
11178       Negative = (Opc == UO_Minus);
11179       ExplicitPlus = !Negative;
11180     } else {
11181       return;
11182     }
11183   }
11184 
11185   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11186   llvm::APInt RightSideValue = RHSInt->getValue();
11187   if (LeftSideValue != 2 && LeftSideValue != 10)
11188     return;
11189 
11190   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11191     return;
11192 
11193   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11194       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11195   llvm::StringRef ExprStr =
11196       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11197 
11198   CharSourceRange XorRange =
11199       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11200   llvm::StringRef XorStr =
11201       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11202   // Do not diagnose if xor keyword/macro is used.
11203   if (XorStr == "xor")
11204     return;
11205 
11206   std::string LHSStr = Lexer::getSourceText(
11207       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11208       S.getSourceManager(), S.getLangOpts());
11209   std::string RHSStr = Lexer::getSourceText(
11210       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11211       S.getSourceManager(), S.getLangOpts());
11212 
11213   if (Negative) {
11214     RightSideValue = -RightSideValue;
11215     RHSStr = "-" + RHSStr;
11216   } else if (ExplicitPlus) {
11217     RHSStr = "+" + RHSStr;
11218   }
11219 
11220   StringRef LHSStrRef = LHSStr;
11221   StringRef RHSStrRef = RHSStr;
11222   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11223   // literals.
11224   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11225       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11226       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11227       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11228       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11229       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11230       LHSStrRef.find('\'') != StringRef::npos ||
11231       RHSStrRef.find('\'') != StringRef::npos)
11232     return;
11233 
11234   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11235   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11236   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11237   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11238     std::string SuggestedExpr = "1 << " + RHSStr;
11239     bool Overflow = false;
11240     llvm::APInt One = (LeftSideValue - 1);
11241     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11242     if (Overflow) {
11243       if (RightSideIntValue < 64)
11244         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11245             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11246             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11247       else if (RightSideIntValue == 64)
11248         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11249       else
11250         return;
11251     } else {
11252       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11253           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11254           << PowValue.toString(10, true)
11255           << FixItHint::CreateReplacement(
11256                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11257     }
11258 
11259     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11260   } else if (LeftSideValue == 10) {
11261     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11262     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11263         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11264         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11265     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11266   }
11267 }
11268 
11269 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11270                                           SourceLocation Loc) {
11271   // Ensure that either both operands are of the same vector type, or
11272   // one operand is of a vector type and the other is of its element type.
11273   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11274                                        /*AllowBothBool*/true,
11275                                        /*AllowBoolConversions*/false);
11276   if (vType.isNull())
11277     return InvalidOperands(Loc, LHS, RHS);
11278   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11279       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11280     return InvalidOperands(Loc, LHS, RHS);
11281   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11282   //        usage of the logical operators && and || with vectors in C. This
11283   //        check could be notionally dropped.
11284   if (!getLangOpts().CPlusPlus &&
11285       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11286     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11287 
11288   return GetSignedVectorType(LHS.get()->getType());
11289 }
11290 
11291 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11292                                            SourceLocation Loc,
11293                                            BinaryOperatorKind Opc) {
11294   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11295 
11296   bool IsCompAssign =
11297       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11298 
11299   if (LHS.get()->getType()->isVectorType() ||
11300       RHS.get()->getType()->isVectorType()) {
11301     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11302         RHS.get()->getType()->hasIntegerRepresentation())
11303       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11304                         /*AllowBothBool*/true,
11305                         /*AllowBoolConversions*/getLangOpts().ZVector);
11306     return InvalidOperands(Loc, LHS, RHS);
11307   }
11308 
11309   if (Opc == BO_And)
11310     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11311 
11312   ExprResult LHSResult = LHS, RHSResult = RHS;
11313   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
11314                                                  IsCompAssign);
11315   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11316     return QualType();
11317   LHS = LHSResult.get();
11318   RHS = RHSResult.get();
11319 
11320   if (Opc == BO_Xor)
11321     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11322 
11323   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11324     return compType;
11325   return InvalidOperands(Loc, LHS, RHS);
11326 }
11327 
11328 // C99 6.5.[13,14]
11329 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11330                                            SourceLocation Loc,
11331                                            BinaryOperatorKind Opc) {
11332   // Check vector operands differently.
11333   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11334     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11335 
11336   bool EnumConstantInBoolContext = false;
11337   for (const ExprResult &HS : {LHS, RHS}) {
11338     if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11339       const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11340       if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11341         EnumConstantInBoolContext = true;
11342     }
11343   }
11344 
11345   if (EnumConstantInBoolContext)
11346     Diag(Loc, diag::warn_enum_constant_in_bool_context);
11347 
11348   // Diagnose cases where the user write a logical and/or but probably meant a
11349   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11350   // is a constant.
11351   if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11352       !LHS.get()->getType()->isBooleanType() &&
11353       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11354       // Don't warn in macros or template instantiations.
11355       !Loc.isMacroID() && !inTemplateInstantiation()) {
11356     // If the RHS can be constant folded, and if it constant folds to something
11357     // that isn't 0 or 1 (which indicate a potential logical operation that
11358     // happened to fold to true/false) then warn.
11359     // Parens on the RHS are ignored.
11360     Expr::EvalResult EVResult;
11361     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11362       llvm::APSInt Result = EVResult.Val.getInt();
11363       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11364            !RHS.get()->getExprLoc().isMacroID()) ||
11365           (Result != 0 && Result != 1)) {
11366         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11367           << RHS.get()->getSourceRange()
11368           << (Opc == BO_LAnd ? "&&" : "||");
11369         // Suggest replacing the logical operator with the bitwise version
11370         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11371             << (Opc == BO_LAnd ? "&" : "|")
11372             << FixItHint::CreateReplacement(SourceRange(
11373                                                  Loc, getLocForEndOfToken(Loc)),
11374                                             Opc == BO_LAnd ? "&" : "|");
11375         if (Opc == BO_LAnd)
11376           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11377           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11378               << FixItHint::CreateRemoval(
11379                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11380                                  RHS.get()->getEndLoc()));
11381       }
11382     }
11383   }
11384 
11385   if (!Context.getLangOpts().CPlusPlus) {
11386     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11387     // not operate on the built-in scalar and vector float types.
11388     if (Context.getLangOpts().OpenCL &&
11389         Context.getLangOpts().OpenCLVersion < 120) {
11390       if (LHS.get()->getType()->isFloatingType() ||
11391           RHS.get()->getType()->isFloatingType())
11392         return InvalidOperands(Loc, LHS, RHS);
11393     }
11394 
11395     LHS = UsualUnaryConversions(LHS.get());
11396     if (LHS.isInvalid())
11397       return QualType();
11398 
11399     RHS = UsualUnaryConversions(RHS.get());
11400     if (RHS.isInvalid())
11401       return QualType();
11402 
11403     if (!LHS.get()->getType()->isScalarType() ||
11404         !RHS.get()->getType()->isScalarType())
11405       return InvalidOperands(Loc, LHS, RHS);
11406 
11407     return Context.IntTy;
11408   }
11409 
11410   // The following is safe because we only use this method for
11411   // non-overloadable operands.
11412 
11413   // C++ [expr.log.and]p1
11414   // C++ [expr.log.or]p1
11415   // The operands are both contextually converted to type bool.
11416   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11417   if (LHSRes.isInvalid())
11418     return InvalidOperands(Loc, LHS, RHS);
11419   LHS = LHSRes;
11420 
11421   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11422   if (RHSRes.isInvalid())
11423     return InvalidOperands(Loc, LHS, RHS);
11424   RHS = RHSRes;
11425 
11426   // C++ [expr.log.and]p2
11427   // C++ [expr.log.or]p2
11428   // The result is a bool.
11429   return Context.BoolTy;
11430 }
11431 
11432 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11433   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11434   if (!ME) return false;
11435   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11436   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11437       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11438   if (!Base) return false;
11439   return Base->getMethodDecl() != nullptr;
11440 }
11441 
11442 /// Is the given expression (which must be 'const') a reference to a
11443 /// variable which was originally non-const, but which has become
11444 /// 'const' due to being captured within a block?
11445 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11446 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11447   assert(E->isLValue() && E->getType().isConstQualified());
11448   E = E->IgnoreParens();
11449 
11450   // Must be a reference to a declaration from an enclosing scope.
11451   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11452   if (!DRE) return NCCK_None;
11453   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11454 
11455   // The declaration must be a variable which is not declared 'const'.
11456   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11457   if (!var) return NCCK_None;
11458   if (var->getType().isConstQualified()) return NCCK_None;
11459   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11460 
11461   // Decide whether the first capture was for a block or a lambda.
11462   DeclContext *DC = S.CurContext, *Prev = nullptr;
11463   // Decide whether the first capture was for a block or a lambda.
11464   while (DC) {
11465     // For init-capture, it is possible that the variable belongs to the
11466     // template pattern of the current context.
11467     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11468       if (var->isInitCapture() &&
11469           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11470         break;
11471     if (DC == var->getDeclContext())
11472       break;
11473     Prev = DC;
11474     DC = DC->getParent();
11475   }
11476   // Unless we have an init-capture, we've gone one step too far.
11477   if (!var->isInitCapture())
11478     DC = Prev;
11479   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11480 }
11481 
11482 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11483   Ty = Ty.getNonReferenceType();
11484   if (IsDereference && Ty->isPointerType())
11485     Ty = Ty->getPointeeType();
11486   return !Ty.isConstQualified();
11487 }
11488 
11489 // Update err_typecheck_assign_const and note_typecheck_assign_const
11490 // when this enum is changed.
11491 enum {
11492   ConstFunction,
11493   ConstVariable,
11494   ConstMember,
11495   ConstMethod,
11496   NestedConstMember,
11497   ConstUnknown,  // Keep as last element
11498 };
11499 
11500 /// Emit the "read-only variable not assignable" error and print notes to give
11501 /// more information about why the variable is not assignable, such as pointing
11502 /// to the declaration of a const variable, showing that a method is const, or
11503 /// that the function is returning a const reference.
11504 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11505                                     SourceLocation Loc) {
11506   SourceRange ExprRange = E->getSourceRange();
11507 
11508   // Only emit one error on the first const found.  All other consts will emit
11509   // a note to the error.
11510   bool DiagnosticEmitted = false;
11511 
11512   // Track if the current expression is the result of a dereference, and if the
11513   // next checked expression is the result of a dereference.
11514   bool IsDereference = false;
11515   bool NextIsDereference = false;
11516 
11517   // Loop to process MemberExpr chains.
11518   while (true) {
11519     IsDereference = NextIsDereference;
11520 
11521     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11522     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11523       NextIsDereference = ME->isArrow();
11524       const ValueDecl *VD = ME->getMemberDecl();
11525       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11526         // Mutable fields can be modified even if the class is const.
11527         if (Field->isMutable()) {
11528           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11529           break;
11530         }
11531 
11532         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11533           if (!DiagnosticEmitted) {
11534             S.Diag(Loc, diag::err_typecheck_assign_const)
11535                 << ExprRange << ConstMember << false /*static*/ << Field
11536                 << Field->getType();
11537             DiagnosticEmitted = true;
11538           }
11539           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11540               << ConstMember << false /*static*/ << Field << Field->getType()
11541               << Field->getSourceRange();
11542         }
11543         E = ME->getBase();
11544         continue;
11545       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11546         if (VDecl->getType().isConstQualified()) {
11547           if (!DiagnosticEmitted) {
11548             S.Diag(Loc, diag::err_typecheck_assign_const)
11549                 << ExprRange << ConstMember << true /*static*/ << VDecl
11550                 << VDecl->getType();
11551             DiagnosticEmitted = true;
11552           }
11553           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11554               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11555               << VDecl->getSourceRange();
11556         }
11557         // Static fields do not inherit constness from parents.
11558         break;
11559       }
11560       break; // End MemberExpr
11561     } else if (const ArraySubscriptExpr *ASE =
11562                    dyn_cast<ArraySubscriptExpr>(E)) {
11563       E = ASE->getBase()->IgnoreParenImpCasts();
11564       continue;
11565     } else if (const ExtVectorElementExpr *EVE =
11566                    dyn_cast<ExtVectorElementExpr>(E)) {
11567       E = EVE->getBase()->IgnoreParenImpCasts();
11568       continue;
11569     }
11570     break;
11571   }
11572 
11573   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11574     // Function calls
11575     const FunctionDecl *FD = CE->getDirectCallee();
11576     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11577       if (!DiagnosticEmitted) {
11578         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11579                                                       << ConstFunction << FD;
11580         DiagnosticEmitted = true;
11581       }
11582       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11583              diag::note_typecheck_assign_const)
11584           << ConstFunction << FD << FD->getReturnType()
11585           << FD->getReturnTypeSourceRange();
11586     }
11587   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11588     // Point to variable declaration.
11589     if (const ValueDecl *VD = DRE->getDecl()) {
11590       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11591         if (!DiagnosticEmitted) {
11592           S.Diag(Loc, diag::err_typecheck_assign_const)
11593               << ExprRange << ConstVariable << VD << VD->getType();
11594           DiagnosticEmitted = true;
11595         }
11596         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11597             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11598       }
11599     }
11600   } else if (isa<CXXThisExpr>(E)) {
11601     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11602       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11603         if (MD->isConst()) {
11604           if (!DiagnosticEmitted) {
11605             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11606                                                           << ConstMethod << MD;
11607             DiagnosticEmitted = true;
11608           }
11609           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11610               << ConstMethod << MD << MD->getSourceRange();
11611         }
11612       }
11613     }
11614   }
11615 
11616   if (DiagnosticEmitted)
11617     return;
11618 
11619   // Can't determine a more specific message, so display the generic error.
11620   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11621 }
11622 
11623 enum OriginalExprKind {
11624   OEK_Variable,
11625   OEK_Member,
11626   OEK_LValue
11627 };
11628 
11629 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11630                                          const RecordType *Ty,
11631                                          SourceLocation Loc, SourceRange Range,
11632                                          OriginalExprKind OEK,
11633                                          bool &DiagnosticEmitted) {
11634   std::vector<const RecordType *> RecordTypeList;
11635   RecordTypeList.push_back(Ty);
11636   unsigned NextToCheckIndex = 0;
11637   // We walk the record hierarchy breadth-first to ensure that we print
11638   // diagnostics in field nesting order.
11639   while (RecordTypeList.size() > NextToCheckIndex) {
11640     bool IsNested = NextToCheckIndex > 0;
11641     for (const FieldDecl *Field :
11642          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11643       // First, check every field for constness.
11644       QualType FieldTy = Field->getType();
11645       if (FieldTy.isConstQualified()) {
11646         if (!DiagnosticEmitted) {
11647           S.Diag(Loc, diag::err_typecheck_assign_const)
11648               << Range << NestedConstMember << OEK << VD
11649               << IsNested << Field;
11650           DiagnosticEmitted = true;
11651         }
11652         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11653             << NestedConstMember << IsNested << Field
11654             << FieldTy << Field->getSourceRange();
11655       }
11656 
11657       // Then we append it to the list to check next in order.
11658       FieldTy = FieldTy.getCanonicalType();
11659       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11660         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11661           RecordTypeList.push_back(FieldRecTy);
11662       }
11663     }
11664     ++NextToCheckIndex;
11665   }
11666 }
11667 
11668 /// Emit an error for the case where a record we are trying to assign to has a
11669 /// const-qualified field somewhere in its hierarchy.
11670 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11671                                          SourceLocation Loc) {
11672   QualType Ty = E->getType();
11673   assert(Ty->isRecordType() && "lvalue was not record?");
11674   SourceRange Range = E->getSourceRange();
11675   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11676   bool DiagEmitted = false;
11677 
11678   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11679     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11680             Range, OEK_Member, DiagEmitted);
11681   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11682     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11683             Range, OEK_Variable, DiagEmitted);
11684   else
11685     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11686             Range, OEK_LValue, DiagEmitted);
11687   if (!DiagEmitted)
11688     DiagnoseConstAssignment(S, E, Loc);
11689 }
11690 
11691 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11692 /// emit an error and return true.  If so, return false.
11693 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11694   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11695 
11696   S.CheckShadowingDeclModification(E, Loc);
11697 
11698   SourceLocation OrigLoc = Loc;
11699   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11700                                                               &Loc);
11701   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11702     IsLV = Expr::MLV_InvalidMessageExpression;
11703   if (IsLV == Expr::MLV_Valid)
11704     return false;
11705 
11706   unsigned DiagID = 0;
11707   bool NeedType = false;
11708   switch (IsLV) { // C99 6.5.16p2
11709   case Expr::MLV_ConstQualified:
11710     // Use a specialized diagnostic when we're assigning to an object
11711     // from an enclosing function or block.
11712     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11713       if (NCCK == NCCK_Block)
11714         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11715       else
11716         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11717       break;
11718     }
11719 
11720     // In ARC, use some specialized diagnostics for occasions where we
11721     // infer 'const'.  These are always pseudo-strong variables.
11722     if (S.getLangOpts().ObjCAutoRefCount) {
11723       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11724       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11725         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11726 
11727         // Use the normal diagnostic if it's pseudo-__strong but the
11728         // user actually wrote 'const'.
11729         if (var->isARCPseudoStrong() &&
11730             (!var->getTypeSourceInfo() ||
11731              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11732           // There are three pseudo-strong cases:
11733           //  - self
11734           ObjCMethodDecl *method = S.getCurMethodDecl();
11735           if (method && var == method->getSelfDecl()) {
11736             DiagID = method->isClassMethod()
11737               ? diag::err_typecheck_arc_assign_self_class_method
11738               : diag::err_typecheck_arc_assign_self;
11739 
11740           //  - Objective-C externally_retained attribute.
11741           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11742                      isa<ParmVarDecl>(var)) {
11743             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11744 
11745           //  - fast enumeration variables
11746           } else {
11747             DiagID = diag::err_typecheck_arr_assign_enumeration;
11748           }
11749 
11750           SourceRange Assign;
11751           if (Loc != OrigLoc)
11752             Assign = SourceRange(OrigLoc, OrigLoc);
11753           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11754           // We need to preserve the AST regardless, so migration tool
11755           // can do its job.
11756           return false;
11757         }
11758       }
11759     }
11760 
11761     // If none of the special cases above are triggered, then this is a
11762     // simple const assignment.
11763     if (DiagID == 0) {
11764       DiagnoseConstAssignment(S, E, Loc);
11765       return true;
11766     }
11767 
11768     break;
11769   case Expr::MLV_ConstAddrSpace:
11770     DiagnoseConstAssignment(S, E, Loc);
11771     return true;
11772   case Expr::MLV_ConstQualifiedField:
11773     DiagnoseRecursiveConstFields(S, E, Loc);
11774     return true;
11775   case Expr::MLV_ArrayType:
11776   case Expr::MLV_ArrayTemporary:
11777     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11778     NeedType = true;
11779     break;
11780   case Expr::MLV_NotObjectType:
11781     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11782     NeedType = true;
11783     break;
11784   case Expr::MLV_LValueCast:
11785     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11786     break;
11787   case Expr::MLV_Valid:
11788     llvm_unreachable("did not take early return for MLV_Valid");
11789   case Expr::MLV_InvalidExpression:
11790   case Expr::MLV_MemberFunction:
11791   case Expr::MLV_ClassTemporary:
11792     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11793     break;
11794   case Expr::MLV_IncompleteType:
11795   case Expr::MLV_IncompleteVoidType:
11796     return S.RequireCompleteType(Loc, E->getType(),
11797              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11798   case Expr::MLV_DuplicateVectorComponents:
11799     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11800     break;
11801   case Expr::MLV_NoSetterProperty:
11802     llvm_unreachable("readonly properties should be processed differently");
11803   case Expr::MLV_InvalidMessageExpression:
11804     DiagID = diag::err_readonly_message_assignment;
11805     break;
11806   case Expr::MLV_SubObjCPropertySetting:
11807     DiagID = diag::err_no_subobject_property_setting;
11808     break;
11809   }
11810 
11811   SourceRange Assign;
11812   if (Loc != OrigLoc)
11813     Assign = SourceRange(OrigLoc, OrigLoc);
11814   if (NeedType)
11815     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11816   else
11817     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11818   return true;
11819 }
11820 
11821 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11822                                          SourceLocation Loc,
11823                                          Sema &Sema) {
11824   if (Sema.inTemplateInstantiation())
11825     return;
11826   if (Sema.isUnevaluatedContext())
11827     return;
11828   if (Loc.isInvalid() || Loc.isMacroID())
11829     return;
11830   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11831     return;
11832 
11833   // C / C++ fields
11834   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11835   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11836   if (ML && MR) {
11837     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11838       return;
11839     const ValueDecl *LHSDecl =
11840         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11841     const ValueDecl *RHSDecl =
11842         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11843     if (LHSDecl != RHSDecl)
11844       return;
11845     if (LHSDecl->getType().isVolatileQualified())
11846       return;
11847     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11848       if (RefTy->getPointeeType().isVolatileQualified())
11849         return;
11850 
11851     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11852   }
11853 
11854   // Objective-C instance variables
11855   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11856   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11857   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11858     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11859     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11860     if (RL && RR && RL->getDecl() == RR->getDecl())
11861       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11862   }
11863 }
11864 
11865 // C99 6.5.16.1
11866 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11867                                        SourceLocation Loc,
11868                                        QualType CompoundType) {
11869   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11870 
11871   // Verify that LHS is a modifiable lvalue, and emit error if not.
11872   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11873     return QualType();
11874 
11875   QualType LHSType = LHSExpr->getType();
11876   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11877                                              CompoundType;
11878   // OpenCL v1.2 s6.1.1.1 p2:
11879   // The half data type can only be used to declare a pointer to a buffer that
11880   // contains half values
11881   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11882     LHSType->isHalfType()) {
11883     Diag(Loc, diag::err_opencl_half_load_store) << 1
11884         << LHSType.getUnqualifiedType();
11885     return QualType();
11886   }
11887 
11888   AssignConvertType ConvTy;
11889   if (CompoundType.isNull()) {
11890     Expr *RHSCheck = RHS.get();
11891 
11892     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11893 
11894     QualType LHSTy(LHSType);
11895     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11896     if (RHS.isInvalid())
11897       return QualType();
11898     // Special case of NSObject attributes on c-style pointer types.
11899     if (ConvTy == IncompatiblePointer &&
11900         ((Context.isObjCNSObjectType(LHSType) &&
11901           RHSType->isObjCObjectPointerType()) ||
11902          (Context.isObjCNSObjectType(RHSType) &&
11903           LHSType->isObjCObjectPointerType())))
11904       ConvTy = Compatible;
11905 
11906     if (ConvTy == Compatible &&
11907         LHSType->isObjCObjectType())
11908         Diag(Loc, diag::err_objc_object_assignment)
11909           << LHSType;
11910 
11911     // If the RHS is a unary plus or minus, check to see if they = and + are
11912     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11913     // instead of "x += 4".
11914     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11915       RHSCheck = ICE->getSubExpr();
11916     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11917       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11918           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11919           // Only if the two operators are exactly adjacent.
11920           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11921           // And there is a space or other character before the subexpr of the
11922           // unary +/-.  We don't want to warn on "x=-1".
11923           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11924           UO->getSubExpr()->getBeginLoc().isFileID()) {
11925         Diag(Loc, diag::warn_not_compound_assign)
11926           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11927           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11928       }
11929     }
11930 
11931     if (ConvTy == Compatible) {
11932       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11933         // Warn about retain cycles where a block captures the LHS, but
11934         // not if the LHS is a simple variable into which the block is
11935         // being stored...unless that variable can be captured by reference!
11936         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11937         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11938         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11939           checkRetainCycles(LHSExpr, RHS.get());
11940       }
11941 
11942       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11943           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11944         // It is safe to assign a weak reference into a strong variable.
11945         // Although this code can still have problems:
11946         //   id x = self.weakProp;
11947         //   id y = self.weakProp;
11948         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11949         // paths through the function. This should be revisited if
11950         // -Wrepeated-use-of-weak is made flow-sensitive.
11951         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11952         // variable, which will be valid for the current autorelease scope.
11953         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11954                              RHS.get()->getBeginLoc()))
11955           getCurFunction()->markSafeWeakUse(RHS.get());
11956 
11957       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11958         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11959       }
11960     }
11961   } else {
11962     // Compound assignment "x += y"
11963     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11964   }
11965 
11966   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11967                                RHS.get(), AA_Assigning))
11968     return QualType();
11969 
11970   CheckForNullPointerDereference(*this, LHSExpr);
11971 
11972   if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
11973     if (CompoundType.isNull()) {
11974       // C++2a [expr.ass]p5:
11975       //   A simple-assignment whose left operand is of a volatile-qualified
11976       //   type is deprecated unless the assignment is either a discarded-value
11977       //   expression or an unevaluated operand
11978       ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
11979     } else {
11980       // C++2a [expr.ass]p6:
11981       //   [Compound-assignment] expressions are deprecated if E1 has
11982       //   volatile-qualified type
11983       Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
11984     }
11985   }
11986 
11987   // C99 6.5.16p3: The type of an assignment expression is the type of the
11988   // left operand unless the left operand has qualified type, in which case
11989   // it is the unqualified version of the type of the left operand.
11990   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11991   // is converted to the type of the assignment expression (above).
11992   // C++ 5.17p1: the type of the assignment expression is that of its left
11993   // operand.
11994   return (getLangOpts().CPlusPlus
11995           ? LHSType : LHSType.getUnqualifiedType());
11996 }
11997 
11998 // Only ignore explicit casts to void.
11999 static bool IgnoreCommaOperand(const Expr *E) {
12000   E = E->IgnoreParens();
12001 
12002   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12003     if (CE->getCastKind() == CK_ToVoid) {
12004       return true;
12005     }
12006 
12007     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12008     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12009         CE->getSubExpr()->getType()->isDependentType()) {
12010       return true;
12011     }
12012   }
12013 
12014   return false;
12015 }
12016 
12017 // Look for instances where it is likely the comma operator is confused with
12018 // another operator.  There is a whitelist of acceptable expressions for the
12019 // left hand side of the comma operator, otherwise emit a warning.
12020 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12021   // No warnings in macros
12022   if (Loc.isMacroID())
12023     return;
12024 
12025   // Don't warn in template instantiations.
12026   if (inTemplateInstantiation())
12027     return;
12028 
12029   // Scope isn't fine-grained enough to whitelist the specific cases, so
12030   // instead, skip more than needed, then call back into here with the
12031   // CommaVisitor in SemaStmt.cpp.
12032   // The whitelisted locations are the initialization and increment portions
12033   // of a for loop.  The additional checks are on the condition of
12034   // if statements, do/while loops, and for loops.
12035   // Differences in scope flags for C89 mode requires the extra logic.
12036   const unsigned ForIncrementFlags =
12037       getLangOpts().C99 || getLangOpts().CPlusPlus
12038           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12039           : Scope::ContinueScope | Scope::BreakScope;
12040   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12041   const unsigned ScopeFlags = getCurScope()->getFlags();
12042   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12043       (ScopeFlags & ForInitFlags) == ForInitFlags)
12044     return;
12045 
12046   // If there are multiple comma operators used together, get the RHS of the
12047   // of the comma operator as the LHS.
12048   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12049     if (BO->getOpcode() != BO_Comma)
12050       break;
12051     LHS = BO->getRHS();
12052   }
12053 
12054   // Only allow some expressions on LHS to not warn.
12055   if (IgnoreCommaOperand(LHS))
12056     return;
12057 
12058   Diag(Loc, diag::warn_comma_operator);
12059   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12060       << LHS->getSourceRange()
12061       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12062                                     LangOpts.CPlusPlus ? "static_cast<void>("
12063                                                        : "(void)(")
12064       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12065                                     ")");
12066 }
12067 
12068 // C99 6.5.17
12069 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12070                                    SourceLocation Loc) {
12071   LHS = S.CheckPlaceholderExpr(LHS.get());
12072   RHS = S.CheckPlaceholderExpr(RHS.get());
12073   if (LHS.isInvalid() || RHS.isInvalid())
12074     return QualType();
12075 
12076   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12077   // operands, but not unary promotions.
12078   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12079 
12080   // So we treat the LHS as a ignored value, and in C++ we allow the
12081   // containing site to determine what should be done with the RHS.
12082   LHS = S.IgnoredValueConversions(LHS.get());
12083   if (LHS.isInvalid())
12084     return QualType();
12085 
12086   S.DiagnoseUnusedExprResult(LHS.get());
12087 
12088   if (!S.getLangOpts().CPlusPlus) {
12089     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12090     if (RHS.isInvalid())
12091       return QualType();
12092     if (!RHS.get()->getType()->isVoidType())
12093       S.RequireCompleteType(Loc, RHS.get()->getType(),
12094                             diag::err_incomplete_type);
12095   }
12096 
12097   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12098     S.DiagnoseCommaOperator(LHS.get(), Loc);
12099 
12100   return RHS.get()->getType();
12101 }
12102 
12103 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12104 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12105 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12106                                                ExprValueKind &VK,
12107                                                ExprObjectKind &OK,
12108                                                SourceLocation OpLoc,
12109                                                bool IsInc, bool IsPrefix) {
12110   if (Op->isTypeDependent())
12111     return S.Context.DependentTy;
12112 
12113   QualType ResType = Op->getType();
12114   // Atomic types can be used for increment / decrement where the non-atomic
12115   // versions can, so ignore the _Atomic() specifier for the purpose of
12116   // checking.
12117   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12118     ResType = ResAtomicType->getValueType();
12119 
12120   assert(!ResType.isNull() && "no type for increment/decrement expression");
12121 
12122   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12123     // Decrement of bool is not allowed.
12124     if (!IsInc) {
12125       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12126       return QualType();
12127     }
12128     // Increment of bool sets it to true, but is deprecated.
12129     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12130                                               : diag::warn_increment_bool)
12131       << Op->getSourceRange();
12132   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12133     // Error on enum increments and decrements in C++ mode
12134     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12135     return QualType();
12136   } else if (ResType->isRealType()) {
12137     // OK!
12138   } else if (ResType->isPointerType()) {
12139     // C99 6.5.2.4p2, 6.5.6p2
12140     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12141       return QualType();
12142   } else if (ResType->isObjCObjectPointerType()) {
12143     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12144     // Otherwise, we just need a complete type.
12145     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12146         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12147       return QualType();
12148   } else if (ResType->isAnyComplexType()) {
12149     // C99 does not support ++/-- on complex types, we allow as an extension.
12150     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12151       << ResType << Op->getSourceRange();
12152   } else if (ResType->isPlaceholderType()) {
12153     ExprResult PR = S.CheckPlaceholderExpr(Op);
12154     if (PR.isInvalid()) return QualType();
12155     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12156                                           IsInc, IsPrefix);
12157   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12158     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12159   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12160              (ResType->castAs<VectorType>()->getVectorKind() !=
12161               VectorType::AltiVecBool)) {
12162     // The z vector extensions allow ++ and -- for non-bool vectors.
12163   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12164             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12165     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12166   } else {
12167     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12168       << ResType << int(IsInc) << Op->getSourceRange();
12169     return QualType();
12170   }
12171   // At this point, we know we have a real, complex or pointer type.
12172   // Now make sure the operand is a modifiable lvalue.
12173   if (CheckForModifiableLvalue(Op, OpLoc, S))
12174     return QualType();
12175   if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12176     // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12177     //   An operand with volatile-qualified type is deprecated
12178     S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12179         << IsInc << ResType;
12180   }
12181   // In C++, a prefix increment is the same type as the operand. Otherwise
12182   // (in C or with postfix), the increment is the unqualified type of the
12183   // operand.
12184   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12185     VK = VK_LValue;
12186     OK = Op->getObjectKind();
12187     return ResType;
12188   } else {
12189     VK = VK_RValue;
12190     return ResType.getUnqualifiedType();
12191   }
12192 }
12193 
12194 
12195 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12196 /// This routine allows us to typecheck complex/recursive expressions
12197 /// where the declaration is needed for type checking. We only need to
12198 /// handle cases when the expression references a function designator
12199 /// or is an lvalue. Here are some examples:
12200 ///  - &(x) => x
12201 ///  - &*****f => f for f a function designator.
12202 ///  - &s.xx => s
12203 ///  - &s.zz[1].yy -> s, if zz is an array
12204 ///  - *(x + 1) -> x, if x is an array
12205 ///  - &"123"[2] -> 0
12206 ///  - & __real__ x -> x
12207 static ValueDecl *getPrimaryDecl(Expr *E) {
12208   switch (E->getStmtClass()) {
12209   case Stmt::DeclRefExprClass:
12210     return cast<DeclRefExpr>(E)->getDecl();
12211   case Stmt::MemberExprClass:
12212     // If this is an arrow operator, the address is an offset from
12213     // the base's value, so the object the base refers to is
12214     // irrelevant.
12215     if (cast<MemberExpr>(E)->isArrow())
12216       return nullptr;
12217     // Otherwise, the expression refers to a part of the base
12218     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12219   case Stmt::ArraySubscriptExprClass: {
12220     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12221     // promotion of register arrays earlier.
12222     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12223     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12224       if (ICE->getSubExpr()->getType()->isArrayType())
12225         return getPrimaryDecl(ICE->getSubExpr());
12226     }
12227     return nullptr;
12228   }
12229   case Stmt::UnaryOperatorClass: {
12230     UnaryOperator *UO = cast<UnaryOperator>(E);
12231 
12232     switch(UO->getOpcode()) {
12233     case UO_Real:
12234     case UO_Imag:
12235     case UO_Extension:
12236       return getPrimaryDecl(UO->getSubExpr());
12237     default:
12238       return nullptr;
12239     }
12240   }
12241   case Stmt::ParenExprClass:
12242     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12243   case Stmt::ImplicitCastExprClass:
12244     // If the result of an implicit cast is an l-value, we care about
12245     // the sub-expression; otherwise, the result here doesn't matter.
12246     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12247   default:
12248     return nullptr;
12249   }
12250 }
12251 
12252 namespace {
12253   enum {
12254     AO_Bit_Field = 0,
12255     AO_Vector_Element = 1,
12256     AO_Property_Expansion = 2,
12257     AO_Register_Variable = 3,
12258     AO_No_Error = 4
12259   };
12260 }
12261 /// Diagnose invalid operand for address of operations.
12262 ///
12263 /// \param Type The type of operand which cannot have its address taken.
12264 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12265                                          Expr *E, unsigned Type) {
12266   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12267 }
12268 
12269 /// CheckAddressOfOperand - The operand of & must be either a function
12270 /// designator or an lvalue designating an object. If it is an lvalue, the
12271 /// object cannot be declared with storage class register or be a bit field.
12272 /// Note: The usual conversions are *not* applied to the operand of the &
12273 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12274 /// In C++, the operand might be an overloaded function name, in which case
12275 /// we allow the '&' but retain the overloaded-function type.
12276 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12277   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12278     if (PTy->getKind() == BuiltinType::Overload) {
12279       Expr *E = OrigOp.get()->IgnoreParens();
12280       if (!isa<OverloadExpr>(E)) {
12281         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12282         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12283           << OrigOp.get()->getSourceRange();
12284         return QualType();
12285       }
12286 
12287       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12288       if (isa<UnresolvedMemberExpr>(Ovl))
12289         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12290           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12291             << OrigOp.get()->getSourceRange();
12292           return QualType();
12293         }
12294 
12295       return Context.OverloadTy;
12296     }
12297 
12298     if (PTy->getKind() == BuiltinType::UnknownAny)
12299       return Context.UnknownAnyTy;
12300 
12301     if (PTy->getKind() == BuiltinType::BoundMember) {
12302       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12303         << OrigOp.get()->getSourceRange();
12304       return QualType();
12305     }
12306 
12307     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12308     if (OrigOp.isInvalid()) return QualType();
12309   }
12310 
12311   if (OrigOp.get()->isTypeDependent())
12312     return Context.DependentTy;
12313 
12314   assert(!OrigOp.get()->getType()->isPlaceholderType());
12315 
12316   // Make sure to ignore parentheses in subsequent checks
12317   Expr *op = OrigOp.get()->IgnoreParens();
12318 
12319   // In OpenCL captures for blocks called as lambda functions
12320   // are located in the private address space. Blocks used in
12321   // enqueue_kernel can be located in a different address space
12322   // depending on a vendor implementation. Thus preventing
12323   // taking an address of the capture to avoid invalid AS casts.
12324   if (LangOpts.OpenCL) {
12325     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12326     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12327       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12328       return QualType();
12329     }
12330   }
12331 
12332   if (getLangOpts().C99) {
12333     // Implement C99-only parts of addressof rules.
12334     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12335       if (uOp->getOpcode() == UO_Deref)
12336         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12337         // (assuming the deref expression is valid).
12338         return uOp->getSubExpr()->getType();
12339     }
12340     // Technically, there should be a check for array subscript
12341     // expressions here, but the result of one is always an lvalue anyway.
12342   }
12343   ValueDecl *dcl = getPrimaryDecl(op);
12344 
12345   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12346     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12347                                            op->getBeginLoc()))
12348       return QualType();
12349 
12350   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12351   unsigned AddressOfError = AO_No_Error;
12352 
12353   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12354     bool sfinae = (bool)isSFINAEContext();
12355     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12356                                   : diag::ext_typecheck_addrof_temporary)
12357       << op->getType() << op->getSourceRange();
12358     if (sfinae)
12359       return QualType();
12360     // Materialize the temporary as an lvalue so that we can take its address.
12361     OrigOp = op =
12362         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12363   } else if (isa<ObjCSelectorExpr>(op)) {
12364     return Context.getPointerType(op->getType());
12365   } else if (lval == Expr::LV_MemberFunction) {
12366     // If it's an instance method, make a member pointer.
12367     // The expression must have exactly the form &A::foo.
12368 
12369     // If the underlying expression isn't a decl ref, give up.
12370     if (!isa<DeclRefExpr>(op)) {
12371       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12372         << OrigOp.get()->getSourceRange();
12373       return QualType();
12374     }
12375     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12376     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12377 
12378     // The id-expression was parenthesized.
12379     if (OrigOp.get() != DRE) {
12380       Diag(OpLoc, diag::err_parens_pointer_member_function)
12381         << OrigOp.get()->getSourceRange();
12382 
12383     // The method was named without a qualifier.
12384     } else if (!DRE->getQualifier()) {
12385       if (MD->getParent()->getName().empty())
12386         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12387           << op->getSourceRange();
12388       else {
12389         SmallString<32> Str;
12390         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12391         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12392           << op->getSourceRange()
12393           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12394       }
12395     }
12396 
12397     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12398     if (isa<CXXDestructorDecl>(MD))
12399       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12400 
12401     QualType MPTy = Context.getMemberPointerType(
12402         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12403     // Under the MS ABI, lock down the inheritance model now.
12404     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12405       (void)isCompleteType(OpLoc, MPTy);
12406     return MPTy;
12407   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12408     // C99 6.5.3.2p1
12409     // The operand must be either an l-value or a function designator
12410     if (!op->getType()->isFunctionType()) {
12411       // Use a special diagnostic for loads from property references.
12412       if (isa<PseudoObjectExpr>(op)) {
12413         AddressOfError = AO_Property_Expansion;
12414       } else {
12415         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12416           << op->getType() << op->getSourceRange();
12417         return QualType();
12418       }
12419     }
12420   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12421     // The operand cannot be a bit-field
12422     AddressOfError = AO_Bit_Field;
12423   } else if (op->getObjectKind() == OK_VectorComponent) {
12424     // The operand cannot be an element of a vector
12425     AddressOfError = AO_Vector_Element;
12426   } else if (dcl) { // C99 6.5.3.2p1
12427     // We have an lvalue with a decl. Make sure the decl is not declared
12428     // with the register storage-class specifier.
12429     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12430       // in C++ it is not error to take address of a register
12431       // variable (c++03 7.1.1P3)
12432       if (vd->getStorageClass() == SC_Register &&
12433           !getLangOpts().CPlusPlus) {
12434         AddressOfError = AO_Register_Variable;
12435       }
12436     } else if (isa<MSPropertyDecl>(dcl)) {
12437       AddressOfError = AO_Property_Expansion;
12438     } else if (isa<FunctionTemplateDecl>(dcl)) {
12439       return Context.OverloadTy;
12440     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12441       // Okay: we can take the address of a field.
12442       // Could be a pointer to member, though, if there is an explicit
12443       // scope qualifier for the class.
12444       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12445         DeclContext *Ctx = dcl->getDeclContext();
12446         if (Ctx && Ctx->isRecord()) {
12447           if (dcl->getType()->isReferenceType()) {
12448             Diag(OpLoc,
12449                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12450               << dcl->getDeclName() << dcl->getType();
12451             return QualType();
12452           }
12453 
12454           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12455             Ctx = Ctx->getParent();
12456 
12457           QualType MPTy = Context.getMemberPointerType(
12458               op->getType(),
12459               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12460           // Under the MS ABI, lock down the inheritance model now.
12461           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12462             (void)isCompleteType(OpLoc, MPTy);
12463           return MPTy;
12464         }
12465       }
12466     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12467                !isa<BindingDecl>(dcl))
12468       llvm_unreachable("Unknown/unexpected decl type");
12469   }
12470 
12471   if (AddressOfError != AO_No_Error) {
12472     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12473     return QualType();
12474   }
12475 
12476   if (lval == Expr::LV_IncompleteVoidType) {
12477     // Taking the address of a void variable is technically illegal, but we
12478     // allow it in cases which are otherwise valid.
12479     // Example: "extern void x; void* y = &x;".
12480     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12481   }
12482 
12483   // If the operand has type "type", the result has type "pointer to type".
12484   if (op->getType()->isObjCObjectType())
12485     return Context.getObjCObjectPointerType(op->getType());
12486 
12487   CheckAddressOfPackedMember(op);
12488 
12489   return Context.getPointerType(op->getType());
12490 }
12491 
12492 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12493   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12494   if (!DRE)
12495     return;
12496   const Decl *D = DRE->getDecl();
12497   if (!D)
12498     return;
12499   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12500   if (!Param)
12501     return;
12502   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12503     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12504       return;
12505   if (FunctionScopeInfo *FD = S.getCurFunction())
12506     if (!FD->ModifiedNonNullParams.count(Param))
12507       FD->ModifiedNonNullParams.insert(Param);
12508 }
12509 
12510 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12511 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12512                                         SourceLocation OpLoc) {
12513   if (Op->isTypeDependent())
12514     return S.Context.DependentTy;
12515 
12516   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12517   if (ConvResult.isInvalid())
12518     return QualType();
12519   Op = ConvResult.get();
12520   QualType OpTy = Op->getType();
12521   QualType Result;
12522 
12523   if (isa<CXXReinterpretCastExpr>(Op)) {
12524     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12525     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12526                                      Op->getSourceRange());
12527   }
12528 
12529   if (const PointerType *PT = OpTy->getAs<PointerType>())
12530   {
12531     Result = PT->getPointeeType();
12532   }
12533   else if (const ObjCObjectPointerType *OPT =
12534              OpTy->getAs<ObjCObjectPointerType>())
12535     Result = OPT->getPointeeType();
12536   else {
12537     ExprResult PR = S.CheckPlaceholderExpr(Op);
12538     if (PR.isInvalid()) return QualType();
12539     if (PR.get() != Op)
12540       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12541   }
12542 
12543   if (Result.isNull()) {
12544     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12545       << OpTy << Op->getSourceRange();
12546     return QualType();
12547   }
12548 
12549   // Note that per both C89 and C99, indirection is always legal, even if Result
12550   // is an incomplete type or void.  It would be possible to warn about
12551   // dereferencing a void pointer, but it's completely well-defined, and such a
12552   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12553   // for pointers to 'void' but is fine for any other pointer type:
12554   //
12555   // C++ [expr.unary.op]p1:
12556   //   [...] the expression to which [the unary * operator] is applied shall
12557   //   be a pointer to an object type, or a pointer to a function type
12558   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12559     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12560       << OpTy << Op->getSourceRange();
12561 
12562   // Dereferences are usually l-values...
12563   VK = VK_LValue;
12564 
12565   // ...except that certain expressions are never l-values in C.
12566   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12567     VK = VK_RValue;
12568 
12569   return Result;
12570 }
12571 
12572 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12573   BinaryOperatorKind Opc;
12574   switch (Kind) {
12575   default: llvm_unreachable("Unknown binop!");
12576   case tok::periodstar:           Opc = BO_PtrMemD; break;
12577   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12578   case tok::star:                 Opc = BO_Mul; break;
12579   case tok::slash:                Opc = BO_Div; break;
12580   case tok::percent:              Opc = BO_Rem; break;
12581   case tok::plus:                 Opc = BO_Add; break;
12582   case tok::minus:                Opc = BO_Sub; break;
12583   case tok::lessless:             Opc = BO_Shl; break;
12584   case tok::greatergreater:       Opc = BO_Shr; break;
12585   case tok::lessequal:            Opc = BO_LE; break;
12586   case tok::less:                 Opc = BO_LT; break;
12587   case tok::greaterequal:         Opc = BO_GE; break;
12588   case tok::greater:              Opc = BO_GT; break;
12589   case tok::exclaimequal:         Opc = BO_NE; break;
12590   case tok::equalequal:           Opc = BO_EQ; break;
12591   case tok::spaceship:            Opc = BO_Cmp; break;
12592   case tok::amp:                  Opc = BO_And; break;
12593   case tok::caret:                Opc = BO_Xor; break;
12594   case tok::pipe:                 Opc = BO_Or; break;
12595   case tok::ampamp:               Opc = BO_LAnd; break;
12596   case tok::pipepipe:             Opc = BO_LOr; break;
12597   case tok::equal:                Opc = BO_Assign; break;
12598   case tok::starequal:            Opc = BO_MulAssign; break;
12599   case tok::slashequal:           Opc = BO_DivAssign; break;
12600   case tok::percentequal:         Opc = BO_RemAssign; break;
12601   case tok::plusequal:            Opc = BO_AddAssign; break;
12602   case tok::minusequal:           Opc = BO_SubAssign; break;
12603   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12604   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12605   case tok::ampequal:             Opc = BO_AndAssign; break;
12606   case tok::caretequal:           Opc = BO_XorAssign; break;
12607   case tok::pipeequal:            Opc = BO_OrAssign; break;
12608   case tok::comma:                Opc = BO_Comma; break;
12609   }
12610   return Opc;
12611 }
12612 
12613 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12614   tok::TokenKind Kind) {
12615   UnaryOperatorKind Opc;
12616   switch (Kind) {
12617   default: llvm_unreachable("Unknown unary op!");
12618   case tok::plusplus:     Opc = UO_PreInc; break;
12619   case tok::minusminus:   Opc = UO_PreDec; break;
12620   case tok::amp:          Opc = UO_AddrOf; break;
12621   case tok::star:         Opc = UO_Deref; break;
12622   case tok::plus:         Opc = UO_Plus; break;
12623   case tok::minus:        Opc = UO_Minus; break;
12624   case tok::tilde:        Opc = UO_Not; break;
12625   case tok::exclaim:      Opc = UO_LNot; break;
12626   case tok::kw___real:    Opc = UO_Real; break;
12627   case tok::kw___imag:    Opc = UO_Imag; break;
12628   case tok::kw___extension__: Opc = UO_Extension; break;
12629   }
12630   return Opc;
12631 }
12632 
12633 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12634 /// This warning suppressed in the event of macro expansions.
12635 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12636                                    SourceLocation OpLoc, bool IsBuiltin) {
12637   if (S.inTemplateInstantiation())
12638     return;
12639   if (S.isUnevaluatedContext())
12640     return;
12641   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12642     return;
12643   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12644   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12645   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12646   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12647   if (!LHSDeclRef || !RHSDeclRef ||
12648       LHSDeclRef->getLocation().isMacroID() ||
12649       RHSDeclRef->getLocation().isMacroID())
12650     return;
12651   const ValueDecl *LHSDecl =
12652     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12653   const ValueDecl *RHSDecl =
12654     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12655   if (LHSDecl != RHSDecl)
12656     return;
12657   if (LHSDecl->getType().isVolatileQualified())
12658     return;
12659   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12660     if (RefTy->getPointeeType().isVolatileQualified())
12661       return;
12662 
12663   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12664                           : diag::warn_self_assignment_overloaded)
12665       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12666       << RHSExpr->getSourceRange();
12667 }
12668 
12669 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12670 /// is usually indicative of introspection within the Objective-C pointer.
12671 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12672                                           SourceLocation OpLoc) {
12673   if (!S.getLangOpts().ObjC)
12674     return;
12675 
12676   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12677   const Expr *LHS = L.get();
12678   const Expr *RHS = R.get();
12679 
12680   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12681     ObjCPointerExpr = LHS;
12682     OtherExpr = RHS;
12683   }
12684   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12685     ObjCPointerExpr = RHS;
12686     OtherExpr = LHS;
12687   }
12688 
12689   // This warning is deliberately made very specific to reduce false
12690   // positives with logic that uses '&' for hashing.  This logic mainly
12691   // looks for code trying to introspect into tagged pointers, which
12692   // code should generally never do.
12693   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12694     unsigned Diag = diag::warn_objc_pointer_masking;
12695     // Determine if we are introspecting the result of performSelectorXXX.
12696     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12697     // Special case messages to -performSelector and friends, which
12698     // can return non-pointer values boxed in a pointer value.
12699     // Some clients may wish to silence warnings in this subcase.
12700     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12701       Selector S = ME->getSelector();
12702       StringRef SelArg0 = S.getNameForSlot(0);
12703       if (SelArg0.startswith("performSelector"))
12704         Diag = diag::warn_objc_pointer_masking_performSelector;
12705     }
12706 
12707     S.Diag(OpLoc, Diag)
12708       << ObjCPointerExpr->getSourceRange();
12709   }
12710 }
12711 
12712 static NamedDecl *getDeclFromExpr(Expr *E) {
12713   if (!E)
12714     return nullptr;
12715   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12716     return DRE->getDecl();
12717   if (auto *ME = dyn_cast<MemberExpr>(E))
12718     return ME->getMemberDecl();
12719   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12720     return IRE->getDecl();
12721   return nullptr;
12722 }
12723 
12724 // This helper function promotes a binary operator's operands (which are of a
12725 // half vector type) to a vector of floats and then truncates the result to
12726 // a vector of either half or short.
12727 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12728                                       BinaryOperatorKind Opc, QualType ResultTy,
12729                                       ExprValueKind VK, ExprObjectKind OK,
12730                                       bool IsCompAssign, SourceLocation OpLoc,
12731                                       FPOptions FPFeatures) {
12732   auto &Context = S.getASTContext();
12733   assert((isVector(ResultTy, Context.HalfTy) ||
12734           isVector(ResultTy, Context.ShortTy)) &&
12735          "Result must be a vector of half or short");
12736   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12737          isVector(RHS.get()->getType(), Context.HalfTy) &&
12738          "both operands expected to be a half vector");
12739 
12740   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12741   QualType BinOpResTy = RHS.get()->getType();
12742 
12743   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12744   // change BinOpResTy to a vector of ints.
12745   if (isVector(ResultTy, Context.ShortTy))
12746     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12747 
12748   if (IsCompAssign)
12749     return new (Context) CompoundAssignOperator(
12750         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12751         OpLoc, FPFeatures);
12752 
12753   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12754   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12755                                           VK, OK, OpLoc, FPFeatures);
12756   return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12757 }
12758 
12759 static std::pair<ExprResult, ExprResult>
12760 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12761                            Expr *RHSExpr) {
12762   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12763   if (!S.getLangOpts().CPlusPlus) {
12764     // C cannot handle TypoExpr nodes on either side of a binop because it
12765     // doesn't handle dependent types properly, so make sure any TypoExprs have
12766     // been dealt with before checking the operands.
12767     LHS = S.CorrectDelayedTyposInExpr(LHS);
12768     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12769       if (Opc != BO_Assign)
12770         return ExprResult(E);
12771       // Avoid correcting the RHS to the same Expr as the LHS.
12772       Decl *D = getDeclFromExpr(E);
12773       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12774     });
12775   }
12776   return std::make_pair(LHS, RHS);
12777 }
12778 
12779 /// Returns true if conversion between vectors of halfs and vectors of floats
12780 /// is needed.
12781 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12782                                      QualType SrcType) {
12783   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12784          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12785          isVector(SrcType, Ctx.HalfTy);
12786 }
12787 
12788 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12789 /// operator @p Opc at location @c TokLoc. This routine only supports
12790 /// built-in operations; ActOnBinOp handles overloaded operators.
12791 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12792                                     BinaryOperatorKind Opc,
12793                                     Expr *LHSExpr, Expr *RHSExpr) {
12794   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12795     // The syntax only allows initializer lists on the RHS of assignment,
12796     // so we don't need to worry about accepting invalid code for
12797     // non-assignment operators.
12798     // C++11 5.17p9:
12799     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12800     //   of x = {} is x = T().
12801     InitializationKind Kind = InitializationKind::CreateDirectList(
12802         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12803     InitializedEntity Entity =
12804         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12805     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12806     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12807     if (Init.isInvalid())
12808       return Init;
12809     RHSExpr = Init.get();
12810   }
12811 
12812   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12813   QualType ResultTy;     // Result type of the binary operator.
12814   // The following two variables are used for compound assignment operators
12815   QualType CompLHSTy;    // Type of LHS after promotions for computation
12816   QualType CompResultTy; // Type of computation result
12817   ExprValueKind VK = VK_RValue;
12818   ExprObjectKind OK = OK_Ordinary;
12819   bool ConvertHalfVec = false;
12820 
12821   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12822   if (!LHS.isUsable() || !RHS.isUsable())
12823     return ExprError();
12824 
12825   if (getLangOpts().OpenCL) {
12826     QualType LHSTy = LHSExpr->getType();
12827     QualType RHSTy = RHSExpr->getType();
12828     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12829     // the ATOMIC_VAR_INIT macro.
12830     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12831       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12832       if (BO_Assign == Opc)
12833         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12834       else
12835         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12836       return ExprError();
12837     }
12838 
12839     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12840     // only with a builtin functions and therefore should be disallowed here.
12841     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12842         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12843         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12844         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12845       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12846       return ExprError();
12847     }
12848   }
12849 
12850   // Diagnose operations on the unsupported types for OpenMP device compilation.
12851   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12852     if (Opc != BO_Assign && Opc != BO_Comma) {
12853       checkOpenMPDeviceExpr(LHSExpr);
12854       checkOpenMPDeviceExpr(RHSExpr);
12855     }
12856   }
12857 
12858   switch (Opc) {
12859   case BO_Assign:
12860     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12861     if (getLangOpts().CPlusPlus &&
12862         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12863       VK = LHS.get()->getValueKind();
12864       OK = LHS.get()->getObjectKind();
12865     }
12866     if (!ResultTy.isNull()) {
12867       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12868       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12869 
12870       // Avoid copying a block to the heap if the block is assigned to a local
12871       // auto variable that is declared in the same scope as the block. This
12872       // optimization is unsafe if the local variable is declared in an outer
12873       // scope. For example:
12874       //
12875       // BlockTy b;
12876       // {
12877       //   b = ^{...};
12878       // }
12879       // // It is unsafe to invoke the block here if it wasn't copied to the
12880       // // heap.
12881       // b();
12882 
12883       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12884         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12885           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12886             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12887               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12888 
12889       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
12890         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
12891                               NTCUC_Assignment, NTCUK_Copy);
12892     }
12893     RecordModifiableNonNullParam(*this, LHS.get());
12894     break;
12895   case BO_PtrMemD:
12896   case BO_PtrMemI:
12897     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12898                                             Opc == BO_PtrMemI);
12899     break;
12900   case BO_Mul:
12901   case BO_Div:
12902     ConvertHalfVec = true;
12903     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12904                                            Opc == BO_Div);
12905     break;
12906   case BO_Rem:
12907     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12908     break;
12909   case BO_Add:
12910     ConvertHalfVec = true;
12911     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12912     break;
12913   case BO_Sub:
12914     ConvertHalfVec = true;
12915     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12916     break;
12917   case BO_Shl:
12918   case BO_Shr:
12919     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12920     break;
12921   case BO_LE:
12922   case BO_LT:
12923   case BO_GE:
12924   case BO_GT:
12925     ConvertHalfVec = true;
12926     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12927     break;
12928   case BO_EQ:
12929   case BO_NE:
12930     ConvertHalfVec = true;
12931     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12932     break;
12933   case BO_Cmp:
12934     ConvertHalfVec = true;
12935     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12936     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12937     break;
12938   case BO_And:
12939     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12940     LLVM_FALLTHROUGH;
12941   case BO_Xor:
12942   case BO_Or:
12943     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12944     break;
12945   case BO_LAnd:
12946   case BO_LOr:
12947     ConvertHalfVec = true;
12948     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12949     break;
12950   case BO_MulAssign:
12951   case BO_DivAssign:
12952     ConvertHalfVec = true;
12953     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12954                                                Opc == BO_DivAssign);
12955     CompLHSTy = CompResultTy;
12956     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12957       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12958     break;
12959   case BO_RemAssign:
12960     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12961     CompLHSTy = CompResultTy;
12962     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12963       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12964     break;
12965   case BO_AddAssign:
12966     ConvertHalfVec = true;
12967     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12968     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12969       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12970     break;
12971   case BO_SubAssign:
12972     ConvertHalfVec = true;
12973     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12974     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12975       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12976     break;
12977   case BO_ShlAssign:
12978   case BO_ShrAssign:
12979     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12980     CompLHSTy = CompResultTy;
12981     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12982       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12983     break;
12984   case BO_AndAssign:
12985   case BO_OrAssign: // fallthrough
12986     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12987     LLVM_FALLTHROUGH;
12988   case BO_XorAssign:
12989     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12990     CompLHSTy = CompResultTy;
12991     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12992       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12993     break;
12994   case BO_Comma:
12995     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12996     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12997       VK = RHS.get()->getValueKind();
12998       OK = RHS.get()->getObjectKind();
12999     }
13000     break;
13001   }
13002   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13003     return ExprError();
13004 
13005   // Some of the binary operations require promoting operands of half vector to
13006   // float vectors and truncating the result back to half vector. For now, we do
13007   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13008   // arm64).
13009   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
13010          isVector(LHS.get()->getType(), Context.HalfTy) &&
13011          "both sides are half vectors or neither sides are");
13012   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
13013                                             LHS.get()->getType());
13014 
13015   // Check for array bounds violations for both sides of the BinaryOperator
13016   CheckArrayAccess(LHS.get());
13017   CheckArrayAccess(RHS.get());
13018 
13019   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13020     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13021                                                  &Context.Idents.get("object_setClass"),
13022                                                  SourceLocation(), LookupOrdinaryName);
13023     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13024       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13025       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13026           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13027                                         "object_setClass(")
13028           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13029                                           ",")
13030           << FixItHint::CreateInsertion(RHSLocEnd, ")");
13031     }
13032     else
13033       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13034   }
13035   else if (const ObjCIvarRefExpr *OIRE =
13036            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13037     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13038 
13039   // Opc is not a compound assignment if CompResultTy is null.
13040   if (CompResultTy.isNull()) {
13041     if (ConvertHalfVec)
13042       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13043                                  OpLoc, FPFeatures);
13044     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13045                                         OK, OpLoc, FPFeatures);
13046   }
13047 
13048   // Handle compound assignments.
13049   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13050       OK_ObjCProperty) {
13051     VK = VK_LValue;
13052     OK = LHS.get()->getObjectKind();
13053   }
13054 
13055   if (ConvertHalfVec)
13056     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13057                                OpLoc, FPFeatures);
13058 
13059   return new (Context) CompoundAssignOperator(
13060       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13061       OpLoc, FPFeatures);
13062 }
13063 
13064 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13065 /// operators are mixed in a way that suggests that the programmer forgot that
13066 /// comparison operators have higher precedence. The most typical example of
13067 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13068 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13069                                       SourceLocation OpLoc, Expr *LHSExpr,
13070                                       Expr *RHSExpr) {
13071   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13072   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13073 
13074   // Check that one of the sides is a comparison operator and the other isn't.
13075   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13076   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13077   if (isLeftComp == isRightComp)
13078     return;
13079 
13080   // Bitwise operations are sometimes used as eager logical ops.
13081   // Don't diagnose this.
13082   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13083   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13084   if (isLeftBitwise || isRightBitwise)
13085     return;
13086 
13087   SourceRange DiagRange = isLeftComp
13088                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13089                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13090   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13091   SourceRange ParensRange =
13092       isLeftComp
13093           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13094           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13095 
13096   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13097     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13098   SuggestParentheses(Self, OpLoc,
13099     Self.PDiag(diag::note_precedence_silence) << OpStr,
13100     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13101   SuggestParentheses(Self, OpLoc,
13102     Self.PDiag(diag::note_precedence_bitwise_first)
13103       << BinaryOperator::getOpcodeStr(Opc),
13104     ParensRange);
13105 }
13106 
13107 /// It accepts a '&&' expr that is inside a '||' one.
13108 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13109 /// in parentheses.
13110 static void
13111 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13112                                        BinaryOperator *Bop) {
13113   assert(Bop->getOpcode() == BO_LAnd);
13114   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13115       << Bop->getSourceRange() << OpLoc;
13116   SuggestParentheses(Self, Bop->getOperatorLoc(),
13117     Self.PDiag(diag::note_precedence_silence)
13118       << Bop->getOpcodeStr(),
13119     Bop->getSourceRange());
13120 }
13121 
13122 /// Returns true if the given expression can be evaluated as a constant
13123 /// 'true'.
13124 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13125   bool Res;
13126   return !E->isValueDependent() &&
13127          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13128 }
13129 
13130 /// Returns true if the given expression can be evaluated as a constant
13131 /// 'false'.
13132 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13133   bool Res;
13134   return !E->isValueDependent() &&
13135          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13136 }
13137 
13138 /// Look for '&&' in the left hand of a '||' expr.
13139 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13140                                              Expr *LHSExpr, Expr *RHSExpr) {
13141   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13142     if (Bop->getOpcode() == BO_LAnd) {
13143       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13144       if (EvaluatesAsFalse(S, RHSExpr))
13145         return;
13146       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13147       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13148         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13149     } else if (Bop->getOpcode() == BO_LOr) {
13150       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13151         // If it's "a || b && 1 || c" we didn't warn earlier for
13152         // "a || b && 1", but warn now.
13153         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13154           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13155       }
13156     }
13157   }
13158 }
13159 
13160 /// Look for '&&' in the right hand of a '||' expr.
13161 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13162                                              Expr *LHSExpr, Expr *RHSExpr) {
13163   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13164     if (Bop->getOpcode() == BO_LAnd) {
13165       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13166       if (EvaluatesAsFalse(S, LHSExpr))
13167         return;
13168       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13169       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13170         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13171     }
13172   }
13173 }
13174 
13175 /// Look for bitwise op in the left or right hand of a bitwise op with
13176 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13177 /// the '&' expression in parentheses.
13178 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13179                                          SourceLocation OpLoc, Expr *SubExpr) {
13180   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13181     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13182       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13183         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13184         << Bop->getSourceRange() << OpLoc;
13185       SuggestParentheses(S, Bop->getOperatorLoc(),
13186         S.PDiag(diag::note_precedence_silence)
13187           << Bop->getOpcodeStr(),
13188         Bop->getSourceRange());
13189     }
13190   }
13191 }
13192 
13193 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13194                                     Expr *SubExpr, StringRef Shift) {
13195   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13196     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13197       StringRef Op = Bop->getOpcodeStr();
13198       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13199           << Bop->getSourceRange() << OpLoc << Shift << Op;
13200       SuggestParentheses(S, Bop->getOperatorLoc(),
13201           S.PDiag(diag::note_precedence_silence) << Op,
13202           Bop->getSourceRange());
13203     }
13204   }
13205 }
13206 
13207 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13208                                  Expr *LHSExpr, Expr *RHSExpr) {
13209   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13210   if (!OCE)
13211     return;
13212 
13213   FunctionDecl *FD = OCE->getDirectCallee();
13214   if (!FD || !FD->isOverloadedOperator())
13215     return;
13216 
13217   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13218   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13219     return;
13220 
13221   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13222       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13223       << (Kind == OO_LessLess);
13224   SuggestParentheses(S, OCE->getOperatorLoc(),
13225                      S.PDiag(diag::note_precedence_silence)
13226                          << (Kind == OO_LessLess ? "<<" : ">>"),
13227                      OCE->getSourceRange());
13228   SuggestParentheses(
13229       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13230       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13231 }
13232 
13233 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13234 /// precedence.
13235 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13236                                     SourceLocation OpLoc, Expr *LHSExpr,
13237                                     Expr *RHSExpr){
13238   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13239   if (BinaryOperator::isBitwiseOp(Opc))
13240     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13241 
13242   // Diagnose "arg1 & arg2 | arg3"
13243   if ((Opc == BO_Or || Opc == BO_Xor) &&
13244       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13245     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13246     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13247   }
13248 
13249   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13250   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13251   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13252     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13253     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13254   }
13255 
13256   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13257       || Opc == BO_Shr) {
13258     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13259     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13260     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13261   }
13262 
13263   // Warn on overloaded shift operators and comparisons, such as:
13264   // cout << 5 == 4;
13265   if (BinaryOperator::isComparisonOp(Opc))
13266     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13267 }
13268 
13269 // Binary Operators.  'Tok' is the token for the operator.
13270 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13271                             tok::TokenKind Kind,
13272                             Expr *LHSExpr, Expr *RHSExpr) {
13273   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13274   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13275   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13276 
13277   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13278   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13279 
13280   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13281 }
13282 
13283 /// Build an overloaded binary operator expression in the given scope.
13284 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13285                                        BinaryOperatorKind Opc,
13286                                        Expr *LHS, Expr *RHS) {
13287   switch (Opc) {
13288   case BO_Assign:
13289   case BO_DivAssign:
13290   case BO_RemAssign:
13291   case BO_SubAssign:
13292   case BO_AndAssign:
13293   case BO_OrAssign:
13294   case BO_XorAssign:
13295     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13296     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13297     break;
13298   default:
13299     break;
13300   }
13301 
13302   // Find all of the overloaded operators visible from this
13303   // point. We perform both an operator-name lookup from the local
13304   // scope and an argument-dependent lookup based on the types of
13305   // the arguments.
13306   UnresolvedSet<16> Functions;
13307   OverloadedOperatorKind OverOp
13308     = BinaryOperator::getOverloadedOperator(Opc);
13309   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13310     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13311                                    RHS->getType(), Functions);
13312 
13313   // Build the (potentially-overloaded, potentially-dependent)
13314   // binary operation.
13315   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13316 }
13317 
13318 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13319                             BinaryOperatorKind Opc,
13320                             Expr *LHSExpr, Expr *RHSExpr) {
13321   ExprResult LHS, RHS;
13322   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13323   if (!LHS.isUsable() || !RHS.isUsable())
13324     return ExprError();
13325   LHSExpr = LHS.get();
13326   RHSExpr = RHS.get();
13327 
13328   // We want to end up calling one of checkPseudoObjectAssignment
13329   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13330   // both expressions are overloadable or either is type-dependent),
13331   // or CreateBuiltinBinOp (in any other case).  We also want to get
13332   // any placeholder types out of the way.
13333 
13334   // Handle pseudo-objects in the LHS.
13335   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13336     // Assignments with a pseudo-object l-value need special analysis.
13337     if (pty->getKind() == BuiltinType::PseudoObject &&
13338         BinaryOperator::isAssignmentOp(Opc))
13339       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13340 
13341     // Don't resolve overloads if the other type is overloadable.
13342     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13343       // We can't actually test that if we still have a placeholder,
13344       // though.  Fortunately, none of the exceptions we see in that
13345       // code below are valid when the LHS is an overload set.  Note
13346       // that an overload set can be dependently-typed, but it never
13347       // instantiates to having an overloadable type.
13348       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13349       if (resolvedRHS.isInvalid()) return ExprError();
13350       RHSExpr = resolvedRHS.get();
13351 
13352       if (RHSExpr->isTypeDependent() ||
13353           RHSExpr->getType()->isOverloadableType())
13354         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13355     }
13356 
13357     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13358     // template, diagnose the missing 'template' keyword instead of diagnosing
13359     // an invalid use of a bound member function.
13360     //
13361     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13362     // to C++1z [over.over]/1.4, but we already checked for that case above.
13363     if (Opc == BO_LT && inTemplateInstantiation() &&
13364         (pty->getKind() == BuiltinType::BoundMember ||
13365          pty->getKind() == BuiltinType::Overload)) {
13366       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13367       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13368           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13369             return isa<FunctionTemplateDecl>(ND);
13370           })) {
13371         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13372                                 : OE->getNameLoc(),
13373              diag::err_template_kw_missing)
13374           << OE->getName().getAsString() << "";
13375         return ExprError();
13376       }
13377     }
13378 
13379     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13380     if (LHS.isInvalid()) return ExprError();
13381     LHSExpr = LHS.get();
13382   }
13383 
13384   // Handle pseudo-objects in the RHS.
13385   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13386     // An overload in the RHS can potentially be resolved by the type
13387     // being assigned to.
13388     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13389       if (getLangOpts().CPlusPlus &&
13390           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13391            LHSExpr->getType()->isOverloadableType()))
13392         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13393 
13394       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13395     }
13396 
13397     // Don't resolve overloads if the other type is overloadable.
13398     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13399         LHSExpr->getType()->isOverloadableType())
13400       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13401 
13402     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13403     if (!resolvedRHS.isUsable()) return ExprError();
13404     RHSExpr = resolvedRHS.get();
13405   }
13406 
13407   if (getLangOpts().CPlusPlus) {
13408     // If either expression is type-dependent, always build an
13409     // overloaded op.
13410     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13411       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13412 
13413     // Otherwise, build an overloaded op if either expression has an
13414     // overloadable type.
13415     if (LHSExpr->getType()->isOverloadableType() ||
13416         RHSExpr->getType()->isOverloadableType())
13417       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13418   }
13419 
13420   // Build a built-in binary operation.
13421   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13422 }
13423 
13424 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13425   if (T.isNull() || T->isDependentType())
13426     return false;
13427 
13428   if (!T->isPromotableIntegerType())
13429     return true;
13430 
13431   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13432 }
13433 
13434 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13435                                       UnaryOperatorKind Opc,
13436                                       Expr *InputExpr) {
13437   ExprResult Input = InputExpr;
13438   ExprValueKind VK = VK_RValue;
13439   ExprObjectKind OK = OK_Ordinary;
13440   QualType resultType;
13441   bool CanOverflow = false;
13442 
13443   bool ConvertHalfVec = false;
13444   if (getLangOpts().OpenCL) {
13445     QualType Ty = InputExpr->getType();
13446     // The only legal unary operation for atomics is '&'.
13447     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13448     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13449     // only with a builtin functions and therefore should be disallowed here.
13450         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13451         || Ty->isBlockPointerType())) {
13452       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13453                        << InputExpr->getType()
13454                        << Input.get()->getSourceRange());
13455     }
13456   }
13457   // Diagnose operations on the unsupported types for OpenMP device compilation.
13458   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13459     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13460         UnaryOperator::isArithmeticOp(Opc))
13461       checkOpenMPDeviceExpr(InputExpr);
13462   }
13463 
13464   switch (Opc) {
13465   case UO_PreInc:
13466   case UO_PreDec:
13467   case UO_PostInc:
13468   case UO_PostDec:
13469     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13470                                                 OpLoc,
13471                                                 Opc == UO_PreInc ||
13472                                                 Opc == UO_PostInc,
13473                                                 Opc == UO_PreInc ||
13474                                                 Opc == UO_PreDec);
13475     CanOverflow = isOverflowingIntegerType(Context, resultType);
13476     break;
13477   case UO_AddrOf:
13478     resultType = CheckAddressOfOperand(Input, OpLoc);
13479     CheckAddressOfNoDeref(InputExpr);
13480     RecordModifiableNonNullParam(*this, InputExpr);
13481     break;
13482   case UO_Deref: {
13483     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13484     if (Input.isInvalid()) return ExprError();
13485     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13486     break;
13487   }
13488   case UO_Plus:
13489   case UO_Minus:
13490     CanOverflow = Opc == UO_Minus &&
13491                   isOverflowingIntegerType(Context, Input.get()->getType());
13492     Input = UsualUnaryConversions(Input.get());
13493     if (Input.isInvalid()) return ExprError();
13494     // Unary plus and minus require promoting an operand of half vector to a
13495     // float vector and truncating the result back to a half vector. For now, we
13496     // do this only when HalfArgsAndReturns is set (that is, when the target is
13497     // arm or arm64).
13498     ConvertHalfVec =
13499         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13500 
13501     // If the operand is a half vector, promote it to a float vector.
13502     if (ConvertHalfVec)
13503       Input = convertVector(Input.get(), Context.FloatTy, *this);
13504     resultType = Input.get()->getType();
13505     if (resultType->isDependentType())
13506       break;
13507     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13508       break;
13509     else if (resultType->isVectorType() &&
13510              // The z vector extensions don't allow + or - with bool vectors.
13511              (!Context.getLangOpts().ZVector ||
13512               resultType->castAs<VectorType>()->getVectorKind() !=
13513               VectorType::AltiVecBool))
13514       break;
13515     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13516              Opc == UO_Plus &&
13517              resultType->isPointerType())
13518       break;
13519 
13520     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13521       << resultType << Input.get()->getSourceRange());
13522 
13523   case UO_Not: // bitwise complement
13524     Input = UsualUnaryConversions(Input.get());
13525     if (Input.isInvalid())
13526       return ExprError();
13527     resultType = Input.get()->getType();
13528     if (resultType->isDependentType())
13529       break;
13530     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13531     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13532       // C99 does not support '~' for complex conjugation.
13533       Diag(OpLoc, diag::ext_integer_complement_complex)
13534           << resultType << Input.get()->getSourceRange();
13535     else if (resultType->hasIntegerRepresentation())
13536       break;
13537     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13538       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13539       // on vector float types.
13540       QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13541       if (!T->isIntegerType())
13542         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13543                           << resultType << Input.get()->getSourceRange());
13544     } else {
13545       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13546                        << resultType << Input.get()->getSourceRange());
13547     }
13548     break;
13549 
13550   case UO_LNot: // logical negation
13551     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13552     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13553     if (Input.isInvalid()) return ExprError();
13554     resultType = Input.get()->getType();
13555 
13556     // Though we still have to promote half FP to float...
13557     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13558       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13559       resultType = Context.FloatTy;
13560     }
13561 
13562     if (resultType->isDependentType())
13563       break;
13564     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13565       // C99 6.5.3.3p1: ok, fallthrough;
13566       if (Context.getLangOpts().CPlusPlus) {
13567         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13568         // operand contextually converted to bool.
13569         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13570                                   ScalarTypeToBooleanCastKind(resultType));
13571       } else if (Context.getLangOpts().OpenCL &&
13572                  Context.getLangOpts().OpenCLVersion < 120) {
13573         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13574         // operate on scalar float types.
13575         if (!resultType->isIntegerType() && !resultType->isPointerType())
13576           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13577                            << resultType << Input.get()->getSourceRange());
13578       }
13579     } else if (resultType->isExtVectorType()) {
13580       if (Context.getLangOpts().OpenCL &&
13581           Context.getLangOpts().OpenCLVersion < 120 &&
13582           !Context.getLangOpts().OpenCLCPlusPlus) {
13583         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13584         // operate on vector float types.
13585         QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13586         if (!T->isIntegerType())
13587           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13588                            << resultType << Input.get()->getSourceRange());
13589       }
13590       // Vector logical not returns the signed variant of the operand type.
13591       resultType = GetSignedVectorType(resultType);
13592       break;
13593     } else {
13594       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13595       //        type in C++. We should allow that here too.
13596       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13597         << resultType << Input.get()->getSourceRange());
13598     }
13599 
13600     // LNot always has type int. C99 6.5.3.3p5.
13601     // In C++, it's bool. C++ 5.3.1p8
13602     resultType = Context.getLogicalOperationType();
13603     break;
13604   case UO_Real:
13605   case UO_Imag:
13606     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13607     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13608     // complex l-values to ordinary l-values and all other values to r-values.
13609     if (Input.isInvalid()) return ExprError();
13610     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13611       if (Input.get()->getValueKind() != VK_RValue &&
13612           Input.get()->getObjectKind() == OK_Ordinary)
13613         VK = Input.get()->getValueKind();
13614     } else if (!getLangOpts().CPlusPlus) {
13615       // In C, a volatile scalar is read by __imag. In C++, it is not.
13616       Input = DefaultLvalueConversion(Input.get());
13617     }
13618     break;
13619   case UO_Extension:
13620     resultType = Input.get()->getType();
13621     VK = Input.get()->getValueKind();
13622     OK = Input.get()->getObjectKind();
13623     break;
13624   case UO_Coawait:
13625     // It's unnecessary to represent the pass-through operator co_await in the
13626     // AST; just return the input expression instead.
13627     assert(!Input.get()->getType()->isDependentType() &&
13628                    "the co_await expression must be non-dependant before "
13629                    "building operator co_await");
13630     return Input;
13631   }
13632   if (resultType.isNull() || Input.isInvalid())
13633     return ExprError();
13634 
13635   // Check for array bounds violations in the operand of the UnaryOperator,
13636   // except for the '*' and '&' operators that have to be handled specially
13637   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13638   // that are explicitly defined as valid by the standard).
13639   if (Opc != UO_AddrOf && Opc != UO_Deref)
13640     CheckArrayAccess(Input.get());
13641 
13642   auto *UO = new (Context)
13643       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13644 
13645   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13646       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13647     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13648 
13649   // Convert the result back to a half vector.
13650   if (ConvertHalfVec)
13651     return convertVector(UO, Context.HalfTy, *this);
13652   return UO;
13653 }
13654 
13655 /// Determine whether the given expression is a qualified member
13656 /// access expression, of a form that could be turned into a pointer to member
13657 /// with the address-of operator.
13658 bool Sema::isQualifiedMemberAccess(Expr *E) {
13659   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13660     if (!DRE->getQualifier())
13661       return false;
13662 
13663     ValueDecl *VD = DRE->getDecl();
13664     if (!VD->isCXXClassMember())
13665       return false;
13666 
13667     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13668       return true;
13669     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13670       return Method->isInstance();
13671 
13672     return false;
13673   }
13674 
13675   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13676     if (!ULE->getQualifier())
13677       return false;
13678 
13679     for (NamedDecl *D : ULE->decls()) {
13680       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13681         if (Method->isInstance())
13682           return true;
13683       } else {
13684         // Overload set does not contain methods.
13685         break;
13686       }
13687     }
13688 
13689     return false;
13690   }
13691 
13692   return false;
13693 }
13694 
13695 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13696                               UnaryOperatorKind Opc, Expr *Input) {
13697   // First things first: handle placeholders so that the
13698   // overloaded-operator check considers the right type.
13699   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13700     // Increment and decrement of pseudo-object references.
13701     if (pty->getKind() == BuiltinType::PseudoObject &&
13702         UnaryOperator::isIncrementDecrementOp(Opc))
13703       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13704 
13705     // extension is always a builtin operator.
13706     if (Opc == UO_Extension)
13707       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13708 
13709     // & gets special logic for several kinds of placeholder.
13710     // The builtin code knows what to do.
13711     if (Opc == UO_AddrOf &&
13712         (pty->getKind() == BuiltinType::Overload ||
13713          pty->getKind() == BuiltinType::UnknownAny ||
13714          pty->getKind() == BuiltinType::BoundMember))
13715       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13716 
13717     // Anything else needs to be handled now.
13718     ExprResult Result = CheckPlaceholderExpr(Input);
13719     if (Result.isInvalid()) return ExprError();
13720     Input = Result.get();
13721   }
13722 
13723   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13724       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13725       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13726     // Find all of the overloaded operators visible from this
13727     // point. We perform both an operator-name lookup from the local
13728     // scope and an argument-dependent lookup based on the types of
13729     // the arguments.
13730     UnresolvedSet<16> Functions;
13731     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13732     if (S && OverOp != OO_None)
13733       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13734                                    Functions);
13735 
13736     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13737   }
13738 
13739   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13740 }
13741 
13742 // Unary Operators.  'Tok' is the token for the operator.
13743 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13744                               tok::TokenKind Op, Expr *Input) {
13745   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13746 }
13747 
13748 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13749 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13750                                 LabelDecl *TheDecl) {
13751   TheDecl->markUsed(Context);
13752   // Create the AST node.  The address of a label always has type 'void*'.
13753   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13754                                      Context.getPointerType(Context.VoidTy));
13755 }
13756 
13757 void Sema::ActOnStartStmtExpr() {
13758   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13759 }
13760 
13761 void Sema::ActOnStmtExprError() {
13762   // Note that function is also called by TreeTransform when leaving a
13763   // StmtExpr scope without rebuilding anything.
13764 
13765   DiscardCleanupsInEvaluationContext();
13766   PopExpressionEvaluationContext();
13767 }
13768 
13769 ExprResult
13770 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13771                     SourceLocation RPLoc) { // "({..})"
13772   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13773   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13774 
13775   if (hasAnyUnrecoverableErrorsInThisFunction())
13776     DiscardCleanupsInEvaluationContext();
13777   assert(!Cleanup.exprNeedsCleanups() &&
13778          "cleanups within StmtExpr not correctly bound!");
13779   PopExpressionEvaluationContext();
13780 
13781   // FIXME: there are a variety of strange constraints to enforce here, for
13782   // example, it is not possible to goto into a stmt expression apparently.
13783   // More semantic analysis is needed.
13784 
13785   // If there are sub-stmts in the compound stmt, take the type of the last one
13786   // as the type of the stmtexpr.
13787   QualType Ty = Context.VoidTy;
13788   bool StmtExprMayBindToTemp = false;
13789   if (!Compound->body_empty()) {
13790     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13791     if (const auto *LastStmt =
13792             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13793       if (const Expr *Value = LastStmt->getExprStmt()) {
13794         StmtExprMayBindToTemp = true;
13795         Ty = Value->getType();
13796       }
13797     }
13798   }
13799 
13800   // FIXME: Check that expression type is complete/non-abstract; statement
13801   // expressions are not lvalues.
13802   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13803   if (StmtExprMayBindToTemp)
13804     return MaybeBindToTemporary(ResStmtExpr);
13805   return ResStmtExpr;
13806 }
13807 
13808 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13809   if (ER.isInvalid())
13810     return ExprError();
13811 
13812   // Do function/array conversion on the last expression, but not
13813   // lvalue-to-rvalue.  However, initialize an unqualified type.
13814   ER = DefaultFunctionArrayConversion(ER.get());
13815   if (ER.isInvalid())
13816     return ExprError();
13817   Expr *E = ER.get();
13818 
13819   if (E->isTypeDependent())
13820     return E;
13821 
13822   // In ARC, if the final expression ends in a consume, splice
13823   // the consume out and bind it later.  In the alternate case
13824   // (when dealing with a retainable type), the result
13825   // initialization will create a produce.  In both cases the
13826   // result will be +1, and we'll need to balance that out with
13827   // a bind.
13828   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13829   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13830     return Cast->getSubExpr();
13831 
13832   // FIXME: Provide a better location for the initialization.
13833   return PerformCopyInitialization(
13834       InitializedEntity::InitializeStmtExprResult(
13835           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13836       SourceLocation(), E);
13837 }
13838 
13839 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13840                                       TypeSourceInfo *TInfo,
13841                                       ArrayRef<OffsetOfComponent> Components,
13842                                       SourceLocation RParenLoc) {
13843   QualType ArgTy = TInfo->getType();
13844   bool Dependent = ArgTy->isDependentType();
13845   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13846 
13847   // We must have at least one component that refers to the type, and the first
13848   // one is known to be a field designator.  Verify that the ArgTy represents
13849   // a struct/union/class.
13850   if (!Dependent && !ArgTy->isRecordType())
13851     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13852                        << ArgTy << TypeRange);
13853 
13854   // Type must be complete per C99 7.17p3 because a declaring a variable
13855   // with an incomplete type would be ill-formed.
13856   if (!Dependent
13857       && RequireCompleteType(BuiltinLoc, ArgTy,
13858                              diag::err_offsetof_incomplete_type, TypeRange))
13859     return ExprError();
13860 
13861   bool DidWarnAboutNonPOD = false;
13862   QualType CurrentType = ArgTy;
13863   SmallVector<OffsetOfNode, 4> Comps;
13864   SmallVector<Expr*, 4> Exprs;
13865   for (const OffsetOfComponent &OC : Components) {
13866     if (OC.isBrackets) {
13867       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13868       if (!CurrentType->isDependentType()) {
13869         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13870         if(!AT)
13871           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13872                            << CurrentType);
13873         CurrentType = AT->getElementType();
13874       } else
13875         CurrentType = Context.DependentTy;
13876 
13877       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13878       if (IdxRval.isInvalid())
13879         return ExprError();
13880       Expr *Idx = IdxRval.get();
13881 
13882       // The expression must be an integral expression.
13883       // FIXME: An integral constant expression?
13884       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13885           !Idx->getType()->isIntegerType())
13886         return ExprError(
13887             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13888             << Idx->getSourceRange());
13889 
13890       // Record this array index.
13891       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13892       Exprs.push_back(Idx);
13893       continue;
13894     }
13895 
13896     // Offset of a field.
13897     if (CurrentType->isDependentType()) {
13898       // We have the offset of a field, but we can't look into the dependent
13899       // type. Just record the identifier of the field.
13900       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13901       CurrentType = Context.DependentTy;
13902       continue;
13903     }
13904 
13905     // We need to have a complete type to look into.
13906     if (RequireCompleteType(OC.LocStart, CurrentType,
13907                             diag::err_offsetof_incomplete_type))
13908       return ExprError();
13909 
13910     // Look for the designated field.
13911     const RecordType *RC = CurrentType->getAs<RecordType>();
13912     if (!RC)
13913       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13914                        << CurrentType);
13915     RecordDecl *RD = RC->getDecl();
13916 
13917     // C++ [lib.support.types]p5:
13918     //   The macro offsetof accepts a restricted set of type arguments in this
13919     //   International Standard. type shall be a POD structure or a POD union
13920     //   (clause 9).
13921     // C++11 [support.types]p4:
13922     //   If type is not a standard-layout class (Clause 9), the results are
13923     //   undefined.
13924     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13925       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13926       unsigned DiagID =
13927         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13928                             : diag::ext_offsetof_non_pod_type;
13929 
13930       if (!IsSafe && !DidWarnAboutNonPOD &&
13931           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13932                               PDiag(DiagID)
13933                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13934                               << CurrentType))
13935         DidWarnAboutNonPOD = true;
13936     }
13937 
13938     // Look for the field.
13939     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13940     LookupQualifiedName(R, RD);
13941     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13942     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13943     if (!MemberDecl) {
13944       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13945         MemberDecl = IndirectMemberDecl->getAnonField();
13946     }
13947 
13948     if (!MemberDecl)
13949       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13950                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13951                                                               OC.LocEnd));
13952 
13953     // C99 7.17p3:
13954     //   (If the specified member is a bit-field, the behavior is undefined.)
13955     //
13956     // We diagnose this as an error.
13957     if (MemberDecl->isBitField()) {
13958       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13959         << MemberDecl->getDeclName()
13960         << SourceRange(BuiltinLoc, RParenLoc);
13961       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13962       return ExprError();
13963     }
13964 
13965     RecordDecl *Parent = MemberDecl->getParent();
13966     if (IndirectMemberDecl)
13967       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13968 
13969     // If the member was found in a base class, introduce OffsetOfNodes for
13970     // the base class indirections.
13971     CXXBasePaths Paths;
13972     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13973                       Paths)) {
13974       if (Paths.getDetectedVirtual()) {
13975         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13976           << MemberDecl->getDeclName()
13977           << SourceRange(BuiltinLoc, RParenLoc);
13978         return ExprError();
13979       }
13980 
13981       CXXBasePath &Path = Paths.front();
13982       for (const CXXBasePathElement &B : Path)
13983         Comps.push_back(OffsetOfNode(B.Base));
13984     }
13985 
13986     if (IndirectMemberDecl) {
13987       for (auto *FI : IndirectMemberDecl->chain()) {
13988         assert(isa<FieldDecl>(FI));
13989         Comps.push_back(OffsetOfNode(OC.LocStart,
13990                                      cast<FieldDecl>(FI), OC.LocEnd));
13991       }
13992     } else
13993       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13994 
13995     CurrentType = MemberDecl->getType().getNonReferenceType();
13996   }
13997 
13998   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13999                               Comps, Exprs, RParenLoc);
14000 }
14001 
14002 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14003                                       SourceLocation BuiltinLoc,
14004                                       SourceLocation TypeLoc,
14005                                       ParsedType ParsedArgTy,
14006                                       ArrayRef<OffsetOfComponent> Components,
14007                                       SourceLocation RParenLoc) {
14008 
14009   TypeSourceInfo *ArgTInfo;
14010   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14011   if (ArgTy.isNull())
14012     return ExprError();
14013 
14014   if (!ArgTInfo)
14015     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14016 
14017   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14018 }
14019 
14020 
14021 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14022                                  Expr *CondExpr,
14023                                  Expr *LHSExpr, Expr *RHSExpr,
14024                                  SourceLocation RPLoc) {
14025   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
14026 
14027   ExprValueKind VK = VK_RValue;
14028   ExprObjectKind OK = OK_Ordinary;
14029   QualType resType;
14030   bool ValueDependent = false;
14031   bool CondIsTrue = false;
14032   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14033     resType = Context.DependentTy;
14034     ValueDependent = true;
14035   } else {
14036     // The conditional expression is required to be a constant expression.
14037     llvm::APSInt condEval(32);
14038     ExprResult CondICE
14039       = VerifyIntegerConstantExpression(CondExpr, &condEval,
14040           diag::err_typecheck_choose_expr_requires_constant, false);
14041     if (CondICE.isInvalid())
14042       return ExprError();
14043     CondExpr = CondICE.get();
14044     CondIsTrue = condEval.getZExtValue();
14045 
14046     // If the condition is > zero, then the AST type is the same as the LHSExpr.
14047     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14048 
14049     resType = ActiveExpr->getType();
14050     ValueDependent = ActiveExpr->isValueDependent();
14051     VK = ActiveExpr->getValueKind();
14052     OK = ActiveExpr->getObjectKind();
14053   }
14054 
14055   return new (Context)
14056       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14057                  CondIsTrue, resType->isDependentType(), ValueDependent);
14058 }
14059 
14060 //===----------------------------------------------------------------------===//
14061 // Clang Extensions.
14062 //===----------------------------------------------------------------------===//
14063 
14064 /// ActOnBlockStart - This callback is invoked when a block literal is started.
14065 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14066   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14067 
14068   if (LangOpts.CPlusPlus) {
14069     MangleNumberingContext *MCtx;
14070     Decl *ManglingContextDecl;
14071     std::tie(MCtx, ManglingContextDecl) =
14072         getCurrentMangleNumberContext(Block->getDeclContext());
14073     if (MCtx) {
14074       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14075       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14076     }
14077   }
14078 
14079   PushBlockScope(CurScope, Block);
14080   CurContext->addDecl(Block);
14081   if (CurScope)
14082     PushDeclContext(CurScope, Block);
14083   else
14084     CurContext = Block;
14085 
14086   getCurBlock()->HasImplicitReturnType = true;
14087 
14088   // Enter a new evaluation context to insulate the block from any
14089   // cleanups from the enclosing full-expression.
14090   PushExpressionEvaluationContext(
14091       ExpressionEvaluationContext::PotentiallyEvaluated);
14092 }
14093 
14094 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14095                                Scope *CurScope) {
14096   assert(ParamInfo.getIdentifier() == nullptr &&
14097          "block-id should have no identifier!");
14098   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14099   BlockScopeInfo *CurBlock = getCurBlock();
14100 
14101   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14102   QualType T = Sig->getType();
14103 
14104   // FIXME: We should allow unexpanded parameter packs here, but that would,
14105   // in turn, make the block expression contain unexpanded parameter packs.
14106   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14107     // Drop the parameters.
14108     FunctionProtoType::ExtProtoInfo EPI;
14109     EPI.HasTrailingReturn = false;
14110     EPI.TypeQuals.addConst();
14111     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14112     Sig = Context.getTrivialTypeSourceInfo(T);
14113   }
14114 
14115   // GetTypeForDeclarator always produces a function type for a block
14116   // literal signature.  Furthermore, it is always a FunctionProtoType
14117   // unless the function was written with a typedef.
14118   assert(T->isFunctionType() &&
14119          "GetTypeForDeclarator made a non-function block signature");
14120 
14121   // Look for an explicit signature in that function type.
14122   FunctionProtoTypeLoc ExplicitSignature;
14123 
14124   if ((ExplicitSignature = Sig->getTypeLoc()
14125                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14126 
14127     // Check whether that explicit signature was synthesized by
14128     // GetTypeForDeclarator.  If so, don't save that as part of the
14129     // written signature.
14130     if (ExplicitSignature.getLocalRangeBegin() ==
14131         ExplicitSignature.getLocalRangeEnd()) {
14132       // This would be much cheaper if we stored TypeLocs instead of
14133       // TypeSourceInfos.
14134       TypeLoc Result = ExplicitSignature.getReturnLoc();
14135       unsigned Size = Result.getFullDataSize();
14136       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14137       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14138 
14139       ExplicitSignature = FunctionProtoTypeLoc();
14140     }
14141   }
14142 
14143   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14144   CurBlock->FunctionType = T;
14145 
14146   const FunctionType *Fn = T->getAs<FunctionType>();
14147   QualType RetTy = Fn->getReturnType();
14148   bool isVariadic =
14149     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14150 
14151   CurBlock->TheDecl->setIsVariadic(isVariadic);
14152 
14153   // Context.DependentTy is used as a placeholder for a missing block
14154   // return type.  TODO:  what should we do with declarators like:
14155   //   ^ * { ... }
14156   // If the answer is "apply template argument deduction"....
14157   if (RetTy != Context.DependentTy) {
14158     CurBlock->ReturnType = RetTy;
14159     CurBlock->TheDecl->setBlockMissingReturnType(false);
14160     CurBlock->HasImplicitReturnType = false;
14161   }
14162 
14163   // Push block parameters from the declarator if we had them.
14164   SmallVector<ParmVarDecl*, 8> Params;
14165   if (ExplicitSignature) {
14166     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14167       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14168       if (Param->getIdentifier() == nullptr &&
14169           !Param->isImplicit() &&
14170           !Param->isInvalidDecl() &&
14171           !getLangOpts().CPlusPlus)
14172         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14173       Params.push_back(Param);
14174     }
14175 
14176   // Fake up parameter variables if we have a typedef, like
14177   //   ^ fntype { ... }
14178   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14179     for (const auto &I : Fn->param_types()) {
14180       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14181           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14182       Params.push_back(Param);
14183     }
14184   }
14185 
14186   // Set the parameters on the block decl.
14187   if (!Params.empty()) {
14188     CurBlock->TheDecl->setParams(Params);
14189     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14190                              /*CheckParameterNames=*/false);
14191   }
14192 
14193   // Finally we can process decl attributes.
14194   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14195 
14196   // Put the parameter variables in scope.
14197   for (auto AI : CurBlock->TheDecl->parameters()) {
14198     AI->setOwningFunction(CurBlock->TheDecl);
14199 
14200     // If this has an identifier, add it to the scope stack.
14201     if (AI->getIdentifier()) {
14202       CheckShadow(CurBlock->TheScope, AI);
14203 
14204       PushOnScopeChains(AI, CurBlock->TheScope);
14205     }
14206   }
14207 }
14208 
14209 /// ActOnBlockError - If there is an error parsing a block, this callback
14210 /// is invoked to pop the information about the block from the action impl.
14211 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14212   // Leave the expression-evaluation context.
14213   DiscardCleanupsInEvaluationContext();
14214   PopExpressionEvaluationContext();
14215 
14216   // Pop off CurBlock, handle nested blocks.
14217   PopDeclContext();
14218   PopFunctionScopeInfo();
14219 }
14220 
14221 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14222 /// literal was successfully completed.  ^(int x){...}
14223 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14224                                     Stmt *Body, Scope *CurScope) {
14225   // If blocks are disabled, emit an error.
14226   if (!LangOpts.Blocks)
14227     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14228 
14229   // Leave the expression-evaluation context.
14230   if (hasAnyUnrecoverableErrorsInThisFunction())
14231     DiscardCleanupsInEvaluationContext();
14232   assert(!Cleanup.exprNeedsCleanups() &&
14233          "cleanups within block not correctly bound!");
14234   PopExpressionEvaluationContext();
14235 
14236   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14237   BlockDecl *BD = BSI->TheDecl;
14238 
14239   if (BSI->HasImplicitReturnType)
14240     deduceClosureReturnType(*BSI);
14241 
14242   QualType RetTy = Context.VoidTy;
14243   if (!BSI->ReturnType.isNull())
14244     RetTy = BSI->ReturnType;
14245 
14246   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14247   QualType BlockTy;
14248 
14249   // If the user wrote a function type in some form, try to use that.
14250   if (!BSI->FunctionType.isNull()) {
14251     const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14252 
14253     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14254     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14255 
14256     // Turn protoless block types into nullary block types.
14257     if (isa<FunctionNoProtoType>(FTy)) {
14258       FunctionProtoType::ExtProtoInfo EPI;
14259       EPI.ExtInfo = Ext;
14260       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14261 
14262     // Otherwise, if we don't need to change anything about the function type,
14263     // preserve its sugar structure.
14264     } else if (FTy->getReturnType() == RetTy &&
14265                (!NoReturn || FTy->getNoReturnAttr())) {
14266       BlockTy = BSI->FunctionType;
14267 
14268     // Otherwise, make the minimal modifications to the function type.
14269     } else {
14270       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14271       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14272       EPI.TypeQuals = Qualifiers();
14273       EPI.ExtInfo = Ext;
14274       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14275     }
14276 
14277   // If we don't have a function type, just build one from nothing.
14278   } else {
14279     FunctionProtoType::ExtProtoInfo EPI;
14280     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14281     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14282   }
14283 
14284   DiagnoseUnusedParameters(BD->parameters());
14285   BlockTy = Context.getBlockPointerType(BlockTy);
14286 
14287   // If needed, diagnose invalid gotos and switches in the block.
14288   if (getCurFunction()->NeedsScopeChecking() &&
14289       !PP.isCodeCompletionEnabled())
14290     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14291 
14292   BD->setBody(cast<CompoundStmt>(Body));
14293 
14294   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14295     DiagnoseUnguardedAvailabilityViolations(BD);
14296 
14297   // Try to apply the named return value optimization. We have to check again
14298   // if we can do this, though, because blocks keep return statements around
14299   // to deduce an implicit return type.
14300   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14301       !BD->isDependentContext())
14302     computeNRVO(Body, BSI);
14303 
14304   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14305       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14306     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14307                           NTCUK_Destruct|NTCUK_Copy);
14308 
14309   PopDeclContext();
14310 
14311   // Pop the block scope now but keep it alive to the end of this function.
14312   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14313   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14314 
14315   // Set the captured variables on the block.
14316   SmallVector<BlockDecl::Capture, 4> Captures;
14317   for (Capture &Cap : BSI->Captures) {
14318     if (Cap.isInvalid() || Cap.isThisCapture())
14319       continue;
14320 
14321     VarDecl *Var = Cap.getVariable();
14322     Expr *CopyExpr = nullptr;
14323     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14324       if (const RecordType *Record =
14325               Cap.getCaptureType()->getAs<RecordType>()) {
14326         // The capture logic needs the destructor, so make sure we mark it.
14327         // Usually this is unnecessary because most local variables have
14328         // their destructors marked at declaration time, but parameters are
14329         // an exception because it's technically only the call site that
14330         // actually requires the destructor.
14331         if (isa<ParmVarDecl>(Var))
14332           FinalizeVarWithDestructor(Var, Record);
14333 
14334         // Enter a separate potentially-evaluated context while building block
14335         // initializers to isolate their cleanups from those of the block
14336         // itself.
14337         // FIXME: Is this appropriate even when the block itself occurs in an
14338         // unevaluated operand?
14339         EnterExpressionEvaluationContext EvalContext(
14340             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14341 
14342         SourceLocation Loc = Cap.getLocation();
14343 
14344         ExprResult Result = BuildDeclarationNameExpr(
14345             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14346 
14347         // According to the blocks spec, the capture of a variable from
14348         // the stack requires a const copy constructor.  This is not true
14349         // of the copy/move done to move a __block variable to the heap.
14350         if (!Result.isInvalid() &&
14351             !Result.get()->getType().isConstQualified()) {
14352           Result = ImpCastExprToType(Result.get(),
14353                                      Result.get()->getType().withConst(),
14354                                      CK_NoOp, VK_LValue);
14355         }
14356 
14357         if (!Result.isInvalid()) {
14358           Result = PerformCopyInitialization(
14359               InitializedEntity::InitializeBlock(Var->getLocation(),
14360                                                  Cap.getCaptureType(), false),
14361               Loc, Result.get());
14362         }
14363 
14364         // Build a full-expression copy expression if initialization
14365         // succeeded and used a non-trivial constructor.  Recover from
14366         // errors by pretending that the copy isn't necessary.
14367         if (!Result.isInvalid() &&
14368             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14369                 ->isTrivial()) {
14370           Result = MaybeCreateExprWithCleanups(Result);
14371           CopyExpr = Result.get();
14372         }
14373       }
14374     }
14375 
14376     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14377                               CopyExpr);
14378     Captures.push_back(NewCap);
14379   }
14380   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14381 
14382   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14383 
14384   // If the block isn't obviously global, i.e. it captures anything at
14385   // all, then we need to do a few things in the surrounding context:
14386   if (Result->getBlockDecl()->hasCaptures()) {
14387     // First, this expression has a new cleanup object.
14388     ExprCleanupObjects.push_back(Result->getBlockDecl());
14389     Cleanup.setExprNeedsCleanups(true);
14390 
14391     // It also gets a branch-protected scope if any of the captured
14392     // variables needs destruction.
14393     for (const auto &CI : Result->getBlockDecl()->captures()) {
14394       const VarDecl *var = CI.getVariable();
14395       if (var->getType().isDestructedType() != QualType::DK_none) {
14396         setFunctionHasBranchProtectedScope();
14397         break;
14398       }
14399     }
14400   }
14401 
14402   if (getCurFunction())
14403     getCurFunction()->addBlock(BD);
14404 
14405   return Result;
14406 }
14407 
14408 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14409                             SourceLocation RPLoc) {
14410   TypeSourceInfo *TInfo;
14411   GetTypeFromParser(Ty, &TInfo);
14412   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14413 }
14414 
14415 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14416                                 Expr *E, TypeSourceInfo *TInfo,
14417                                 SourceLocation RPLoc) {
14418   Expr *OrigExpr = E;
14419   bool IsMS = false;
14420 
14421   // CUDA device code does not support varargs.
14422   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14423     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14424       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14425       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14426         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14427     }
14428   }
14429 
14430   // NVPTX does not support va_arg expression.
14431   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14432       Context.getTargetInfo().getTriple().isNVPTX())
14433     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14434 
14435   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14436   // as Microsoft ABI on an actual Microsoft platform, where
14437   // __builtin_ms_va_list and __builtin_va_list are the same.)
14438   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14439       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14440     QualType MSVaListType = Context.getBuiltinMSVaListType();
14441     if (Context.hasSameType(MSVaListType, E->getType())) {
14442       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14443         return ExprError();
14444       IsMS = true;
14445     }
14446   }
14447 
14448   // Get the va_list type
14449   QualType VaListType = Context.getBuiltinVaListType();
14450   if (!IsMS) {
14451     if (VaListType->isArrayType()) {
14452       // Deal with implicit array decay; for example, on x86-64,
14453       // va_list is an array, but it's supposed to decay to
14454       // a pointer for va_arg.
14455       VaListType = Context.getArrayDecayedType(VaListType);
14456       // Make sure the input expression also decays appropriately.
14457       ExprResult Result = UsualUnaryConversions(E);
14458       if (Result.isInvalid())
14459         return ExprError();
14460       E = Result.get();
14461     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14462       // If va_list is a record type and we are compiling in C++ mode,
14463       // check the argument using reference binding.
14464       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14465           Context, Context.getLValueReferenceType(VaListType), false);
14466       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14467       if (Init.isInvalid())
14468         return ExprError();
14469       E = Init.getAs<Expr>();
14470     } else {
14471       // Otherwise, the va_list argument must be an l-value because
14472       // it is modified by va_arg.
14473       if (!E->isTypeDependent() &&
14474           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14475         return ExprError();
14476     }
14477   }
14478 
14479   if (!IsMS && !E->isTypeDependent() &&
14480       !Context.hasSameType(VaListType, E->getType()))
14481     return ExprError(
14482         Diag(E->getBeginLoc(),
14483              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14484         << OrigExpr->getType() << E->getSourceRange());
14485 
14486   if (!TInfo->getType()->isDependentType()) {
14487     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14488                             diag::err_second_parameter_to_va_arg_incomplete,
14489                             TInfo->getTypeLoc()))
14490       return ExprError();
14491 
14492     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14493                                TInfo->getType(),
14494                                diag::err_second_parameter_to_va_arg_abstract,
14495                                TInfo->getTypeLoc()))
14496       return ExprError();
14497 
14498     if (!TInfo->getType().isPODType(Context)) {
14499       Diag(TInfo->getTypeLoc().getBeginLoc(),
14500            TInfo->getType()->isObjCLifetimeType()
14501              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14502              : diag::warn_second_parameter_to_va_arg_not_pod)
14503         << TInfo->getType()
14504         << TInfo->getTypeLoc().getSourceRange();
14505     }
14506 
14507     // Check for va_arg where arguments of the given type will be promoted
14508     // (i.e. this va_arg is guaranteed to have undefined behavior).
14509     QualType PromoteType;
14510     if (TInfo->getType()->isPromotableIntegerType()) {
14511       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14512       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14513         PromoteType = QualType();
14514     }
14515     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14516       PromoteType = Context.DoubleTy;
14517     if (!PromoteType.isNull())
14518       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14519                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14520                           << TInfo->getType()
14521                           << PromoteType
14522                           << TInfo->getTypeLoc().getSourceRange());
14523   }
14524 
14525   QualType T = TInfo->getType().getNonLValueExprType(Context);
14526   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14527 }
14528 
14529 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14530   // The type of __null will be int or long, depending on the size of
14531   // pointers on the target.
14532   QualType Ty;
14533   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14534   if (pw == Context.getTargetInfo().getIntWidth())
14535     Ty = Context.IntTy;
14536   else if (pw == Context.getTargetInfo().getLongWidth())
14537     Ty = Context.LongTy;
14538   else if (pw == Context.getTargetInfo().getLongLongWidth())
14539     Ty = Context.LongLongTy;
14540   else {
14541     llvm_unreachable("I don't know size of pointer!");
14542   }
14543 
14544   return new (Context) GNUNullExpr(Ty, TokenLoc);
14545 }
14546 
14547 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14548                                     SourceLocation BuiltinLoc,
14549                                     SourceLocation RPLoc) {
14550   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14551 }
14552 
14553 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14554                                     SourceLocation BuiltinLoc,
14555                                     SourceLocation RPLoc,
14556                                     DeclContext *ParentContext) {
14557   return new (Context)
14558       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14559 }
14560 
14561 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14562                                               bool Diagnose) {
14563   if (!getLangOpts().ObjC)
14564     return false;
14565 
14566   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14567   if (!PT)
14568     return false;
14569 
14570   if (!PT->isObjCIdType()) {
14571     // Check if the destination is the 'NSString' interface.
14572     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14573     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14574       return false;
14575   }
14576 
14577   // Ignore any parens, implicit casts (should only be
14578   // array-to-pointer decays), and not-so-opaque values.  The last is
14579   // important for making this trigger for property assignments.
14580   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14581   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14582     if (OV->getSourceExpr())
14583       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14584 
14585   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14586   if (!SL || !SL->isAscii())
14587     return false;
14588   if (Diagnose) {
14589     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14590         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14591     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14592   }
14593   return true;
14594 }
14595 
14596 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14597                                               const Expr *SrcExpr) {
14598   if (!DstType->isFunctionPointerType() ||
14599       !SrcExpr->getType()->isFunctionType())
14600     return false;
14601 
14602   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14603   if (!DRE)
14604     return false;
14605 
14606   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14607   if (!FD)
14608     return false;
14609 
14610   return !S.checkAddressOfFunctionIsAvailable(FD,
14611                                               /*Complain=*/true,
14612                                               SrcExpr->getBeginLoc());
14613 }
14614 
14615 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14616                                     SourceLocation Loc,
14617                                     QualType DstType, QualType SrcType,
14618                                     Expr *SrcExpr, AssignmentAction Action,
14619                                     bool *Complained) {
14620   if (Complained)
14621     *Complained = false;
14622 
14623   // Decode the result (notice that AST's are still created for extensions).
14624   bool CheckInferredResultType = false;
14625   bool isInvalid = false;
14626   unsigned DiagKind = 0;
14627   FixItHint Hint;
14628   ConversionFixItGenerator ConvHints;
14629   bool MayHaveConvFixit = false;
14630   bool MayHaveFunctionDiff = false;
14631   const ObjCInterfaceDecl *IFace = nullptr;
14632   const ObjCProtocolDecl *PDecl = nullptr;
14633 
14634   switch (ConvTy) {
14635   case Compatible:
14636       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14637       return false;
14638 
14639   case PointerToInt:
14640     DiagKind = diag::ext_typecheck_convert_pointer_int;
14641     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14642     MayHaveConvFixit = true;
14643     break;
14644   case IntToPointer:
14645     DiagKind = diag::ext_typecheck_convert_int_pointer;
14646     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14647     MayHaveConvFixit = true;
14648     break;
14649   case IncompatiblePointer:
14650     if (Action == AA_Passing_CFAudited)
14651       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14652     else if (SrcType->isFunctionPointerType() &&
14653              DstType->isFunctionPointerType())
14654       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14655     else
14656       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14657 
14658     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14659       SrcType->isObjCObjectPointerType();
14660     if (Hint.isNull() && !CheckInferredResultType) {
14661       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14662     }
14663     else if (CheckInferredResultType) {
14664       SrcType = SrcType.getUnqualifiedType();
14665       DstType = DstType.getUnqualifiedType();
14666     }
14667     MayHaveConvFixit = true;
14668     break;
14669   case IncompatiblePointerSign:
14670     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14671     break;
14672   case FunctionVoidPointer:
14673     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14674     break;
14675   case IncompatiblePointerDiscardsQualifiers: {
14676     // Perform array-to-pointer decay if necessary.
14677     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14678 
14679     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14680     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14681     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14682       DiagKind = diag::err_typecheck_incompatible_address_space;
14683       break;
14684 
14685     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14686       DiagKind = diag::err_typecheck_incompatible_ownership;
14687       break;
14688     }
14689 
14690     llvm_unreachable("unknown error case for discarding qualifiers!");
14691     // fallthrough
14692   }
14693   case CompatiblePointerDiscardsQualifiers:
14694     // If the qualifiers lost were because we were applying the
14695     // (deprecated) C++ conversion from a string literal to a char*
14696     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14697     // Ideally, this check would be performed in
14698     // checkPointerTypesForAssignment. However, that would require a
14699     // bit of refactoring (so that the second argument is an
14700     // expression, rather than a type), which should be done as part
14701     // of a larger effort to fix checkPointerTypesForAssignment for
14702     // C++ semantics.
14703     if (getLangOpts().CPlusPlus &&
14704         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14705       return false;
14706     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14707     break;
14708   case IncompatibleNestedPointerQualifiers:
14709     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14710     break;
14711   case IncompatibleNestedPointerAddressSpaceMismatch:
14712     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14713     break;
14714   case IntToBlockPointer:
14715     DiagKind = diag::err_int_to_block_pointer;
14716     break;
14717   case IncompatibleBlockPointer:
14718     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14719     break;
14720   case IncompatibleObjCQualifiedId: {
14721     if (SrcType->isObjCQualifiedIdType()) {
14722       const ObjCObjectPointerType *srcOPT =
14723                 SrcType->castAs<ObjCObjectPointerType>();
14724       for (auto *srcProto : srcOPT->quals()) {
14725         PDecl = srcProto;
14726         break;
14727       }
14728       if (const ObjCInterfaceType *IFaceT =
14729             DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14730         IFace = IFaceT->getDecl();
14731     }
14732     else if (DstType->isObjCQualifiedIdType()) {
14733       const ObjCObjectPointerType *dstOPT =
14734         DstType->castAs<ObjCObjectPointerType>();
14735       for (auto *dstProto : dstOPT->quals()) {
14736         PDecl = dstProto;
14737         break;
14738       }
14739       if (const ObjCInterfaceType *IFaceT =
14740             SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14741         IFace = IFaceT->getDecl();
14742     }
14743     DiagKind = diag::warn_incompatible_qualified_id;
14744     break;
14745   }
14746   case IncompatibleVectors:
14747     DiagKind = diag::warn_incompatible_vectors;
14748     break;
14749   case IncompatibleObjCWeakRef:
14750     DiagKind = diag::err_arc_weak_unavailable_assign;
14751     break;
14752   case Incompatible:
14753     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14754       if (Complained)
14755         *Complained = true;
14756       return true;
14757     }
14758 
14759     DiagKind = diag::err_typecheck_convert_incompatible;
14760     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14761     MayHaveConvFixit = true;
14762     isInvalid = true;
14763     MayHaveFunctionDiff = true;
14764     break;
14765   }
14766 
14767   QualType FirstType, SecondType;
14768   switch (Action) {
14769   case AA_Assigning:
14770   case AA_Initializing:
14771     // The destination type comes first.
14772     FirstType = DstType;
14773     SecondType = SrcType;
14774     break;
14775 
14776   case AA_Returning:
14777   case AA_Passing:
14778   case AA_Passing_CFAudited:
14779   case AA_Converting:
14780   case AA_Sending:
14781   case AA_Casting:
14782     // The source type comes first.
14783     FirstType = SrcType;
14784     SecondType = DstType;
14785     break;
14786   }
14787 
14788   PartialDiagnostic FDiag = PDiag(DiagKind);
14789   if (Action == AA_Passing_CFAudited)
14790     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14791   else
14792     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14793 
14794   // If we can fix the conversion, suggest the FixIts.
14795   assert(ConvHints.isNull() || Hint.isNull());
14796   if (!ConvHints.isNull()) {
14797     for (FixItHint &H : ConvHints.Hints)
14798       FDiag << H;
14799   } else {
14800     FDiag << Hint;
14801   }
14802   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14803 
14804   if (MayHaveFunctionDiff)
14805     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14806 
14807   Diag(Loc, FDiag);
14808   if (DiagKind == diag::warn_incompatible_qualified_id &&
14809       PDecl && IFace && !IFace->hasDefinition())
14810       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14811         << IFace << PDecl;
14812 
14813   if (SecondType == Context.OverloadTy)
14814     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14815                               FirstType, /*TakingAddress=*/true);
14816 
14817   if (CheckInferredResultType)
14818     EmitRelatedResultTypeNote(SrcExpr);
14819 
14820   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14821     EmitRelatedResultTypeNoteForReturn(DstType);
14822 
14823   if (Complained)
14824     *Complained = true;
14825   return isInvalid;
14826 }
14827 
14828 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14829                                                  llvm::APSInt *Result) {
14830   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14831   public:
14832     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14833       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14834     }
14835   } Diagnoser;
14836 
14837   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14838 }
14839 
14840 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14841                                                  llvm::APSInt *Result,
14842                                                  unsigned DiagID,
14843                                                  bool AllowFold) {
14844   class IDDiagnoser : public VerifyICEDiagnoser {
14845     unsigned DiagID;
14846 
14847   public:
14848     IDDiagnoser(unsigned DiagID)
14849       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14850 
14851     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14852       S.Diag(Loc, DiagID) << SR;
14853     }
14854   } Diagnoser(DiagID);
14855 
14856   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14857 }
14858 
14859 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14860                                             SourceRange SR) {
14861   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14862 }
14863 
14864 ExprResult
14865 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14866                                       VerifyICEDiagnoser &Diagnoser,
14867                                       bool AllowFold) {
14868   SourceLocation DiagLoc = E->getBeginLoc();
14869 
14870   if (getLangOpts().CPlusPlus11) {
14871     // C++11 [expr.const]p5:
14872     //   If an expression of literal class type is used in a context where an
14873     //   integral constant expression is required, then that class type shall
14874     //   have a single non-explicit conversion function to an integral or
14875     //   unscoped enumeration type
14876     ExprResult Converted;
14877     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14878     public:
14879       CXX11ConvertDiagnoser(bool Silent)
14880           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14881                                 Silent, true) {}
14882 
14883       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14884                                            QualType T) override {
14885         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14886       }
14887 
14888       SemaDiagnosticBuilder diagnoseIncomplete(
14889           Sema &S, SourceLocation Loc, QualType T) override {
14890         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14891       }
14892 
14893       SemaDiagnosticBuilder diagnoseExplicitConv(
14894           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14895         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14896       }
14897 
14898       SemaDiagnosticBuilder noteExplicitConv(
14899           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14900         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14901                  << ConvTy->isEnumeralType() << ConvTy;
14902       }
14903 
14904       SemaDiagnosticBuilder diagnoseAmbiguous(
14905           Sema &S, SourceLocation Loc, QualType T) override {
14906         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14907       }
14908 
14909       SemaDiagnosticBuilder noteAmbiguous(
14910           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14911         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14912                  << ConvTy->isEnumeralType() << ConvTy;
14913       }
14914 
14915       SemaDiagnosticBuilder diagnoseConversion(
14916           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14917         llvm_unreachable("conversion functions are permitted");
14918       }
14919     } ConvertDiagnoser(Diagnoser.Suppress);
14920 
14921     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14922                                                     ConvertDiagnoser);
14923     if (Converted.isInvalid())
14924       return Converted;
14925     E = Converted.get();
14926     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14927       return ExprError();
14928   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14929     // An ICE must be of integral or unscoped enumeration type.
14930     if (!Diagnoser.Suppress)
14931       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14932     return ExprError();
14933   }
14934 
14935   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14936   // in the non-ICE case.
14937   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14938     if (Result)
14939       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14940     if (!isa<ConstantExpr>(E))
14941       E = ConstantExpr::Create(Context, E);
14942     return E;
14943   }
14944 
14945   Expr::EvalResult EvalResult;
14946   SmallVector<PartialDiagnosticAt, 8> Notes;
14947   EvalResult.Diag = &Notes;
14948 
14949   // Try to evaluate the expression, and produce diagnostics explaining why it's
14950   // not a constant expression as a side-effect.
14951   bool Folded =
14952       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14953       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14954 
14955   if (!isa<ConstantExpr>(E))
14956     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14957 
14958   // In C++11, we can rely on diagnostics being produced for any expression
14959   // which is not a constant expression. If no diagnostics were produced, then
14960   // this is a constant expression.
14961   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14962     if (Result)
14963       *Result = EvalResult.Val.getInt();
14964     return E;
14965   }
14966 
14967   // If our only note is the usual "invalid subexpression" note, just point
14968   // the caret at its location rather than producing an essentially
14969   // redundant note.
14970   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14971         diag::note_invalid_subexpr_in_const_expr) {
14972     DiagLoc = Notes[0].first;
14973     Notes.clear();
14974   }
14975 
14976   if (!Folded || !AllowFold) {
14977     if (!Diagnoser.Suppress) {
14978       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14979       for (const PartialDiagnosticAt &Note : Notes)
14980         Diag(Note.first, Note.second);
14981     }
14982 
14983     return ExprError();
14984   }
14985 
14986   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14987   for (const PartialDiagnosticAt &Note : Notes)
14988     Diag(Note.first, Note.second);
14989 
14990   if (Result)
14991     *Result = EvalResult.Val.getInt();
14992   return E;
14993 }
14994 
14995 namespace {
14996   // Handle the case where we conclude a expression which we speculatively
14997   // considered to be unevaluated is actually evaluated.
14998   class TransformToPE : public TreeTransform<TransformToPE> {
14999     typedef TreeTransform<TransformToPE> BaseTransform;
15000 
15001   public:
15002     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15003 
15004     // Make sure we redo semantic analysis
15005     bool AlwaysRebuild() { return true; }
15006     bool ReplacingOriginal() { return true; }
15007 
15008     // We need to special-case DeclRefExprs referring to FieldDecls which
15009     // are not part of a member pointer formation; normal TreeTransforming
15010     // doesn't catch this case because of the way we represent them in the AST.
15011     // FIXME: This is a bit ugly; is it really the best way to handle this
15012     // case?
15013     //
15014     // Error on DeclRefExprs referring to FieldDecls.
15015     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15016       if (isa<FieldDecl>(E->getDecl()) &&
15017           !SemaRef.isUnevaluatedContext())
15018         return SemaRef.Diag(E->getLocation(),
15019                             diag::err_invalid_non_static_member_use)
15020             << E->getDecl() << E->getSourceRange();
15021 
15022       return BaseTransform::TransformDeclRefExpr(E);
15023     }
15024 
15025     // Exception: filter out member pointer formation
15026     ExprResult TransformUnaryOperator(UnaryOperator *E) {
15027       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15028         return E;
15029 
15030       return BaseTransform::TransformUnaryOperator(E);
15031     }
15032 
15033     // The body of a lambda-expression is in a separate expression evaluation
15034     // context so never needs to be transformed.
15035     // FIXME: Ideally we wouldn't transform the closure type either, and would
15036     // just recreate the capture expressions and lambda expression.
15037     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15038       return SkipLambdaBody(E, Body);
15039     }
15040   };
15041 }
15042 
15043 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15044   assert(isUnevaluatedContext() &&
15045          "Should only transform unevaluated expressions");
15046   ExprEvalContexts.back().Context =
15047       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15048   if (isUnevaluatedContext())
15049     return E;
15050   return TransformToPE(*this).TransformExpr(E);
15051 }
15052 
15053 void
15054 Sema::PushExpressionEvaluationContext(
15055     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15056     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15057   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15058                                 LambdaContextDecl, ExprContext);
15059   Cleanup.reset();
15060   if (!MaybeODRUseExprs.empty())
15061     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15062 }
15063 
15064 void
15065 Sema::PushExpressionEvaluationContext(
15066     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15067     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15068   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15069   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15070 }
15071 
15072 namespace {
15073 
15074 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15075   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15076   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15077     if (E->getOpcode() == UO_Deref)
15078       return CheckPossibleDeref(S, E->getSubExpr());
15079   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15080     return CheckPossibleDeref(S, E->getBase());
15081   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15082     return CheckPossibleDeref(S, E->getBase());
15083   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15084     QualType Inner;
15085     QualType Ty = E->getType();
15086     if (const auto *Ptr = Ty->getAs<PointerType>())
15087       Inner = Ptr->getPointeeType();
15088     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15089       Inner = Arr->getElementType();
15090     else
15091       return nullptr;
15092 
15093     if (Inner->hasAttr(attr::NoDeref))
15094       return E;
15095   }
15096   return nullptr;
15097 }
15098 
15099 } // namespace
15100 
15101 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15102   for (const Expr *E : Rec.PossibleDerefs) {
15103     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15104     if (DeclRef) {
15105       const ValueDecl *Decl = DeclRef->getDecl();
15106       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15107           << Decl->getName() << E->getSourceRange();
15108       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15109     } else {
15110       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15111           << E->getSourceRange();
15112     }
15113   }
15114   Rec.PossibleDerefs.clear();
15115 }
15116 
15117 /// Check whether E, which is either a discarded-value expression or an
15118 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15119 /// and if so, remove it from the list of volatile-qualified assignments that
15120 /// we are going to warn are deprecated.
15121 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15122   if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15123     return;
15124 
15125   // Note: ignoring parens here is not justified by the standard rules, but
15126   // ignoring parentheses seems like a more reasonable approach, and this only
15127   // drives a deprecation warning so doesn't affect conformance.
15128   if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15129     if (BO->getOpcode() == BO_Assign) {
15130       auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15131       LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15132                  LHSs.end());
15133     }
15134   }
15135 }
15136 
15137 void Sema::PopExpressionEvaluationContext() {
15138   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15139   unsigned NumTypos = Rec.NumTypos;
15140 
15141   if (!Rec.Lambdas.empty()) {
15142     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15143     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15144         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15145       unsigned D;
15146       if (Rec.isUnevaluated()) {
15147         // C++11 [expr.prim.lambda]p2:
15148         //   A lambda-expression shall not appear in an unevaluated operand
15149         //   (Clause 5).
15150         D = diag::err_lambda_unevaluated_operand;
15151       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15152         // C++1y [expr.const]p2:
15153         //   A conditional-expression e is a core constant expression unless the
15154         //   evaluation of e, following the rules of the abstract machine, would
15155         //   evaluate [...] a lambda-expression.
15156         D = diag::err_lambda_in_constant_expression;
15157       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15158         // C++17 [expr.prim.lamda]p2:
15159         // A lambda-expression shall not appear [...] in a template-argument.
15160         D = diag::err_lambda_in_invalid_context;
15161       } else
15162         llvm_unreachable("Couldn't infer lambda error message.");
15163 
15164       for (const auto *L : Rec.Lambdas)
15165         Diag(L->getBeginLoc(), D);
15166     }
15167   }
15168 
15169   WarnOnPendingNoDerefs(Rec);
15170 
15171   // Warn on any volatile-qualified simple-assignments that are not discarded-
15172   // value expressions nor unevaluated operands (those cases get removed from
15173   // this list by CheckUnusedVolatileAssignment).
15174   for (auto *BO : Rec.VolatileAssignmentLHSs)
15175     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15176         << BO->getType();
15177 
15178   // When are coming out of an unevaluated context, clear out any
15179   // temporaries that we may have created as part of the evaluation of
15180   // the expression in that context: they aren't relevant because they
15181   // will never be constructed.
15182   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15183     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15184                              ExprCleanupObjects.end());
15185     Cleanup = Rec.ParentCleanup;
15186     CleanupVarDeclMarking();
15187     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15188   // Otherwise, merge the contexts together.
15189   } else {
15190     Cleanup.mergeFrom(Rec.ParentCleanup);
15191     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15192                             Rec.SavedMaybeODRUseExprs.end());
15193   }
15194 
15195   // Pop the current expression evaluation context off the stack.
15196   ExprEvalContexts.pop_back();
15197 
15198   // The global expression evaluation context record is never popped.
15199   ExprEvalContexts.back().NumTypos += NumTypos;
15200 }
15201 
15202 void Sema::DiscardCleanupsInEvaluationContext() {
15203   ExprCleanupObjects.erase(
15204          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15205          ExprCleanupObjects.end());
15206   Cleanup.reset();
15207   MaybeODRUseExprs.clear();
15208 }
15209 
15210 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15211   ExprResult Result = CheckPlaceholderExpr(E);
15212   if (Result.isInvalid())
15213     return ExprError();
15214   E = Result.get();
15215   if (!E->getType()->isVariablyModifiedType())
15216     return E;
15217   return TransformToPotentiallyEvaluated(E);
15218 }
15219 
15220 /// Are we in a context that is potentially constant evaluated per C++20
15221 /// [expr.const]p12?
15222 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15223   /// C++2a [expr.const]p12:
15224   //   An expression or conversion is potentially constant evaluated if it is
15225   switch (SemaRef.ExprEvalContexts.back().Context) {
15226     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15227       // -- a manifestly constant-evaluated expression,
15228     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15229     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15230     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15231       // -- a potentially-evaluated expression,
15232     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15233       // -- an immediate subexpression of a braced-init-list,
15234 
15235       // -- [FIXME] an expression of the form & cast-expression that occurs
15236       //    within a templated entity
15237       // -- a subexpression of one of the above that is not a subexpression of
15238       // a nested unevaluated operand.
15239       return true;
15240 
15241     case Sema::ExpressionEvaluationContext::Unevaluated:
15242     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15243       // Expressions in this context are never evaluated.
15244       return false;
15245   }
15246   llvm_unreachable("Invalid context");
15247 }
15248 
15249 /// Return true if this function has a calling convention that requires mangling
15250 /// in the size of the parameter pack.
15251 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15252   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15253   // we don't need parameter type sizes.
15254   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15255   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
15256                             TT.getArch() != llvm::Triple::x86_64))
15257     return false;
15258 
15259   // If this is C++ and this isn't an extern "C" function, parameters do not
15260   // need to be complete. In this case, C++ mangling will apply, which doesn't
15261   // use the size of the parameters.
15262   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15263     return false;
15264 
15265   // Stdcall, fastcall, and vectorcall need this special treatment.
15266   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15267   switch (CC) {
15268   case CC_X86StdCall:
15269   case CC_X86FastCall:
15270   case CC_X86VectorCall:
15271     return true;
15272   default:
15273     break;
15274   }
15275   return false;
15276 }
15277 
15278 /// Require that all of the parameter types of function be complete. Normally,
15279 /// parameter types are only required to be complete when a function is called
15280 /// or defined, but to mangle functions with certain calling conventions, the
15281 /// mangler needs to know the size of the parameter list. In this situation,
15282 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15283 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15284 /// result in a linker error. Clang doesn't implement this behavior, and instead
15285 /// attempts to error at compile time.
15286 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15287                                                   SourceLocation Loc) {
15288   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15289     FunctionDecl *FD;
15290     ParmVarDecl *Param;
15291 
15292   public:
15293     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15294         : FD(FD), Param(Param) {}
15295 
15296     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15297       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15298       StringRef CCName;
15299       switch (CC) {
15300       case CC_X86StdCall:
15301         CCName = "stdcall";
15302         break;
15303       case CC_X86FastCall:
15304         CCName = "fastcall";
15305         break;
15306       case CC_X86VectorCall:
15307         CCName = "vectorcall";
15308         break;
15309       default:
15310         llvm_unreachable("CC does not need mangling");
15311       }
15312 
15313       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15314           << Param->getDeclName() << FD->getDeclName() << CCName;
15315     }
15316   };
15317 
15318   for (ParmVarDecl *Param : FD->parameters()) {
15319     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15320     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15321   }
15322 }
15323 
15324 namespace {
15325 enum class OdrUseContext {
15326   /// Declarations in this context are not odr-used.
15327   None,
15328   /// Declarations in this context are formally odr-used, but this is a
15329   /// dependent context.
15330   Dependent,
15331   /// Declarations in this context are odr-used but not actually used (yet).
15332   FormallyOdrUsed,
15333   /// Declarations in this context are used.
15334   Used
15335 };
15336 }
15337 
15338 /// Are we within a context in which references to resolved functions or to
15339 /// variables result in odr-use?
15340 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15341   OdrUseContext Result;
15342 
15343   switch (SemaRef.ExprEvalContexts.back().Context) {
15344     case Sema::ExpressionEvaluationContext::Unevaluated:
15345     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15346     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15347       return OdrUseContext::None;
15348 
15349     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15350     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15351       Result = OdrUseContext::Used;
15352       break;
15353 
15354     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15355       Result = OdrUseContext::FormallyOdrUsed;
15356       break;
15357 
15358     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15359       // A default argument formally results in odr-use, but doesn't actually
15360       // result in a use in any real sense until it itself is used.
15361       Result = OdrUseContext::FormallyOdrUsed;
15362       break;
15363   }
15364 
15365   if (SemaRef.CurContext->isDependentContext())
15366     return OdrUseContext::Dependent;
15367 
15368   return Result;
15369 }
15370 
15371 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15372   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
15373   return Func->isConstexpr() &&
15374          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
15375 }
15376 
15377 /// Mark a function referenced, and check whether it is odr-used
15378 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15379 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15380                                   bool MightBeOdrUse) {
15381   assert(Func && "No function?");
15382 
15383   Func->setReferenced();
15384 
15385   // Recursive functions aren't really used until they're used from some other
15386   // context.
15387   bool IsRecursiveCall = CurContext == Func;
15388 
15389   // C++11 [basic.def.odr]p3:
15390   //   A function whose name appears as a potentially-evaluated expression is
15391   //   odr-used if it is the unique lookup result or the selected member of a
15392   //   set of overloaded functions [...].
15393   //
15394   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15395   // can just check that here.
15396   OdrUseContext OdrUse =
15397       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15398   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15399     OdrUse = OdrUseContext::FormallyOdrUsed;
15400 
15401   // Trivial default constructors and destructors are never actually used.
15402   // FIXME: What about other special members?
15403   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15404       OdrUse == OdrUseContext::Used) {
15405     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15406       if (Constructor->isDefaultConstructor())
15407         OdrUse = OdrUseContext::FormallyOdrUsed;
15408     if (isa<CXXDestructorDecl>(Func))
15409       OdrUse = OdrUseContext::FormallyOdrUsed;
15410   }
15411 
15412   // C++20 [expr.const]p12:
15413   //   A function [...] is needed for constant evaluation if it is [...] a
15414   //   constexpr function that is named by an expression that is potentially
15415   //   constant evaluated
15416   bool NeededForConstantEvaluation =
15417       isPotentiallyConstantEvaluatedContext(*this) &&
15418       isImplicitlyDefinableConstexprFunction(Func);
15419 
15420   // Determine whether we require a function definition to exist, per
15421   // C++11 [temp.inst]p3:
15422   //   Unless a function template specialization has been explicitly
15423   //   instantiated or explicitly specialized, the function template
15424   //   specialization is implicitly instantiated when the specialization is
15425   //   referenced in a context that requires a function definition to exist.
15426   // C++20 [temp.inst]p7:
15427   //   The existence of a definition of a [...] function is considered to
15428   //   affect the semantics of the program if the [...] function is needed for
15429   //   constant evaluation by an expression
15430   // C++20 [basic.def.odr]p10:
15431   //   Every program shall contain exactly one definition of every non-inline
15432   //   function or variable that is odr-used in that program outside of a
15433   //   discarded statement
15434   // C++20 [special]p1:
15435   //   The implementation will implicitly define [defaulted special members]
15436   //   if they are odr-used or needed for constant evaluation.
15437   //
15438   // Note that we skip the implicit instantiation of templates that are only
15439   // used in unused default arguments or by recursive calls to themselves.
15440   // This is formally non-conforming, but seems reasonable in practice.
15441   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15442                                              NeededForConstantEvaluation);
15443 
15444   // C++14 [temp.expl.spec]p6:
15445   //   If a template [...] is explicitly specialized then that specialization
15446   //   shall be declared before the first use of that specialization that would
15447   //   cause an implicit instantiation to take place, in every translation unit
15448   //   in which such a use occurs
15449   if (NeedDefinition &&
15450       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15451        Func->getMemberSpecializationInfo()))
15452     checkSpecializationVisibility(Loc, Func);
15453 
15454   // C++14 [except.spec]p17:
15455   //   An exception-specification is considered to be needed when:
15456   //   - the function is odr-used or, if it appears in an unevaluated operand,
15457   //     would be odr-used if the expression were potentially-evaluated;
15458   //
15459   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15460   // function is a pure virtual function we're calling, and in that case the
15461   // function was selected by overload resolution and we need to resolve its
15462   // exception specification for a different reason.
15463   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15464   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15465     ResolveExceptionSpec(Loc, FPT);
15466 
15467   if (getLangOpts().CUDA)
15468     CheckCUDACall(Loc, Func);
15469 
15470   // If we need a definition, try to create one.
15471   if (NeedDefinition && !Func->getBody()) {
15472     runWithSufficientStackSpace(Loc, [&] {
15473       if (CXXConstructorDecl *Constructor =
15474               dyn_cast<CXXConstructorDecl>(Func)) {
15475         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15476         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15477           if (Constructor->isDefaultConstructor()) {
15478             if (Constructor->isTrivial() &&
15479                 !Constructor->hasAttr<DLLExportAttr>())
15480               return;
15481             DefineImplicitDefaultConstructor(Loc, Constructor);
15482           } else if (Constructor->isCopyConstructor()) {
15483             DefineImplicitCopyConstructor(Loc, Constructor);
15484           } else if (Constructor->isMoveConstructor()) {
15485             DefineImplicitMoveConstructor(Loc, Constructor);
15486           }
15487         } else if (Constructor->getInheritedConstructor()) {
15488           DefineInheritingConstructor(Loc, Constructor);
15489         }
15490       } else if (CXXDestructorDecl *Destructor =
15491                      dyn_cast<CXXDestructorDecl>(Func)) {
15492         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15493         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15494           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15495             return;
15496           DefineImplicitDestructor(Loc, Destructor);
15497         }
15498         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15499           MarkVTableUsed(Loc, Destructor->getParent());
15500       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15501         if (MethodDecl->isOverloadedOperator() &&
15502             MethodDecl->getOverloadedOperator() == OO_Equal) {
15503           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15504           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15505             if (MethodDecl->isCopyAssignmentOperator())
15506               DefineImplicitCopyAssignment(Loc, MethodDecl);
15507             else if (MethodDecl->isMoveAssignmentOperator())
15508               DefineImplicitMoveAssignment(Loc, MethodDecl);
15509           }
15510         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15511                    MethodDecl->getParent()->isLambda()) {
15512           CXXConversionDecl *Conversion =
15513               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15514           if (Conversion->isLambdaToBlockPointerConversion())
15515             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15516           else
15517             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15518         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15519           MarkVTableUsed(Loc, MethodDecl->getParent());
15520       }
15521 
15522       // Implicit instantiation of function templates and member functions of
15523       // class templates.
15524       if (Func->isImplicitlyInstantiable()) {
15525         TemplateSpecializationKind TSK =
15526             Func->getTemplateSpecializationKindForInstantiation();
15527         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15528         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15529         if (FirstInstantiation) {
15530           PointOfInstantiation = Loc;
15531           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15532         } else if (TSK != TSK_ImplicitInstantiation) {
15533           // Use the point of use as the point of instantiation, instead of the
15534           // point of explicit instantiation (which we track as the actual point
15535           // of instantiation). This gives better backtraces in diagnostics.
15536           PointOfInstantiation = Loc;
15537         }
15538 
15539         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15540             Func->isConstexpr()) {
15541           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15542               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15543               CodeSynthesisContexts.size())
15544             PendingLocalImplicitInstantiations.push_back(
15545                 std::make_pair(Func, PointOfInstantiation));
15546           else if (Func->isConstexpr())
15547             // Do not defer instantiations of constexpr functions, to avoid the
15548             // expression evaluator needing to call back into Sema if it sees a
15549             // call to such a function.
15550             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15551           else {
15552             Func->setInstantiationIsPending(true);
15553             PendingInstantiations.push_back(
15554                 std::make_pair(Func, PointOfInstantiation));
15555             // Notify the consumer that a function was implicitly instantiated.
15556             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15557           }
15558         }
15559       } else {
15560         // Walk redefinitions, as some of them may be instantiable.
15561         for (auto i : Func->redecls()) {
15562           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15563             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15564         }
15565       }
15566     });
15567   }
15568 
15569   // If this is the first "real" use, act on that.
15570   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15571     // Keep track of used but undefined functions.
15572     if (!Func->isDefined()) {
15573       if (mightHaveNonExternalLinkage(Func))
15574         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15575       else if (Func->getMostRecentDecl()->isInlined() &&
15576                !LangOpts.GNUInline &&
15577                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15578         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15579       else if (isExternalWithNoLinkageType(Func))
15580         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15581     }
15582 
15583     // Some x86 Windows calling conventions mangle the size of the parameter
15584     // pack into the name. Computing the size of the parameters requires the
15585     // parameter types to be complete. Check that now.
15586     if (funcHasParameterSizeMangling(*this, Func))
15587       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15588 
15589     Func->markUsed(Context);
15590   }
15591 
15592   if (LangOpts.OpenMP) {
15593     markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15594     if (LangOpts.OpenMPIsDevice)
15595       checkOpenMPDeviceFunction(Loc, Func);
15596     else
15597       checkOpenMPHostFunction(Loc, Func);
15598   }
15599 }
15600 
15601 /// Directly mark a variable odr-used. Given a choice, prefer to use
15602 /// MarkVariableReferenced since it does additional checks and then
15603 /// calls MarkVarDeclODRUsed.
15604 /// If the variable must be captured:
15605 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15606 ///  - else capture it in the DeclContext that maps to the
15607 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15608 static void
15609 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15610                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15611   // Keep track of used but undefined variables.
15612   // FIXME: We shouldn't suppress this warning for static data members.
15613   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15614       (!Var->isExternallyVisible() || Var->isInline() ||
15615        SemaRef.isExternalWithNoLinkageType(Var)) &&
15616       !(Var->isStaticDataMember() && Var->hasInit())) {
15617     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15618     if (old.isInvalid())
15619       old = Loc;
15620   }
15621   QualType CaptureType, DeclRefType;
15622   if (SemaRef.LangOpts.OpenMP)
15623     SemaRef.tryCaptureOpenMPLambdas(Var);
15624   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15625     /*EllipsisLoc*/ SourceLocation(),
15626     /*BuildAndDiagnose*/ true,
15627     CaptureType, DeclRefType,
15628     FunctionScopeIndexToStopAt);
15629 
15630   Var->markUsed(SemaRef.Context);
15631 }
15632 
15633 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15634                                              SourceLocation Loc,
15635                                              unsigned CapturingScopeIndex) {
15636   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15637 }
15638 
15639 static void
15640 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15641                                    ValueDecl *var, DeclContext *DC) {
15642   DeclContext *VarDC = var->getDeclContext();
15643 
15644   //  If the parameter still belongs to the translation unit, then
15645   //  we're actually just using one parameter in the declaration of
15646   //  the next.
15647   if (isa<ParmVarDecl>(var) &&
15648       isa<TranslationUnitDecl>(VarDC))
15649     return;
15650 
15651   // For C code, don't diagnose about capture if we're not actually in code
15652   // right now; it's impossible to write a non-constant expression outside of
15653   // function context, so we'll get other (more useful) diagnostics later.
15654   //
15655   // For C++, things get a bit more nasty... it would be nice to suppress this
15656   // diagnostic for certain cases like using a local variable in an array bound
15657   // for a member of a local class, but the correct predicate is not obvious.
15658   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15659     return;
15660 
15661   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15662   unsigned ContextKind = 3; // unknown
15663   if (isa<CXXMethodDecl>(VarDC) &&
15664       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15665     ContextKind = 2;
15666   } else if (isa<FunctionDecl>(VarDC)) {
15667     ContextKind = 0;
15668   } else if (isa<BlockDecl>(VarDC)) {
15669     ContextKind = 1;
15670   }
15671 
15672   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15673     << var << ValueKind << ContextKind << VarDC;
15674   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15675       << var;
15676 
15677   // FIXME: Add additional diagnostic info about class etc. which prevents
15678   // capture.
15679 }
15680 
15681 
15682 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15683                                       bool &SubCapturesAreNested,
15684                                       QualType &CaptureType,
15685                                       QualType &DeclRefType) {
15686    // Check whether we've already captured it.
15687   if (CSI->CaptureMap.count(Var)) {
15688     // If we found a capture, any subcaptures are nested.
15689     SubCapturesAreNested = true;
15690 
15691     // Retrieve the capture type for this variable.
15692     CaptureType = CSI->getCapture(Var).getCaptureType();
15693 
15694     // Compute the type of an expression that refers to this variable.
15695     DeclRefType = CaptureType.getNonReferenceType();
15696 
15697     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15698     // are mutable in the sense that user can change their value - they are
15699     // private instances of the captured declarations.
15700     const Capture &Cap = CSI->getCapture(Var);
15701     if (Cap.isCopyCapture() &&
15702         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15703         !(isa<CapturedRegionScopeInfo>(CSI) &&
15704           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15705       DeclRefType.addConst();
15706     return true;
15707   }
15708   return false;
15709 }
15710 
15711 // Only block literals, captured statements, and lambda expressions can
15712 // capture; other scopes don't work.
15713 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15714                                  SourceLocation Loc,
15715                                  const bool Diagnose, Sema &S) {
15716   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15717     return getLambdaAwareParentOfDeclContext(DC);
15718   else if (Var->hasLocalStorage()) {
15719     if (Diagnose)
15720        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15721   }
15722   return nullptr;
15723 }
15724 
15725 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15726 // certain types of variables (unnamed, variably modified types etc.)
15727 // so check for eligibility.
15728 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15729                                  SourceLocation Loc,
15730                                  const bool Diagnose, Sema &S) {
15731 
15732   bool IsBlock = isa<BlockScopeInfo>(CSI);
15733   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15734 
15735   // Lambdas are not allowed to capture unnamed variables
15736   // (e.g. anonymous unions).
15737   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15738   // assuming that's the intent.
15739   if (IsLambda && !Var->getDeclName()) {
15740     if (Diagnose) {
15741       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15742       S.Diag(Var->getLocation(), diag::note_declared_at);
15743     }
15744     return false;
15745   }
15746 
15747   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15748   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15749     if (Diagnose) {
15750       S.Diag(Loc, diag::err_ref_vm_type);
15751       S.Diag(Var->getLocation(), diag::note_previous_decl)
15752         << Var->getDeclName();
15753     }
15754     return false;
15755   }
15756   // Prohibit structs with flexible array members too.
15757   // We cannot capture what is in the tail end of the struct.
15758   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15759     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15760       if (Diagnose) {
15761         if (IsBlock)
15762           S.Diag(Loc, diag::err_ref_flexarray_type);
15763         else
15764           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15765             << Var->getDeclName();
15766         S.Diag(Var->getLocation(), diag::note_previous_decl)
15767           << Var->getDeclName();
15768       }
15769       return false;
15770     }
15771   }
15772   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15773   // Lambdas and captured statements are not allowed to capture __block
15774   // variables; they don't support the expected semantics.
15775   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15776     if (Diagnose) {
15777       S.Diag(Loc, diag::err_capture_block_variable)
15778         << Var->getDeclName() << !IsLambda;
15779       S.Diag(Var->getLocation(), diag::note_previous_decl)
15780         << Var->getDeclName();
15781     }
15782     return false;
15783   }
15784   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15785   if (S.getLangOpts().OpenCL && IsBlock &&
15786       Var->getType()->isBlockPointerType()) {
15787     if (Diagnose)
15788       S.Diag(Loc, diag::err_opencl_block_ref_block);
15789     return false;
15790   }
15791 
15792   return true;
15793 }
15794 
15795 // Returns true if the capture by block was successful.
15796 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15797                                  SourceLocation Loc,
15798                                  const bool BuildAndDiagnose,
15799                                  QualType &CaptureType,
15800                                  QualType &DeclRefType,
15801                                  const bool Nested,
15802                                  Sema &S, bool Invalid) {
15803   bool ByRef = false;
15804 
15805   // Blocks are not allowed to capture arrays, excepting OpenCL.
15806   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15807   // (decayed to pointers).
15808   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15809     if (BuildAndDiagnose) {
15810       S.Diag(Loc, diag::err_ref_array_type);
15811       S.Diag(Var->getLocation(), diag::note_previous_decl)
15812       << Var->getDeclName();
15813       Invalid = true;
15814     } else {
15815       return false;
15816     }
15817   }
15818 
15819   // Forbid the block-capture of autoreleasing variables.
15820   if (!Invalid &&
15821       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15822     if (BuildAndDiagnose) {
15823       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15824         << /*block*/ 0;
15825       S.Diag(Var->getLocation(), diag::note_previous_decl)
15826         << Var->getDeclName();
15827       Invalid = true;
15828     } else {
15829       return false;
15830     }
15831   }
15832 
15833   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15834   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15835     QualType PointeeTy = PT->getPointeeType();
15836 
15837     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15838         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15839         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15840       if (BuildAndDiagnose) {
15841         SourceLocation VarLoc = Var->getLocation();
15842         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15843         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15844       }
15845     }
15846   }
15847 
15848   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15849   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15850       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15851     // Block capture by reference does not change the capture or
15852     // declaration reference types.
15853     ByRef = true;
15854   } else {
15855     // Block capture by copy introduces 'const'.
15856     CaptureType = CaptureType.getNonReferenceType().withConst();
15857     DeclRefType = CaptureType;
15858   }
15859 
15860   // Actually capture the variable.
15861   if (BuildAndDiagnose)
15862     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15863                     CaptureType, Invalid);
15864 
15865   return !Invalid;
15866 }
15867 
15868 
15869 /// Capture the given variable in the captured region.
15870 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15871                                     VarDecl *Var,
15872                                     SourceLocation Loc,
15873                                     const bool BuildAndDiagnose,
15874                                     QualType &CaptureType,
15875                                     QualType &DeclRefType,
15876                                     const bool RefersToCapturedVariable,
15877                                     Sema &S, bool Invalid) {
15878   // By default, capture variables by reference.
15879   bool ByRef = true;
15880   // Using an LValue reference type is consistent with Lambdas (see below).
15881   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15882     if (S.isOpenMPCapturedDecl(Var)) {
15883       bool HasConst = DeclRefType.isConstQualified();
15884       DeclRefType = DeclRefType.getUnqualifiedType();
15885       // Don't lose diagnostics about assignments to const.
15886       if (HasConst)
15887         DeclRefType.addConst();
15888     }
15889     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
15890                                     RSI->OpenMPCaptureLevel);
15891   }
15892 
15893   if (ByRef)
15894     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15895   else
15896     CaptureType = DeclRefType;
15897 
15898   // Actually capture the variable.
15899   if (BuildAndDiagnose)
15900     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15901                     Loc, SourceLocation(), CaptureType, Invalid);
15902 
15903   return !Invalid;
15904 }
15905 
15906 /// Capture the given variable in the lambda.
15907 static bool captureInLambda(LambdaScopeInfo *LSI,
15908                             VarDecl *Var,
15909                             SourceLocation Loc,
15910                             const bool BuildAndDiagnose,
15911                             QualType &CaptureType,
15912                             QualType &DeclRefType,
15913                             const bool RefersToCapturedVariable,
15914                             const Sema::TryCaptureKind Kind,
15915                             SourceLocation EllipsisLoc,
15916                             const bool IsTopScope,
15917                             Sema &S, bool Invalid) {
15918   // Determine whether we are capturing by reference or by value.
15919   bool ByRef = false;
15920   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15921     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15922   } else {
15923     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15924   }
15925 
15926   // Compute the type of the field that will capture this variable.
15927   if (ByRef) {
15928     // C++11 [expr.prim.lambda]p15:
15929     //   An entity is captured by reference if it is implicitly or
15930     //   explicitly captured but not captured by copy. It is
15931     //   unspecified whether additional unnamed non-static data
15932     //   members are declared in the closure type for entities
15933     //   captured by reference.
15934     //
15935     // FIXME: It is not clear whether we want to build an lvalue reference
15936     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15937     // to do the former, while EDG does the latter. Core issue 1249 will
15938     // clarify, but for now we follow GCC because it's a more permissive and
15939     // easily defensible position.
15940     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15941   } else {
15942     // C++11 [expr.prim.lambda]p14:
15943     //   For each entity captured by copy, an unnamed non-static
15944     //   data member is declared in the closure type. The
15945     //   declaration order of these members is unspecified. The type
15946     //   of such a data member is the type of the corresponding
15947     //   captured entity if the entity is not a reference to an
15948     //   object, or the referenced type otherwise. [Note: If the
15949     //   captured entity is a reference to a function, the
15950     //   corresponding data member is also a reference to a
15951     //   function. - end note ]
15952     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15953       if (!RefType->getPointeeType()->isFunctionType())
15954         CaptureType = RefType->getPointeeType();
15955     }
15956 
15957     // Forbid the lambda copy-capture of autoreleasing variables.
15958     if (!Invalid &&
15959         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15960       if (BuildAndDiagnose) {
15961         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15962         S.Diag(Var->getLocation(), diag::note_previous_decl)
15963           << Var->getDeclName();
15964         Invalid = true;
15965       } else {
15966         return false;
15967       }
15968     }
15969 
15970     // Make sure that by-copy captures are of a complete and non-abstract type.
15971     if (!Invalid && BuildAndDiagnose) {
15972       if (!CaptureType->isDependentType() &&
15973           S.RequireCompleteType(Loc, CaptureType,
15974                                 diag::err_capture_of_incomplete_type,
15975                                 Var->getDeclName()))
15976         Invalid = true;
15977       else if (S.RequireNonAbstractType(Loc, CaptureType,
15978                                         diag::err_capture_of_abstract_type))
15979         Invalid = true;
15980     }
15981   }
15982 
15983   // Compute the type of a reference to this captured variable.
15984   if (ByRef)
15985     DeclRefType = CaptureType.getNonReferenceType();
15986   else {
15987     // C++ [expr.prim.lambda]p5:
15988     //   The closure type for a lambda-expression has a public inline
15989     //   function call operator [...]. This function call operator is
15990     //   declared const (9.3.1) if and only if the lambda-expression's
15991     //   parameter-declaration-clause is not followed by mutable.
15992     DeclRefType = CaptureType.getNonReferenceType();
15993     if (!LSI->Mutable && !CaptureType->isReferenceType())
15994       DeclRefType.addConst();
15995   }
15996 
15997   // Add the capture.
15998   if (BuildAndDiagnose)
15999     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16000                     Loc, EllipsisLoc, CaptureType, Invalid);
16001 
16002   return !Invalid;
16003 }
16004 
16005 bool Sema::tryCaptureVariable(
16006     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16007     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16008     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16009   // An init-capture is notionally from the context surrounding its
16010   // declaration, but its parent DC is the lambda class.
16011   DeclContext *VarDC = Var->getDeclContext();
16012   if (Var->isInitCapture())
16013     VarDC = VarDC->getParent();
16014 
16015   DeclContext *DC = CurContext;
16016   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16017       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16018   // We need to sync up the Declaration Context with the
16019   // FunctionScopeIndexToStopAt
16020   if (FunctionScopeIndexToStopAt) {
16021     unsigned FSIndex = FunctionScopes.size() - 1;
16022     while (FSIndex != MaxFunctionScopesIndex) {
16023       DC = getLambdaAwareParentOfDeclContext(DC);
16024       --FSIndex;
16025     }
16026   }
16027 
16028 
16029   // If the variable is declared in the current context, there is no need to
16030   // capture it.
16031   if (VarDC == DC) return true;
16032 
16033   // Capture global variables if it is required to use private copy of this
16034   // variable.
16035   bool IsGlobal = !Var->hasLocalStorage();
16036   if (IsGlobal &&
16037       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16038                                                 MaxFunctionScopesIndex)))
16039     return true;
16040   Var = Var->getCanonicalDecl();
16041 
16042   // Walk up the stack to determine whether we can capture the variable,
16043   // performing the "simple" checks that don't depend on type. We stop when
16044   // we've either hit the declared scope of the variable or find an existing
16045   // capture of that variable.  We start from the innermost capturing-entity
16046   // (the DC) and ensure that all intervening capturing-entities
16047   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16048   // declcontext can either capture the variable or have already captured
16049   // the variable.
16050   CaptureType = Var->getType();
16051   DeclRefType = CaptureType.getNonReferenceType();
16052   bool Nested = false;
16053   bool Explicit = (Kind != TryCapture_Implicit);
16054   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16055   do {
16056     // Only block literals, captured statements, and lambda expressions can
16057     // capture; other scopes don't work.
16058     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16059                                                               ExprLoc,
16060                                                               BuildAndDiagnose,
16061                                                               *this);
16062     // We need to check for the parent *first* because, if we *have*
16063     // private-captured a global variable, we need to recursively capture it in
16064     // intermediate blocks, lambdas, etc.
16065     if (!ParentDC) {
16066       if (IsGlobal) {
16067         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16068         break;
16069       }
16070       return true;
16071     }
16072 
16073     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
16074     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16075 
16076 
16077     // Check whether we've already captured it.
16078     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16079                                              DeclRefType)) {
16080       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16081       break;
16082     }
16083     // If we are instantiating a generic lambda call operator body,
16084     // we do not want to capture new variables.  What was captured
16085     // during either a lambdas transformation or initial parsing
16086     // should be used.
16087     if (isGenericLambdaCallOperatorSpecialization(DC)) {
16088       if (BuildAndDiagnose) {
16089         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16090         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16091           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16092           Diag(Var->getLocation(), diag::note_previous_decl)
16093              << Var->getDeclName();
16094           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16095         } else
16096           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16097       }
16098       return true;
16099     }
16100 
16101     // Try to capture variable-length arrays types.
16102     if (Var->getType()->isVariablyModifiedType()) {
16103       // We're going to walk down into the type and look for VLA
16104       // expressions.
16105       QualType QTy = Var->getType();
16106       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16107         QTy = PVD->getOriginalType();
16108       captureVariablyModifiedType(Context, QTy, CSI);
16109     }
16110 
16111     if (getLangOpts().OpenMP) {
16112       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16113         // OpenMP private variables should not be captured in outer scope, so
16114         // just break here. Similarly, global variables that are captured in a
16115         // target region should not be captured outside the scope of the region.
16116         if (RSI->CapRegionKind == CR_OpenMP) {
16117           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16118           // If the variable is private (i.e. not captured) and has variably
16119           // modified type, we still need to capture the type for correct
16120           // codegen in all regions, associated with the construct. Currently,
16121           // it is captured in the innermost captured region only.
16122           if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
16123             QualType QTy = Var->getType();
16124             if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16125               QTy = PVD->getOriginalType();
16126             for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
16127                  I < E; ++I) {
16128               auto *OuterRSI = cast<CapturedRegionScopeInfo>(
16129                   FunctionScopes[FunctionScopesIndex - I]);
16130               assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
16131                      "Wrong number of captured regions associated with the "
16132                      "OpenMP construct.");
16133               captureVariablyModifiedType(Context, QTy, OuterRSI);
16134             }
16135           }
16136           bool IsTargetCap = !IsOpenMPPrivateDecl &&
16137                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16138           // When we detect target captures we are looking from inside the
16139           // target region, therefore we need to propagate the capture from the
16140           // enclosing region. Therefore, the capture is not initially nested.
16141           if (IsTargetCap)
16142             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16143 
16144           if (IsTargetCap || IsOpenMPPrivateDecl) {
16145             Nested = !IsTargetCap;
16146             DeclRefType = DeclRefType.getUnqualifiedType();
16147             CaptureType = Context.getLValueReferenceType(DeclRefType);
16148             break;
16149           }
16150         }
16151       }
16152     }
16153     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16154       // No capture-default, and this is not an explicit capture
16155       // so cannot capture this variable.
16156       if (BuildAndDiagnose) {
16157         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16158         Diag(Var->getLocation(), diag::note_previous_decl)
16159           << Var->getDeclName();
16160         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16161           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16162                diag::note_lambda_decl);
16163         // FIXME: If we error out because an outer lambda can not implicitly
16164         // capture a variable that an inner lambda explicitly captures, we
16165         // should have the inner lambda do the explicit capture - because
16166         // it makes for cleaner diagnostics later.  This would purely be done
16167         // so that the diagnostic does not misleadingly claim that a variable
16168         // can not be captured by a lambda implicitly even though it is captured
16169         // explicitly.  Suggestion:
16170         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16171         //    at the function head
16172         //  - cache the StartingDeclContext - this must be a lambda
16173         //  - captureInLambda in the innermost lambda the variable.
16174       }
16175       return true;
16176     }
16177 
16178     FunctionScopesIndex--;
16179     DC = ParentDC;
16180     Explicit = false;
16181   } while (!VarDC->Equals(DC));
16182 
16183   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16184   // computing the type of the capture at each step, checking type-specific
16185   // requirements, and adding captures if requested.
16186   // If the variable had already been captured previously, we start capturing
16187   // at the lambda nested within that one.
16188   bool Invalid = false;
16189   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16190        ++I) {
16191     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16192 
16193     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16194     // certain types of variables (unnamed, variably modified types etc.)
16195     // so check for eligibility.
16196     if (!Invalid)
16197       Invalid =
16198           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16199 
16200     // After encountering an error, if we're actually supposed to capture, keep
16201     // capturing in nested contexts to suppress any follow-on diagnostics.
16202     if (Invalid && !BuildAndDiagnose)
16203       return true;
16204 
16205     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16206       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16207                                DeclRefType, Nested, *this, Invalid);
16208       Nested = true;
16209     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16210       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16211                                          CaptureType, DeclRefType, Nested,
16212                                          *this, Invalid);
16213       Nested = true;
16214     } else {
16215       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16216       Invalid =
16217           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16218                            DeclRefType, Nested, Kind, EllipsisLoc,
16219                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16220       Nested = true;
16221     }
16222 
16223     if (Invalid && !BuildAndDiagnose)
16224       return true;
16225   }
16226   return Invalid;
16227 }
16228 
16229 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16230                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16231   QualType CaptureType;
16232   QualType DeclRefType;
16233   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16234                             /*BuildAndDiagnose=*/true, CaptureType,
16235                             DeclRefType, nullptr);
16236 }
16237 
16238 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16239   QualType CaptureType;
16240   QualType DeclRefType;
16241   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16242                              /*BuildAndDiagnose=*/false, CaptureType,
16243                              DeclRefType, nullptr);
16244 }
16245 
16246 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16247   QualType CaptureType;
16248   QualType DeclRefType;
16249 
16250   // Determine whether we can capture this variable.
16251   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16252                          /*BuildAndDiagnose=*/false, CaptureType,
16253                          DeclRefType, nullptr))
16254     return QualType();
16255 
16256   return DeclRefType;
16257 }
16258 
16259 namespace {
16260 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16261 // The produced TemplateArgumentListInfo* points to data stored within this
16262 // object, so should only be used in contexts where the pointer will not be
16263 // used after the CopiedTemplateArgs object is destroyed.
16264 class CopiedTemplateArgs {
16265   bool HasArgs;
16266   TemplateArgumentListInfo TemplateArgStorage;
16267 public:
16268   template<typename RefExpr>
16269   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16270     if (HasArgs)
16271       E->copyTemplateArgumentsInto(TemplateArgStorage);
16272   }
16273   operator TemplateArgumentListInfo*()
16274 #ifdef __has_cpp_attribute
16275 #if __has_cpp_attribute(clang::lifetimebound)
16276   [[clang::lifetimebound]]
16277 #endif
16278 #endif
16279   {
16280     return HasArgs ? &TemplateArgStorage : nullptr;
16281   }
16282 };
16283 }
16284 
16285 /// Walk the set of potential results of an expression and mark them all as
16286 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16287 ///
16288 /// \return A new expression if we found any potential results, ExprEmpty() if
16289 ///         not, and ExprError() if we diagnosed an error.
16290 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16291                                                       NonOdrUseReason NOUR) {
16292   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16293   // an object that satisfies the requirements for appearing in a
16294   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16295   // is immediately applied."  This function handles the lvalue-to-rvalue
16296   // conversion part.
16297   //
16298   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16299   // transform it into the relevant kind of non-odr-use node and rebuild the
16300   // tree of nodes leading to it.
16301   //
16302   // This is a mini-TreeTransform that only transforms a restricted subset of
16303   // nodes (and only certain operands of them).
16304 
16305   // Rebuild a subexpression.
16306   auto Rebuild = [&](Expr *Sub) {
16307     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16308   };
16309 
16310   // Check whether a potential result satisfies the requirements of NOUR.
16311   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16312     // Any entity other than a VarDecl is always odr-used whenever it's named
16313     // in a potentially-evaluated expression.
16314     auto *VD = dyn_cast<VarDecl>(D);
16315     if (!VD)
16316       return true;
16317 
16318     // C++2a [basic.def.odr]p4:
16319     //   A variable x whose name appears as a potentially-evalauted expression
16320     //   e is odr-used by e unless
16321     //   -- x is a reference that is usable in constant expressions, or
16322     //   -- x is a variable of non-reference type that is usable in constant
16323     //      expressions and has no mutable subobjects, and e is an element of
16324     //      the set of potential results of an expression of
16325     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16326     //      conversion is applied, or
16327     //   -- x is a variable of non-reference type, and e is an element of the
16328     //      set of potential results of a discarded-value expression to which
16329     //      the lvalue-to-rvalue conversion is not applied
16330     //
16331     // We check the first bullet and the "potentially-evaluated" condition in
16332     // BuildDeclRefExpr. We check the type requirements in the second bullet
16333     // in CheckLValueToRValueConversionOperand below.
16334     switch (NOUR) {
16335     case NOUR_None:
16336     case NOUR_Unevaluated:
16337       llvm_unreachable("unexpected non-odr-use-reason");
16338 
16339     case NOUR_Constant:
16340       // Constant references were handled when they were built.
16341       if (VD->getType()->isReferenceType())
16342         return true;
16343       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16344         if (RD->hasMutableFields())
16345           return true;
16346       if (!VD->isUsableInConstantExpressions(S.Context))
16347         return true;
16348       break;
16349 
16350     case NOUR_Discarded:
16351       if (VD->getType()->isReferenceType())
16352         return true;
16353       break;
16354     }
16355     return false;
16356   };
16357 
16358   // Mark that this expression does not constitute an odr-use.
16359   auto MarkNotOdrUsed = [&] {
16360     S.MaybeODRUseExprs.erase(E);
16361     if (LambdaScopeInfo *LSI = S.getCurLambda())
16362       LSI->markVariableExprAsNonODRUsed(E);
16363   };
16364 
16365   // C++2a [basic.def.odr]p2:
16366   //   The set of potential results of an expression e is defined as follows:
16367   switch (E->getStmtClass()) {
16368   //   -- If e is an id-expression, ...
16369   case Expr::DeclRefExprClass: {
16370     auto *DRE = cast<DeclRefExpr>(E);
16371     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16372       break;
16373 
16374     // Rebuild as a non-odr-use DeclRefExpr.
16375     MarkNotOdrUsed();
16376     return DeclRefExpr::Create(
16377         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16378         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16379         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16380         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16381   }
16382 
16383   case Expr::FunctionParmPackExprClass: {
16384     auto *FPPE = cast<FunctionParmPackExpr>(E);
16385     // If any of the declarations in the pack is odr-used, then the expression
16386     // as a whole constitutes an odr-use.
16387     for (VarDecl *D : *FPPE)
16388       if (IsPotentialResultOdrUsed(D))
16389         return ExprEmpty();
16390 
16391     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16392     // nothing cares about whether we marked this as an odr-use, but it might
16393     // be useful for non-compiler tools.
16394     MarkNotOdrUsed();
16395     break;
16396   }
16397 
16398   //   -- If e is a subscripting operation with an array operand...
16399   case Expr::ArraySubscriptExprClass: {
16400     auto *ASE = cast<ArraySubscriptExpr>(E);
16401     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16402     if (!OldBase->getType()->isArrayType())
16403       break;
16404     ExprResult Base = Rebuild(OldBase);
16405     if (!Base.isUsable())
16406       return Base;
16407     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16408     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16409     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16410     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16411                                      ASE->getRBracketLoc());
16412   }
16413 
16414   case Expr::MemberExprClass: {
16415     auto *ME = cast<MemberExpr>(E);
16416     // -- If e is a class member access expression [...] naming a non-static
16417     //    data member...
16418     if (isa<FieldDecl>(ME->getMemberDecl())) {
16419       ExprResult Base = Rebuild(ME->getBase());
16420       if (!Base.isUsable())
16421         return Base;
16422       return MemberExpr::Create(
16423           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16424           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16425           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16426           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16427           ME->getObjectKind(), ME->isNonOdrUse());
16428     }
16429 
16430     if (ME->getMemberDecl()->isCXXInstanceMember())
16431       break;
16432 
16433     // -- If e is a class member access expression naming a static data member,
16434     //    ...
16435     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16436       break;
16437 
16438     // Rebuild as a non-odr-use MemberExpr.
16439     MarkNotOdrUsed();
16440     return MemberExpr::Create(
16441         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16442         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16443         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16444         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16445     return ExprEmpty();
16446   }
16447 
16448   case Expr::BinaryOperatorClass: {
16449     auto *BO = cast<BinaryOperator>(E);
16450     Expr *LHS = BO->getLHS();
16451     Expr *RHS = BO->getRHS();
16452     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16453     if (BO->getOpcode() == BO_PtrMemD) {
16454       ExprResult Sub = Rebuild(LHS);
16455       if (!Sub.isUsable())
16456         return Sub;
16457       LHS = Sub.get();
16458     //   -- If e is a comma expression, ...
16459     } else if (BO->getOpcode() == BO_Comma) {
16460       ExprResult Sub = Rebuild(RHS);
16461       if (!Sub.isUsable())
16462         return Sub;
16463       RHS = Sub.get();
16464     } else {
16465       break;
16466     }
16467     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16468                         LHS, RHS);
16469   }
16470 
16471   //   -- If e has the form (e1)...
16472   case Expr::ParenExprClass: {
16473     auto *PE = cast<ParenExpr>(E);
16474     ExprResult Sub = Rebuild(PE->getSubExpr());
16475     if (!Sub.isUsable())
16476       return Sub;
16477     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16478   }
16479 
16480   //   -- If e is a glvalue conditional expression, ...
16481   // We don't apply this to a binary conditional operator. FIXME: Should we?
16482   case Expr::ConditionalOperatorClass: {
16483     auto *CO = cast<ConditionalOperator>(E);
16484     ExprResult LHS = Rebuild(CO->getLHS());
16485     if (LHS.isInvalid())
16486       return ExprError();
16487     ExprResult RHS = Rebuild(CO->getRHS());
16488     if (RHS.isInvalid())
16489       return ExprError();
16490     if (!LHS.isUsable() && !RHS.isUsable())
16491       return ExprEmpty();
16492     if (!LHS.isUsable())
16493       LHS = CO->getLHS();
16494     if (!RHS.isUsable())
16495       RHS = CO->getRHS();
16496     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16497                                 CO->getCond(), LHS.get(), RHS.get());
16498   }
16499 
16500   // [Clang extension]
16501   //   -- If e has the form __extension__ e1...
16502   case Expr::UnaryOperatorClass: {
16503     auto *UO = cast<UnaryOperator>(E);
16504     if (UO->getOpcode() != UO_Extension)
16505       break;
16506     ExprResult Sub = Rebuild(UO->getSubExpr());
16507     if (!Sub.isUsable())
16508       return Sub;
16509     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16510                           Sub.get());
16511   }
16512 
16513   // [Clang extension]
16514   //   -- If e has the form _Generic(...), the set of potential results is the
16515   //      union of the sets of potential results of the associated expressions.
16516   case Expr::GenericSelectionExprClass: {
16517     auto *GSE = cast<GenericSelectionExpr>(E);
16518 
16519     SmallVector<Expr *, 4> AssocExprs;
16520     bool AnyChanged = false;
16521     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16522       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16523       if (AssocExpr.isInvalid())
16524         return ExprError();
16525       if (AssocExpr.isUsable()) {
16526         AssocExprs.push_back(AssocExpr.get());
16527         AnyChanged = true;
16528       } else {
16529         AssocExprs.push_back(OrigAssocExpr);
16530       }
16531     }
16532 
16533     return AnyChanged ? S.CreateGenericSelectionExpr(
16534                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16535                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16536                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16537                       : ExprEmpty();
16538   }
16539 
16540   // [Clang extension]
16541   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16542   //      results is the union of the sets of potential results of the
16543   //      second and third subexpressions.
16544   case Expr::ChooseExprClass: {
16545     auto *CE = cast<ChooseExpr>(E);
16546 
16547     ExprResult LHS = Rebuild(CE->getLHS());
16548     if (LHS.isInvalid())
16549       return ExprError();
16550 
16551     ExprResult RHS = Rebuild(CE->getLHS());
16552     if (RHS.isInvalid())
16553       return ExprError();
16554 
16555     if (!LHS.get() && !RHS.get())
16556       return ExprEmpty();
16557     if (!LHS.isUsable())
16558       LHS = CE->getLHS();
16559     if (!RHS.isUsable())
16560       RHS = CE->getRHS();
16561 
16562     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16563                              RHS.get(), CE->getRParenLoc());
16564   }
16565 
16566   // Step through non-syntactic nodes.
16567   case Expr::ConstantExprClass: {
16568     auto *CE = cast<ConstantExpr>(E);
16569     ExprResult Sub = Rebuild(CE->getSubExpr());
16570     if (!Sub.isUsable())
16571       return Sub;
16572     return ConstantExpr::Create(S.Context, Sub.get());
16573   }
16574 
16575   // We could mostly rely on the recursive rebuilding to rebuild implicit
16576   // casts, but not at the top level, so rebuild them here.
16577   case Expr::ImplicitCastExprClass: {
16578     auto *ICE = cast<ImplicitCastExpr>(E);
16579     // Only step through the narrow set of cast kinds we expect to encounter.
16580     // Anything else suggests we've left the region in which potential results
16581     // can be found.
16582     switch (ICE->getCastKind()) {
16583     case CK_NoOp:
16584     case CK_DerivedToBase:
16585     case CK_UncheckedDerivedToBase: {
16586       ExprResult Sub = Rebuild(ICE->getSubExpr());
16587       if (!Sub.isUsable())
16588         return Sub;
16589       CXXCastPath Path(ICE->path());
16590       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16591                                  ICE->getValueKind(), &Path);
16592     }
16593 
16594     default:
16595       break;
16596     }
16597     break;
16598   }
16599 
16600   default:
16601     break;
16602   }
16603 
16604   // Can't traverse through this node. Nothing to do.
16605   return ExprEmpty();
16606 }
16607 
16608 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16609   // Check whether the operand is or contains an object of non-trivial C union
16610   // type.
16611   if (E->getType().isVolatileQualified() &&
16612       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16613        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16614     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16615                           Sema::NTCUC_LValueToRValueVolatile,
16616                           NTCUK_Destruct|NTCUK_Copy);
16617 
16618   // C++2a [basic.def.odr]p4:
16619   //   [...] an expression of non-volatile-qualified non-class type to which
16620   //   the lvalue-to-rvalue conversion is applied [...]
16621   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16622     return E;
16623 
16624   ExprResult Result =
16625       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16626   if (Result.isInvalid())
16627     return ExprError();
16628   return Result.get() ? Result : E;
16629 }
16630 
16631 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16632   Res = CorrectDelayedTyposInExpr(Res);
16633 
16634   if (!Res.isUsable())
16635     return Res;
16636 
16637   // If a constant-expression is a reference to a variable where we delay
16638   // deciding whether it is an odr-use, just assume we will apply the
16639   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16640   // (a non-type template argument), we have special handling anyway.
16641   return CheckLValueToRValueConversionOperand(Res.get());
16642 }
16643 
16644 void Sema::CleanupVarDeclMarking() {
16645   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16646   // call.
16647   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16648   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16649 
16650   for (Expr *E : LocalMaybeODRUseExprs) {
16651     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16652       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16653                          DRE->getLocation(), *this);
16654     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16655       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16656                          *this);
16657     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16658       for (VarDecl *VD : *FP)
16659         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16660     } else {
16661       llvm_unreachable("Unexpected expression");
16662     }
16663   }
16664 
16665   assert(MaybeODRUseExprs.empty() &&
16666          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16667 }
16668 
16669 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16670                                     VarDecl *Var, Expr *E) {
16671   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16672           isa<FunctionParmPackExpr>(E)) &&
16673          "Invalid Expr argument to DoMarkVarDeclReferenced");
16674   Var->setReferenced();
16675 
16676   if (Var->isInvalidDecl())
16677     return;
16678 
16679   auto *MSI = Var->getMemberSpecializationInfo();
16680   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16681                                        : Var->getTemplateSpecializationKind();
16682 
16683   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16684   bool UsableInConstantExpr =
16685       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16686 
16687   // C++20 [expr.const]p12:
16688   //   A variable [...] is needed for constant evaluation if it is [...] a
16689   //   variable whose name appears as a potentially constant evaluated
16690   //   expression that is either a contexpr variable or is of non-volatile
16691   //   const-qualified integral type or of reference type
16692   bool NeededForConstantEvaluation =
16693       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16694 
16695   bool NeedDefinition =
16696       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16697 
16698   VarTemplateSpecializationDecl *VarSpec =
16699       dyn_cast<VarTemplateSpecializationDecl>(Var);
16700   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16701          "Can't instantiate a partial template specialization.");
16702 
16703   // If this might be a member specialization of a static data member, check
16704   // the specialization is visible. We already did the checks for variable
16705   // template specializations when we created them.
16706   if (NeedDefinition && TSK != TSK_Undeclared &&
16707       !isa<VarTemplateSpecializationDecl>(Var))
16708     SemaRef.checkSpecializationVisibility(Loc, Var);
16709 
16710   // Perform implicit instantiation of static data members, static data member
16711   // templates of class templates, and variable template specializations. Delay
16712   // instantiations of variable templates, except for those that could be used
16713   // in a constant expression.
16714   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16715     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16716     // instantiation declaration if a variable is usable in a constant
16717     // expression (among other cases).
16718     bool TryInstantiating =
16719         TSK == TSK_ImplicitInstantiation ||
16720         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16721 
16722     if (TryInstantiating) {
16723       SourceLocation PointOfInstantiation =
16724           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16725       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16726       if (FirstInstantiation) {
16727         PointOfInstantiation = Loc;
16728         if (MSI)
16729           MSI->setPointOfInstantiation(PointOfInstantiation);
16730         else
16731           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16732       }
16733 
16734       bool InstantiationDependent = false;
16735       bool IsNonDependent =
16736           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16737                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16738                   : true;
16739 
16740       // Do not instantiate specializations that are still type-dependent.
16741       if (IsNonDependent) {
16742         if (UsableInConstantExpr) {
16743           // Do not defer instantiations of variables that could be used in a
16744           // constant expression.
16745           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16746             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16747           });
16748         } else if (FirstInstantiation ||
16749                    isa<VarTemplateSpecializationDecl>(Var)) {
16750           // FIXME: For a specialization of a variable template, we don't
16751           // distinguish between "declaration and type implicitly instantiated"
16752           // and "implicit instantiation of definition requested", so we have
16753           // no direct way to avoid enqueueing the pending instantiation
16754           // multiple times.
16755           SemaRef.PendingInstantiations
16756               .push_back(std::make_pair(Var, PointOfInstantiation));
16757         }
16758       }
16759     }
16760   }
16761 
16762   // C++2a [basic.def.odr]p4:
16763   //   A variable x whose name appears as a potentially-evaluated expression e
16764   //   is odr-used by e unless
16765   //   -- x is a reference that is usable in constant expressions
16766   //   -- x is a variable of non-reference type that is usable in constant
16767   //      expressions and has no mutable subobjects [FIXME], and e is an
16768   //      element of the set of potential results of an expression of
16769   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16770   //      conversion is applied
16771   //   -- x is a variable of non-reference type, and e is an element of the set
16772   //      of potential results of a discarded-value expression to which the
16773   //      lvalue-to-rvalue conversion is not applied [FIXME]
16774   //
16775   // We check the first part of the second bullet here, and
16776   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16777   // FIXME: To get the third bullet right, we need to delay this even for
16778   // variables that are not usable in constant expressions.
16779 
16780   // If we already know this isn't an odr-use, there's nothing more to do.
16781   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16782     if (DRE->isNonOdrUse())
16783       return;
16784   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16785     if (ME->isNonOdrUse())
16786       return;
16787 
16788   switch (OdrUse) {
16789   case OdrUseContext::None:
16790     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16791            "missing non-odr-use marking for unevaluated decl ref");
16792     break;
16793 
16794   case OdrUseContext::FormallyOdrUsed:
16795     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16796     // behavior.
16797     break;
16798 
16799   case OdrUseContext::Used:
16800     // If we might later find that this expression isn't actually an odr-use,
16801     // delay the marking.
16802     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16803       SemaRef.MaybeODRUseExprs.insert(E);
16804     else
16805       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16806     break;
16807 
16808   case OdrUseContext::Dependent:
16809     // If this is a dependent context, we don't need to mark variables as
16810     // odr-used, but we may still need to track them for lambda capture.
16811     // FIXME: Do we also need to do this inside dependent typeid expressions
16812     // (which are modeled as unevaluated at this point)?
16813     const bool RefersToEnclosingScope =
16814         (SemaRef.CurContext != Var->getDeclContext() &&
16815          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16816     if (RefersToEnclosingScope) {
16817       LambdaScopeInfo *const LSI =
16818           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16819       if (LSI && (!LSI->CallOperator ||
16820                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16821         // If a variable could potentially be odr-used, defer marking it so
16822         // until we finish analyzing the full expression for any
16823         // lvalue-to-rvalue
16824         // or discarded value conversions that would obviate odr-use.
16825         // Add it to the list of potential captures that will be analyzed
16826         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16827         // unless the variable is a reference that was initialized by a constant
16828         // expression (this will never need to be captured or odr-used).
16829         //
16830         // FIXME: We can simplify this a lot after implementing P0588R1.
16831         assert(E && "Capture variable should be used in an expression.");
16832         if (!Var->getType()->isReferenceType() ||
16833             !Var->isUsableInConstantExpressions(SemaRef.Context))
16834           LSI->addPotentialCapture(E->IgnoreParens());
16835       }
16836     }
16837     break;
16838   }
16839 }
16840 
16841 /// Mark a variable referenced, and check whether it is odr-used
16842 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16843 /// used directly for normal expressions referring to VarDecl.
16844 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16845   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16846 }
16847 
16848 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16849                                Decl *D, Expr *E, bool MightBeOdrUse) {
16850   if (SemaRef.isInOpenMPDeclareTargetContext())
16851     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16852 
16853   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16854     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16855     return;
16856   }
16857 
16858   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16859 
16860   // If this is a call to a method via a cast, also mark the method in the
16861   // derived class used in case codegen can devirtualize the call.
16862   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16863   if (!ME)
16864     return;
16865   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16866   if (!MD)
16867     return;
16868   // Only attempt to devirtualize if this is truly a virtual call.
16869   bool IsVirtualCall = MD->isVirtual() &&
16870                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16871   if (!IsVirtualCall)
16872     return;
16873 
16874   // If it's possible to devirtualize the call, mark the called function
16875   // referenced.
16876   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16877       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16878   if (DM)
16879     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16880 }
16881 
16882 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16883 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16884   // TODO: update this with DR# once a defect report is filed.
16885   // C++11 defect. The address of a pure member should not be an ODR use, even
16886   // if it's a qualified reference.
16887   bool OdrUse = true;
16888   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16889     if (Method->isVirtual() &&
16890         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16891       OdrUse = false;
16892   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16893 }
16894 
16895 /// Perform reference-marking and odr-use handling for a MemberExpr.
16896 void Sema::MarkMemberReferenced(MemberExpr *E) {
16897   // C++11 [basic.def.odr]p2:
16898   //   A non-overloaded function whose name appears as a potentially-evaluated
16899   //   expression or a member of a set of candidate functions, if selected by
16900   //   overload resolution when referred to from a potentially-evaluated
16901   //   expression, is odr-used, unless it is a pure virtual function and its
16902   //   name is not explicitly qualified.
16903   bool MightBeOdrUse = true;
16904   if (E->performsVirtualDispatch(getLangOpts())) {
16905     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16906       if (Method->isPure())
16907         MightBeOdrUse = false;
16908   }
16909   SourceLocation Loc =
16910       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16911   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16912 }
16913 
16914 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16915 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16916   for (VarDecl *VD : *E)
16917     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16918 }
16919 
16920 /// Perform marking for a reference to an arbitrary declaration.  It
16921 /// marks the declaration referenced, and performs odr-use checking for
16922 /// functions and variables. This method should not be used when building a
16923 /// normal expression which refers to a variable.
16924 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16925                                  bool MightBeOdrUse) {
16926   if (MightBeOdrUse) {
16927     if (auto *VD = dyn_cast<VarDecl>(D)) {
16928       MarkVariableReferenced(Loc, VD);
16929       return;
16930     }
16931   }
16932   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16933     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16934     return;
16935   }
16936   D->setReferenced();
16937 }
16938 
16939 namespace {
16940   // Mark all of the declarations used by a type as referenced.
16941   // FIXME: Not fully implemented yet! We need to have a better understanding
16942   // of when we're entering a context we should not recurse into.
16943   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16944   // TreeTransforms rebuilding the type in a new context. Rather than
16945   // duplicating the TreeTransform logic, we should consider reusing it here.
16946   // Currently that causes problems when rebuilding LambdaExprs.
16947   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16948     Sema &S;
16949     SourceLocation Loc;
16950 
16951   public:
16952     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16953 
16954     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16955 
16956     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16957   };
16958 }
16959 
16960 bool MarkReferencedDecls::TraverseTemplateArgument(
16961     const TemplateArgument &Arg) {
16962   {
16963     // A non-type template argument is a constant-evaluated context.
16964     EnterExpressionEvaluationContext Evaluated(
16965         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16966     if (Arg.getKind() == TemplateArgument::Declaration) {
16967       if (Decl *D = Arg.getAsDecl())
16968         S.MarkAnyDeclReferenced(Loc, D, true);
16969     } else if (Arg.getKind() == TemplateArgument::Expression) {
16970       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16971     }
16972   }
16973 
16974   return Inherited::TraverseTemplateArgument(Arg);
16975 }
16976 
16977 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16978   MarkReferencedDecls Marker(*this, Loc);
16979   Marker.TraverseType(T);
16980 }
16981 
16982 namespace {
16983   /// Helper class that marks all of the declarations referenced by
16984   /// potentially-evaluated subexpressions as "referenced".
16985   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16986     Sema &S;
16987     bool SkipLocalVariables;
16988 
16989   public:
16990     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16991 
16992     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16993       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16994 
16995     void VisitDeclRefExpr(DeclRefExpr *E) {
16996       // If we were asked not to visit local variables, don't.
16997       if (SkipLocalVariables) {
16998         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16999           if (VD->hasLocalStorage())
17000             return;
17001       }
17002 
17003       S.MarkDeclRefReferenced(E);
17004     }
17005 
17006     void VisitMemberExpr(MemberExpr *E) {
17007       S.MarkMemberReferenced(E);
17008       Inherited::VisitMemberExpr(E);
17009     }
17010 
17011     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
17012       S.MarkFunctionReferenced(
17013           E->getBeginLoc(),
17014           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
17015       Visit(E->getSubExpr());
17016     }
17017 
17018     void VisitCXXNewExpr(CXXNewExpr *E) {
17019       if (E->getOperatorNew())
17020         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
17021       if (E->getOperatorDelete())
17022         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17023       Inherited::VisitCXXNewExpr(E);
17024     }
17025 
17026     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
17027       if (E->getOperatorDelete())
17028         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17029       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
17030       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
17031         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
17032         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
17033       }
17034 
17035       Inherited::VisitCXXDeleteExpr(E);
17036     }
17037 
17038     void VisitCXXConstructExpr(CXXConstructExpr *E) {
17039       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
17040       Inherited::VisitCXXConstructExpr(E);
17041     }
17042 
17043     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
17044       Visit(E->getExpr());
17045     }
17046   };
17047 }
17048 
17049 /// Mark any declarations that appear within this expression or any
17050 /// potentially-evaluated subexpressions as "referenced".
17051 ///
17052 /// \param SkipLocalVariables If true, don't mark local variables as
17053 /// 'referenced'.
17054 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17055                                             bool SkipLocalVariables) {
17056   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17057 }
17058 
17059 /// Emit a diagnostic that describes an effect on the run-time behavior
17060 /// of the program being compiled.
17061 ///
17062 /// This routine emits the given diagnostic when the code currently being
17063 /// type-checked is "potentially evaluated", meaning that there is a
17064 /// possibility that the code will actually be executable. Code in sizeof()
17065 /// expressions, code used only during overload resolution, etc., are not
17066 /// potentially evaluated. This routine will suppress such diagnostics or,
17067 /// in the absolutely nutty case of potentially potentially evaluated
17068 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
17069 /// later.
17070 ///
17071 /// This routine should be used for all diagnostics that describe the run-time
17072 /// behavior of a program, such as passing a non-POD value through an ellipsis.
17073 /// Failure to do so will likely result in spurious diagnostics or failures
17074 /// during overload resolution or within sizeof/alignof/typeof/typeid.
17075 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17076                                const PartialDiagnostic &PD) {
17077   switch (ExprEvalContexts.back().Context) {
17078   case ExpressionEvaluationContext::Unevaluated:
17079   case ExpressionEvaluationContext::UnevaluatedList:
17080   case ExpressionEvaluationContext::UnevaluatedAbstract:
17081   case ExpressionEvaluationContext::DiscardedStatement:
17082     // The argument will never be evaluated, so don't complain.
17083     break;
17084 
17085   case ExpressionEvaluationContext::ConstantEvaluated:
17086     // Relevant diagnostics should be produced by constant evaluation.
17087     break;
17088 
17089   case ExpressionEvaluationContext::PotentiallyEvaluated:
17090   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17091     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17092       FunctionScopes.back()->PossiblyUnreachableDiags.
17093         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17094       return true;
17095     }
17096 
17097     // The initializer of a constexpr variable or of the first declaration of a
17098     // static data member is not syntactically a constant evaluated constant,
17099     // but nonetheless is always required to be a constant expression, so we
17100     // can skip diagnosing.
17101     // FIXME: Using the mangling context here is a hack.
17102     if (auto *VD = dyn_cast_or_null<VarDecl>(
17103             ExprEvalContexts.back().ManglingContextDecl)) {
17104       if (VD->isConstexpr() ||
17105           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17106         break;
17107       // FIXME: For any other kind of variable, we should build a CFG for its
17108       // initializer and check whether the context in question is reachable.
17109     }
17110 
17111     Diag(Loc, PD);
17112     return true;
17113   }
17114 
17115   return false;
17116 }
17117 
17118 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17119                                const PartialDiagnostic &PD) {
17120   return DiagRuntimeBehavior(
17121       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17122 }
17123 
17124 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17125                                CallExpr *CE, FunctionDecl *FD) {
17126   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17127     return false;
17128 
17129   // If we're inside a decltype's expression, don't check for a valid return
17130   // type or construct temporaries until we know whether this is the last call.
17131   if (ExprEvalContexts.back().ExprContext ==
17132       ExpressionEvaluationContextRecord::EK_Decltype) {
17133     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17134     return false;
17135   }
17136 
17137   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17138     FunctionDecl *FD;
17139     CallExpr *CE;
17140 
17141   public:
17142     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17143       : FD(FD), CE(CE) { }
17144 
17145     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17146       if (!FD) {
17147         S.Diag(Loc, diag::err_call_incomplete_return)
17148           << T << CE->getSourceRange();
17149         return;
17150       }
17151 
17152       S.Diag(Loc, diag::err_call_function_incomplete_return)
17153         << CE->getSourceRange() << FD->getDeclName() << T;
17154       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17155           << FD->getDeclName();
17156     }
17157   } Diagnoser(FD, CE);
17158 
17159   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17160     return true;
17161 
17162   return false;
17163 }
17164 
17165 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17166 // will prevent this condition from triggering, which is what we want.
17167 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17168   SourceLocation Loc;
17169 
17170   unsigned diagnostic = diag::warn_condition_is_assignment;
17171   bool IsOrAssign = false;
17172 
17173   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17174     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17175       return;
17176 
17177     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17178 
17179     // Greylist some idioms by putting them into a warning subcategory.
17180     if (ObjCMessageExpr *ME
17181           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17182       Selector Sel = ME->getSelector();
17183 
17184       // self = [<foo> init...]
17185       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17186         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17187 
17188       // <foo> = [<bar> nextObject]
17189       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17190         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17191     }
17192 
17193     Loc = Op->getOperatorLoc();
17194   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17195     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17196       return;
17197 
17198     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17199     Loc = Op->getOperatorLoc();
17200   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17201     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17202   else {
17203     // Not an assignment.
17204     return;
17205   }
17206 
17207   Diag(Loc, diagnostic) << E->getSourceRange();
17208 
17209   SourceLocation Open = E->getBeginLoc();
17210   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17211   Diag(Loc, diag::note_condition_assign_silence)
17212         << FixItHint::CreateInsertion(Open, "(")
17213         << FixItHint::CreateInsertion(Close, ")");
17214 
17215   if (IsOrAssign)
17216     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17217       << FixItHint::CreateReplacement(Loc, "!=");
17218   else
17219     Diag(Loc, diag::note_condition_assign_to_comparison)
17220       << FixItHint::CreateReplacement(Loc, "==");
17221 }
17222 
17223 /// Redundant parentheses over an equality comparison can indicate
17224 /// that the user intended an assignment used as condition.
17225 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17226   // Don't warn if the parens came from a macro.
17227   SourceLocation parenLoc = ParenE->getBeginLoc();
17228   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17229     return;
17230   // Don't warn for dependent expressions.
17231   if (ParenE->isTypeDependent())
17232     return;
17233 
17234   Expr *E = ParenE->IgnoreParens();
17235 
17236   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17237     if (opE->getOpcode() == BO_EQ &&
17238         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17239                                                            == Expr::MLV_Valid) {
17240       SourceLocation Loc = opE->getOperatorLoc();
17241 
17242       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17243       SourceRange ParenERange = ParenE->getSourceRange();
17244       Diag(Loc, diag::note_equality_comparison_silence)
17245         << FixItHint::CreateRemoval(ParenERange.getBegin())
17246         << FixItHint::CreateRemoval(ParenERange.getEnd());
17247       Diag(Loc, diag::note_equality_comparison_to_assign)
17248         << FixItHint::CreateReplacement(Loc, "=");
17249     }
17250 }
17251 
17252 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17253                                        bool IsConstexpr) {
17254   DiagnoseAssignmentAsCondition(E);
17255   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17256     DiagnoseEqualityWithExtraParens(parenE);
17257 
17258   ExprResult result = CheckPlaceholderExpr(E);
17259   if (result.isInvalid()) return ExprError();
17260   E = result.get();
17261 
17262   if (!E->isTypeDependent()) {
17263     if (getLangOpts().CPlusPlus)
17264       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17265 
17266     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17267     if (ERes.isInvalid())
17268       return ExprError();
17269     E = ERes.get();
17270 
17271     QualType T = E->getType();
17272     if (!T->isScalarType()) { // C99 6.8.4.1p1
17273       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17274         << T << E->getSourceRange();
17275       return ExprError();
17276     }
17277     CheckBoolLikeConversion(E, Loc);
17278   }
17279 
17280   return E;
17281 }
17282 
17283 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17284                                            Expr *SubExpr, ConditionKind CK) {
17285   // Empty conditions are valid in for-statements.
17286   if (!SubExpr)
17287     return ConditionResult();
17288 
17289   ExprResult Cond;
17290   switch (CK) {
17291   case ConditionKind::Boolean:
17292     Cond = CheckBooleanCondition(Loc, SubExpr);
17293     break;
17294 
17295   case ConditionKind::ConstexprIf:
17296     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17297     break;
17298 
17299   case ConditionKind::Switch:
17300     Cond = CheckSwitchCondition(Loc, SubExpr);
17301     break;
17302   }
17303   if (Cond.isInvalid())
17304     return ConditionError();
17305 
17306   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17307   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17308   if (!FullExpr.get())
17309     return ConditionError();
17310 
17311   return ConditionResult(*this, nullptr, FullExpr,
17312                          CK == ConditionKind::ConstexprIf);
17313 }
17314 
17315 namespace {
17316   /// A visitor for rebuilding a call to an __unknown_any expression
17317   /// to have an appropriate type.
17318   struct RebuildUnknownAnyFunction
17319     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17320 
17321     Sema &S;
17322 
17323     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17324 
17325     ExprResult VisitStmt(Stmt *S) {
17326       llvm_unreachable("unexpected statement!");
17327     }
17328 
17329     ExprResult VisitExpr(Expr *E) {
17330       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17331         << E->getSourceRange();
17332       return ExprError();
17333     }
17334 
17335     /// Rebuild an expression which simply semantically wraps another
17336     /// expression which it shares the type and value kind of.
17337     template <class T> ExprResult rebuildSugarExpr(T *E) {
17338       ExprResult SubResult = Visit(E->getSubExpr());
17339       if (SubResult.isInvalid()) return ExprError();
17340 
17341       Expr *SubExpr = SubResult.get();
17342       E->setSubExpr(SubExpr);
17343       E->setType(SubExpr->getType());
17344       E->setValueKind(SubExpr->getValueKind());
17345       assert(E->getObjectKind() == OK_Ordinary);
17346       return E;
17347     }
17348 
17349     ExprResult VisitParenExpr(ParenExpr *E) {
17350       return rebuildSugarExpr(E);
17351     }
17352 
17353     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17354       return rebuildSugarExpr(E);
17355     }
17356 
17357     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17358       ExprResult SubResult = Visit(E->getSubExpr());
17359       if (SubResult.isInvalid()) return ExprError();
17360 
17361       Expr *SubExpr = SubResult.get();
17362       E->setSubExpr(SubExpr);
17363       E->setType(S.Context.getPointerType(SubExpr->getType()));
17364       assert(E->getValueKind() == VK_RValue);
17365       assert(E->getObjectKind() == OK_Ordinary);
17366       return E;
17367     }
17368 
17369     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17370       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17371 
17372       E->setType(VD->getType());
17373 
17374       assert(E->getValueKind() == VK_RValue);
17375       if (S.getLangOpts().CPlusPlus &&
17376           !(isa<CXXMethodDecl>(VD) &&
17377             cast<CXXMethodDecl>(VD)->isInstance()))
17378         E->setValueKind(VK_LValue);
17379 
17380       return E;
17381     }
17382 
17383     ExprResult VisitMemberExpr(MemberExpr *E) {
17384       return resolveDecl(E, E->getMemberDecl());
17385     }
17386 
17387     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17388       return resolveDecl(E, E->getDecl());
17389     }
17390   };
17391 }
17392 
17393 /// Given a function expression of unknown-any type, try to rebuild it
17394 /// to have a function type.
17395 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17396   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17397   if (Result.isInvalid()) return ExprError();
17398   return S.DefaultFunctionArrayConversion(Result.get());
17399 }
17400 
17401 namespace {
17402   /// A visitor for rebuilding an expression of type __unknown_anytype
17403   /// into one which resolves the type directly on the referring
17404   /// expression.  Strict preservation of the original source
17405   /// structure is not a goal.
17406   struct RebuildUnknownAnyExpr
17407     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17408 
17409     Sema &S;
17410 
17411     /// The current destination type.
17412     QualType DestType;
17413 
17414     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17415       : S(S), DestType(CastType) {}
17416 
17417     ExprResult VisitStmt(Stmt *S) {
17418       llvm_unreachable("unexpected statement!");
17419     }
17420 
17421     ExprResult VisitExpr(Expr *E) {
17422       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17423         << E->getSourceRange();
17424       return ExprError();
17425     }
17426 
17427     ExprResult VisitCallExpr(CallExpr *E);
17428     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17429 
17430     /// Rebuild an expression which simply semantically wraps another
17431     /// expression which it shares the type and value kind of.
17432     template <class T> ExprResult rebuildSugarExpr(T *E) {
17433       ExprResult SubResult = Visit(E->getSubExpr());
17434       if (SubResult.isInvalid()) return ExprError();
17435       Expr *SubExpr = SubResult.get();
17436       E->setSubExpr(SubExpr);
17437       E->setType(SubExpr->getType());
17438       E->setValueKind(SubExpr->getValueKind());
17439       assert(E->getObjectKind() == OK_Ordinary);
17440       return E;
17441     }
17442 
17443     ExprResult VisitParenExpr(ParenExpr *E) {
17444       return rebuildSugarExpr(E);
17445     }
17446 
17447     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17448       return rebuildSugarExpr(E);
17449     }
17450 
17451     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17452       const PointerType *Ptr = DestType->getAs<PointerType>();
17453       if (!Ptr) {
17454         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17455           << E->getSourceRange();
17456         return ExprError();
17457       }
17458 
17459       if (isa<CallExpr>(E->getSubExpr())) {
17460         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17461           << E->getSourceRange();
17462         return ExprError();
17463       }
17464 
17465       assert(E->getValueKind() == VK_RValue);
17466       assert(E->getObjectKind() == OK_Ordinary);
17467       E->setType(DestType);
17468 
17469       // Build the sub-expression as if it were an object of the pointee type.
17470       DestType = Ptr->getPointeeType();
17471       ExprResult SubResult = Visit(E->getSubExpr());
17472       if (SubResult.isInvalid()) return ExprError();
17473       E->setSubExpr(SubResult.get());
17474       return E;
17475     }
17476 
17477     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17478 
17479     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17480 
17481     ExprResult VisitMemberExpr(MemberExpr *E) {
17482       return resolveDecl(E, E->getMemberDecl());
17483     }
17484 
17485     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17486       return resolveDecl(E, E->getDecl());
17487     }
17488   };
17489 }
17490 
17491 /// Rebuilds a call expression which yielded __unknown_anytype.
17492 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17493   Expr *CalleeExpr = E->getCallee();
17494 
17495   enum FnKind {
17496     FK_MemberFunction,
17497     FK_FunctionPointer,
17498     FK_BlockPointer
17499   };
17500 
17501   FnKind Kind;
17502   QualType CalleeType = CalleeExpr->getType();
17503   if (CalleeType == S.Context.BoundMemberTy) {
17504     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17505     Kind = FK_MemberFunction;
17506     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17507   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17508     CalleeType = Ptr->getPointeeType();
17509     Kind = FK_FunctionPointer;
17510   } else {
17511     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17512     Kind = FK_BlockPointer;
17513   }
17514   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17515 
17516   // Verify that this is a legal result type of a function.
17517   if (DestType->isArrayType() || DestType->isFunctionType()) {
17518     unsigned diagID = diag::err_func_returning_array_function;
17519     if (Kind == FK_BlockPointer)
17520       diagID = diag::err_block_returning_array_function;
17521 
17522     S.Diag(E->getExprLoc(), diagID)
17523       << DestType->isFunctionType() << DestType;
17524     return ExprError();
17525   }
17526 
17527   // Otherwise, go ahead and set DestType as the call's result.
17528   E->setType(DestType.getNonLValueExprType(S.Context));
17529   E->setValueKind(Expr::getValueKindForType(DestType));
17530   assert(E->getObjectKind() == OK_Ordinary);
17531 
17532   // Rebuild the function type, replacing the result type with DestType.
17533   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17534   if (Proto) {
17535     // __unknown_anytype(...) is a special case used by the debugger when
17536     // it has no idea what a function's signature is.
17537     //
17538     // We want to build this call essentially under the K&R
17539     // unprototyped rules, but making a FunctionNoProtoType in C++
17540     // would foul up all sorts of assumptions.  However, we cannot
17541     // simply pass all arguments as variadic arguments, nor can we
17542     // portably just call the function under a non-variadic type; see
17543     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17544     // However, it turns out that in practice it is generally safe to
17545     // call a function declared as "A foo(B,C,D);" under the prototype
17546     // "A foo(B,C,D,...);".  The only known exception is with the
17547     // Windows ABI, where any variadic function is implicitly cdecl
17548     // regardless of its normal CC.  Therefore we change the parameter
17549     // types to match the types of the arguments.
17550     //
17551     // This is a hack, but it is far superior to moving the
17552     // corresponding target-specific code from IR-gen to Sema/AST.
17553 
17554     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17555     SmallVector<QualType, 8> ArgTypes;
17556     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17557       ArgTypes.reserve(E->getNumArgs());
17558       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17559         Expr *Arg = E->getArg(i);
17560         QualType ArgType = Arg->getType();
17561         if (E->isLValue()) {
17562           ArgType = S.Context.getLValueReferenceType(ArgType);
17563         } else if (E->isXValue()) {
17564           ArgType = S.Context.getRValueReferenceType(ArgType);
17565         }
17566         ArgTypes.push_back(ArgType);
17567       }
17568       ParamTypes = ArgTypes;
17569     }
17570     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17571                                          Proto->getExtProtoInfo());
17572   } else {
17573     DestType = S.Context.getFunctionNoProtoType(DestType,
17574                                                 FnType->getExtInfo());
17575   }
17576 
17577   // Rebuild the appropriate pointer-to-function type.
17578   switch (Kind) {
17579   case FK_MemberFunction:
17580     // Nothing to do.
17581     break;
17582 
17583   case FK_FunctionPointer:
17584     DestType = S.Context.getPointerType(DestType);
17585     break;
17586 
17587   case FK_BlockPointer:
17588     DestType = S.Context.getBlockPointerType(DestType);
17589     break;
17590   }
17591 
17592   // Finally, we can recurse.
17593   ExprResult CalleeResult = Visit(CalleeExpr);
17594   if (!CalleeResult.isUsable()) return ExprError();
17595   E->setCallee(CalleeResult.get());
17596 
17597   // Bind a temporary if necessary.
17598   return S.MaybeBindToTemporary(E);
17599 }
17600 
17601 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17602   // Verify that this is a legal result type of a call.
17603   if (DestType->isArrayType() || DestType->isFunctionType()) {
17604     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17605       << DestType->isFunctionType() << DestType;
17606     return ExprError();
17607   }
17608 
17609   // Rewrite the method result type if available.
17610   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17611     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17612     Method->setReturnType(DestType);
17613   }
17614 
17615   // Change the type of the message.
17616   E->setType(DestType.getNonReferenceType());
17617   E->setValueKind(Expr::getValueKindForType(DestType));
17618 
17619   return S.MaybeBindToTemporary(E);
17620 }
17621 
17622 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17623   // The only case we should ever see here is a function-to-pointer decay.
17624   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17625     assert(E->getValueKind() == VK_RValue);
17626     assert(E->getObjectKind() == OK_Ordinary);
17627 
17628     E->setType(DestType);
17629 
17630     // Rebuild the sub-expression as the pointee (function) type.
17631     DestType = DestType->castAs<PointerType>()->getPointeeType();
17632 
17633     ExprResult Result = Visit(E->getSubExpr());
17634     if (!Result.isUsable()) return ExprError();
17635 
17636     E->setSubExpr(Result.get());
17637     return E;
17638   } else if (E->getCastKind() == CK_LValueToRValue) {
17639     assert(E->getValueKind() == VK_RValue);
17640     assert(E->getObjectKind() == OK_Ordinary);
17641 
17642     assert(isa<BlockPointerType>(E->getType()));
17643 
17644     E->setType(DestType);
17645 
17646     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17647     DestType = S.Context.getLValueReferenceType(DestType);
17648 
17649     ExprResult Result = Visit(E->getSubExpr());
17650     if (!Result.isUsable()) return ExprError();
17651 
17652     E->setSubExpr(Result.get());
17653     return E;
17654   } else {
17655     llvm_unreachable("Unhandled cast type!");
17656   }
17657 }
17658 
17659 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17660   ExprValueKind ValueKind = VK_LValue;
17661   QualType Type = DestType;
17662 
17663   // We know how to make this work for certain kinds of decls:
17664 
17665   //  - functions
17666   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17667     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17668       DestType = Ptr->getPointeeType();
17669       ExprResult Result = resolveDecl(E, VD);
17670       if (Result.isInvalid()) return ExprError();
17671       return S.ImpCastExprToType(Result.get(), Type,
17672                                  CK_FunctionToPointerDecay, VK_RValue);
17673     }
17674 
17675     if (!Type->isFunctionType()) {
17676       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17677         << VD << E->getSourceRange();
17678       return ExprError();
17679     }
17680     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17681       // We must match the FunctionDecl's type to the hack introduced in
17682       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17683       // type. See the lengthy commentary in that routine.
17684       QualType FDT = FD->getType();
17685       const FunctionType *FnType = FDT->castAs<FunctionType>();
17686       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17687       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17688       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17689         SourceLocation Loc = FD->getLocation();
17690         FunctionDecl *NewFD = FunctionDecl::Create(
17691             S.Context, FD->getDeclContext(), Loc, Loc,
17692             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17693             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17694             /*ConstexprKind*/ CSK_unspecified);
17695 
17696         if (FD->getQualifier())
17697           NewFD->setQualifierInfo(FD->getQualifierLoc());
17698 
17699         SmallVector<ParmVarDecl*, 16> Params;
17700         for (const auto &AI : FT->param_types()) {
17701           ParmVarDecl *Param =
17702             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17703           Param->setScopeInfo(0, Params.size());
17704           Params.push_back(Param);
17705         }
17706         NewFD->setParams(Params);
17707         DRE->setDecl(NewFD);
17708         VD = DRE->getDecl();
17709       }
17710     }
17711 
17712     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17713       if (MD->isInstance()) {
17714         ValueKind = VK_RValue;
17715         Type = S.Context.BoundMemberTy;
17716       }
17717 
17718     // Function references aren't l-values in C.
17719     if (!S.getLangOpts().CPlusPlus)
17720       ValueKind = VK_RValue;
17721 
17722   //  - variables
17723   } else if (isa<VarDecl>(VD)) {
17724     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17725       Type = RefTy->getPointeeType();
17726     } else if (Type->isFunctionType()) {
17727       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17728         << VD << E->getSourceRange();
17729       return ExprError();
17730     }
17731 
17732   //  - nothing else
17733   } else {
17734     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17735       << VD << E->getSourceRange();
17736     return ExprError();
17737   }
17738 
17739   // Modifying the declaration like this is friendly to IR-gen but
17740   // also really dangerous.
17741   VD->setType(DestType);
17742   E->setType(Type);
17743   E->setValueKind(ValueKind);
17744   return E;
17745 }
17746 
17747 /// Check a cast of an unknown-any type.  We intentionally only
17748 /// trigger this for C-style casts.
17749 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17750                                      Expr *CastExpr, CastKind &CastKind,
17751                                      ExprValueKind &VK, CXXCastPath &Path) {
17752   // The type we're casting to must be either void or complete.
17753   if (!CastType->isVoidType() &&
17754       RequireCompleteType(TypeRange.getBegin(), CastType,
17755                           diag::err_typecheck_cast_to_incomplete))
17756     return ExprError();
17757 
17758   // Rewrite the casted expression from scratch.
17759   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17760   if (!result.isUsable()) return ExprError();
17761 
17762   CastExpr = result.get();
17763   VK = CastExpr->getValueKind();
17764   CastKind = CK_NoOp;
17765 
17766   return CastExpr;
17767 }
17768 
17769 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17770   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17771 }
17772 
17773 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17774                                     Expr *arg, QualType &paramType) {
17775   // If the syntactic form of the argument is not an explicit cast of
17776   // any sort, just do default argument promotion.
17777   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17778   if (!castArg) {
17779     ExprResult result = DefaultArgumentPromotion(arg);
17780     if (result.isInvalid()) return ExprError();
17781     paramType = result.get()->getType();
17782     return result;
17783   }
17784 
17785   // Otherwise, use the type that was written in the explicit cast.
17786   assert(!arg->hasPlaceholderType());
17787   paramType = castArg->getTypeAsWritten();
17788 
17789   // Copy-initialize a parameter of that type.
17790   InitializedEntity entity =
17791     InitializedEntity::InitializeParameter(Context, paramType,
17792                                            /*consumed*/ false);
17793   return PerformCopyInitialization(entity, callLoc, arg);
17794 }
17795 
17796 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17797   Expr *orig = E;
17798   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17799   while (true) {
17800     E = E->IgnoreParenImpCasts();
17801     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17802       E = call->getCallee();
17803       diagID = diag::err_uncasted_call_of_unknown_any;
17804     } else {
17805       break;
17806     }
17807   }
17808 
17809   SourceLocation loc;
17810   NamedDecl *d;
17811   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17812     loc = ref->getLocation();
17813     d = ref->getDecl();
17814   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17815     loc = mem->getMemberLoc();
17816     d = mem->getMemberDecl();
17817   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17818     diagID = diag::err_uncasted_call_of_unknown_any;
17819     loc = msg->getSelectorStartLoc();
17820     d = msg->getMethodDecl();
17821     if (!d) {
17822       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17823         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17824         << orig->getSourceRange();
17825       return ExprError();
17826     }
17827   } else {
17828     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17829       << E->getSourceRange();
17830     return ExprError();
17831   }
17832 
17833   S.Diag(loc, diagID) << d << orig->getSourceRange();
17834 
17835   // Never recoverable.
17836   return ExprError();
17837 }
17838 
17839 /// Check for operands with placeholder types and complain if found.
17840 /// Returns ExprError() if there was an error and no recovery was possible.
17841 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17842   if (!getLangOpts().CPlusPlus) {
17843     // C cannot handle TypoExpr nodes on either side of a binop because it
17844     // doesn't handle dependent types properly, so make sure any TypoExprs have
17845     // been dealt with before checking the operands.
17846     ExprResult Result = CorrectDelayedTyposInExpr(E);
17847     if (!Result.isUsable()) return ExprError();
17848     E = Result.get();
17849   }
17850 
17851   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17852   if (!placeholderType) return E;
17853 
17854   switch (placeholderType->getKind()) {
17855 
17856   // Overloaded expressions.
17857   case BuiltinType::Overload: {
17858     // Try to resolve a single function template specialization.
17859     // This is obligatory.
17860     ExprResult Result = E;
17861     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17862       return Result;
17863 
17864     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17865     // leaves Result unchanged on failure.
17866     Result = E;
17867     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17868       return Result;
17869 
17870     // If that failed, try to recover with a call.
17871     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17872                          /*complain*/ true);
17873     return Result;
17874   }
17875 
17876   // Bound member functions.
17877   case BuiltinType::BoundMember: {
17878     ExprResult result = E;
17879     const Expr *BME = E->IgnoreParens();
17880     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17881     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17882     if (isa<CXXPseudoDestructorExpr>(BME)) {
17883       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17884     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17885       if (ME->getMemberNameInfo().getName().getNameKind() ==
17886           DeclarationName::CXXDestructorName)
17887         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17888     }
17889     tryToRecoverWithCall(result, PD,
17890                          /*complain*/ true);
17891     return result;
17892   }
17893 
17894   // ARC unbridged casts.
17895   case BuiltinType::ARCUnbridgedCast: {
17896     Expr *realCast = stripARCUnbridgedCast(E);
17897     diagnoseARCUnbridgedCast(realCast);
17898     return realCast;
17899   }
17900 
17901   // Expressions of unknown type.
17902   case BuiltinType::UnknownAny:
17903     return diagnoseUnknownAnyExpr(*this, E);
17904 
17905   // Pseudo-objects.
17906   case BuiltinType::PseudoObject:
17907     return checkPseudoObjectRValue(E);
17908 
17909   case BuiltinType::BuiltinFn: {
17910     // Accept __noop without parens by implicitly converting it to a call expr.
17911     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17912     if (DRE) {
17913       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17914       if (FD->getBuiltinID() == Builtin::BI__noop) {
17915         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17916                               CK_BuiltinFnToFnPtr)
17917                 .get();
17918         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17919                                 VK_RValue, SourceLocation());
17920       }
17921     }
17922 
17923     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17924     return ExprError();
17925   }
17926 
17927   // Expressions of unknown type.
17928   case BuiltinType::OMPArraySection:
17929     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17930     return ExprError();
17931 
17932   // Everything else should be impossible.
17933 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17934   case BuiltinType::Id:
17935 #include "clang/Basic/OpenCLImageTypes.def"
17936 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17937   case BuiltinType::Id:
17938 #include "clang/Basic/OpenCLExtensionTypes.def"
17939 #define SVE_TYPE(Name, Id, SingletonId) \
17940   case BuiltinType::Id:
17941 #include "clang/Basic/AArch64SVEACLETypes.def"
17942 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17943 #define PLACEHOLDER_TYPE(Id, SingletonId)
17944 #include "clang/AST/BuiltinTypes.def"
17945     break;
17946   }
17947 
17948   llvm_unreachable("invalid placeholder type!");
17949 }
17950 
17951 bool Sema::CheckCaseExpression(Expr *E) {
17952   if (E->isTypeDependent())
17953     return true;
17954   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17955     return E->getType()->isIntegralOrEnumerationType();
17956   return false;
17957 }
17958 
17959 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17960 ExprResult
17961 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17962   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17963          "Unknown Objective-C Boolean value!");
17964   QualType BoolT = Context.ObjCBuiltinBoolTy;
17965   if (!Context.getBOOLDecl()) {
17966     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17967                         Sema::LookupOrdinaryName);
17968     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17969       NamedDecl *ND = Result.getFoundDecl();
17970       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17971         Context.setBOOLDecl(TD);
17972     }
17973   }
17974   if (Context.getBOOLDecl())
17975     BoolT = Context.getBOOLType();
17976   return new (Context)
17977       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17978 }
17979 
17980 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17981     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17982     SourceLocation RParen) {
17983 
17984   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17985 
17986   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17987     return Spec.getPlatform() == Platform;
17988   });
17989 
17990   VersionTuple Version;
17991   if (Spec != AvailSpecs.end())
17992     Version = Spec->getVersion();
17993 
17994   // The use of `@available` in the enclosing function should be analyzed to
17995   // warn when it's used inappropriately (i.e. not if(@available)).
17996   if (getCurFunctionOrMethodDecl())
17997     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17998   else if (getCurBlock() || getCurLambda())
17999     getCurFunction()->HasPotentialAvailabilityViolations = true;
18000 
18001   return new (Context)
18002       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18003 }
18004