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     // In Microsoft mode, if we are performing lookup from within a friend
1994     // function definition declared at class scope then we must set
1995     // DC to the lexical parent to be able to search into the parent
1996     // class.
1997     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1998         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1999         DC->getLexicalParent()->isRecord())
2000       DC = DC->getLexicalParent();
2001     else
2002       DC = DC->getParent();
2003   }
2004 
2005   // We didn't find anything, so try to correct for a typo.
2006   TypoCorrection Corrected;
2007   if (S && Out) {
2008     SourceLocation TypoLoc = R.getNameLoc();
2009     assert(!ExplicitTemplateArgs &&
2010            "Diagnosing an empty lookup with explicit template args!");
2011     *Out = CorrectTypoDelayed(
2012         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2013         [=](const TypoCorrection &TC) {
2014           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2015                                         diagnostic, diagnostic_suggest);
2016         },
2017         nullptr, CTK_ErrorRecovery);
2018     if (*Out)
2019       return true;
2020   } else if (S &&
2021              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2022                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2023     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2024     bool DroppedSpecifier =
2025         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2026     R.setLookupName(Corrected.getCorrection());
2027 
2028     bool AcceptableWithRecovery = false;
2029     bool AcceptableWithoutRecovery = false;
2030     NamedDecl *ND = Corrected.getFoundDecl();
2031     if (ND) {
2032       if (Corrected.isOverloaded()) {
2033         OverloadCandidateSet OCS(R.getNameLoc(),
2034                                  OverloadCandidateSet::CSK_Normal);
2035         OverloadCandidateSet::iterator Best;
2036         for (NamedDecl *CD : Corrected) {
2037           if (FunctionTemplateDecl *FTD =
2038                    dyn_cast<FunctionTemplateDecl>(CD))
2039             AddTemplateOverloadCandidate(
2040                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2041                 Args, OCS);
2042           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2043             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2044               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2045                                    Args, OCS);
2046         }
2047         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2048         case OR_Success:
2049           ND = Best->FoundDecl;
2050           Corrected.setCorrectionDecl(ND);
2051           break;
2052         default:
2053           // FIXME: Arbitrarily pick the first declaration for the note.
2054           Corrected.setCorrectionDecl(ND);
2055           break;
2056         }
2057       }
2058       R.addDecl(ND);
2059       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2060         CXXRecordDecl *Record = nullptr;
2061         if (Corrected.getCorrectionSpecifier()) {
2062           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2063           Record = Ty->getAsCXXRecordDecl();
2064         }
2065         if (!Record)
2066           Record = cast<CXXRecordDecl>(
2067               ND->getDeclContext()->getRedeclContext());
2068         R.setNamingClass(Record);
2069       }
2070 
2071       auto *UnderlyingND = ND->getUnderlyingDecl();
2072       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2073                                isa<FunctionTemplateDecl>(UnderlyingND);
2074       // FIXME: If we ended up with a typo for a type name or
2075       // Objective-C class name, we're in trouble because the parser
2076       // is in the wrong place to recover. Suggest the typo
2077       // correction, but don't make it a fix-it since we're not going
2078       // to recover well anyway.
2079       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2080                                   getAsTypeTemplateDecl(UnderlyingND) ||
2081                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2082     } else {
2083       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2084       // because we aren't able to recover.
2085       AcceptableWithoutRecovery = true;
2086     }
2087 
2088     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2089       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2090                             ? diag::note_implicit_param_decl
2091                             : diag::note_previous_decl;
2092       if (SS.isEmpty())
2093         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2094                      PDiag(NoteID), AcceptableWithRecovery);
2095       else
2096         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2097                                   << Name << computeDeclContext(SS, false)
2098                                   << DroppedSpecifier << SS.getRange(),
2099                      PDiag(NoteID), AcceptableWithRecovery);
2100 
2101       // Tell the callee whether to try to recover.
2102       return !AcceptableWithRecovery;
2103     }
2104   }
2105   R.clear();
2106 
2107   // Emit a special diagnostic for failed member lookups.
2108   // FIXME: computing the declaration context might fail here (?)
2109   if (!SS.isEmpty()) {
2110     Diag(R.getNameLoc(), diag::err_no_member)
2111       << Name << computeDeclContext(SS, false)
2112       << SS.getRange();
2113     return true;
2114   }
2115 
2116   // Give up, we can't recover.
2117   Diag(R.getNameLoc(), diagnostic) << Name;
2118   return true;
2119 }
2120 
2121 /// In Microsoft mode, if we are inside a template class whose parent class has
2122 /// dependent base classes, and we can't resolve an unqualified identifier, then
2123 /// assume the identifier is a member of a dependent base class.  We can only
2124 /// recover successfully in static methods, instance methods, and other contexts
2125 /// where 'this' is available.  This doesn't precisely match MSVC's
2126 /// instantiation model, but it's close enough.
2127 static Expr *
2128 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2129                                DeclarationNameInfo &NameInfo,
2130                                SourceLocation TemplateKWLoc,
2131                                const TemplateArgumentListInfo *TemplateArgs) {
2132   // Only try to recover from lookup into dependent bases in static methods or
2133   // contexts where 'this' is available.
2134   QualType ThisType = S.getCurrentThisType();
2135   const CXXRecordDecl *RD = nullptr;
2136   if (!ThisType.isNull())
2137     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2138   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2139     RD = MD->getParent();
2140   if (!RD || !RD->hasAnyDependentBases())
2141     return nullptr;
2142 
2143   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2144   // is available, suggest inserting 'this->' as a fixit.
2145   SourceLocation Loc = NameInfo.getLoc();
2146   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2147   DB << NameInfo.getName() << RD;
2148 
2149   if (!ThisType.isNull()) {
2150     DB << FixItHint::CreateInsertion(Loc, "this->");
2151     return CXXDependentScopeMemberExpr::Create(
2152         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2153         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2154         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2155   }
2156 
2157   // Synthesize a fake NNS that points to the derived class.  This will
2158   // perform name lookup during template instantiation.
2159   CXXScopeSpec SS;
2160   auto *NNS =
2161       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2162   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2163   return DependentScopeDeclRefExpr::Create(
2164       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2165       TemplateArgs);
2166 }
2167 
2168 ExprResult
2169 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2170                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2171                         bool HasTrailingLParen, bool IsAddressOfOperand,
2172                         CorrectionCandidateCallback *CCC,
2173                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2174   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2175          "cannot be direct & operand and have a trailing lparen");
2176   if (SS.isInvalid())
2177     return ExprError();
2178 
2179   TemplateArgumentListInfo TemplateArgsBuffer;
2180 
2181   // Decompose the UnqualifiedId into the following data.
2182   DeclarationNameInfo NameInfo;
2183   const TemplateArgumentListInfo *TemplateArgs;
2184   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2185 
2186   DeclarationName Name = NameInfo.getName();
2187   IdentifierInfo *II = Name.getAsIdentifierInfo();
2188   SourceLocation NameLoc = NameInfo.getLoc();
2189 
2190   if (II && II->isEditorPlaceholder()) {
2191     // FIXME: When typed placeholders are supported we can create a typed
2192     // placeholder expression node.
2193     return ExprError();
2194   }
2195 
2196   // C++ [temp.dep.expr]p3:
2197   //   An id-expression is type-dependent if it contains:
2198   //     -- an identifier that was declared with a dependent type,
2199   //        (note: handled after lookup)
2200   //     -- a template-id that is dependent,
2201   //        (note: handled in BuildTemplateIdExpr)
2202   //     -- a conversion-function-id that specifies a dependent type,
2203   //     -- a nested-name-specifier that contains a class-name that
2204   //        names a dependent type.
2205   // Determine whether this is a member of an unknown specialization;
2206   // we need to handle these differently.
2207   bool DependentID = false;
2208   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2209       Name.getCXXNameType()->isDependentType()) {
2210     DependentID = true;
2211   } else if (SS.isSet()) {
2212     if (DeclContext *DC = computeDeclContext(SS, false)) {
2213       if (RequireCompleteDeclContext(SS, DC))
2214         return ExprError();
2215     } else {
2216       DependentID = true;
2217     }
2218   }
2219 
2220   if (DependentID)
2221     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2222                                       IsAddressOfOperand, TemplateArgs);
2223 
2224   // Perform the required lookup.
2225   LookupResult R(*this, NameInfo,
2226                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2227                      ? LookupObjCImplicitSelfParam
2228                      : LookupOrdinaryName);
2229   if (TemplateKWLoc.isValid() || TemplateArgs) {
2230     // Lookup the template name again to correctly establish the context in
2231     // which it was found. This is really unfortunate as we already did the
2232     // lookup to determine that it was a template name in the first place. If
2233     // this becomes a performance hit, we can work harder to preserve those
2234     // results until we get here but it's likely not worth it.
2235     bool MemberOfUnknownSpecialization;
2236     AssumedTemplateKind AssumedTemplate;
2237     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2238                            MemberOfUnknownSpecialization, TemplateKWLoc,
2239                            &AssumedTemplate))
2240       return ExprError();
2241 
2242     if (MemberOfUnknownSpecialization ||
2243         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2244       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2245                                         IsAddressOfOperand, TemplateArgs);
2246   } else {
2247     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2248     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2249 
2250     // If the result might be in a dependent base class, this is a dependent
2251     // id-expression.
2252     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2253       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2254                                         IsAddressOfOperand, TemplateArgs);
2255 
2256     // If this reference is in an Objective-C method, then we need to do
2257     // some special Objective-C lookup, too.
2258     if (IvarLookupFollowUp) {
2259       ExprResult E(LookupInObjCMethod(R, S, II, true));
2260       if (E.isInvalid())
2261         return ExprError();
2262 
2263       if (Expr *Ex = E.getAs<Expr>())
2264         return Ex;
2265     }
2266   }
2267 
2268   if (R.isAmbiguous())
2269     return ExprError();
2270 
2271   // This could be an implicitly declared function reference (legal in C90,
2272   // extension in C99, forbidden in C++).
2273   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2274     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2275     if (D) R.addDecl(D);
2276   }
2277 
2278   // Determine whether this name might be a candidate for
2279   // argument-dependent lookup.
2280   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2281 
2282   if (R.empty() && !ADL) {
2283     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2284       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2285                                                    TemplateKWLoc, TemplateArgs))
2286         return E;
2287     }
2288 
2289     // Don't diagnose an empty lookup for inline assembly.
2290     if (IsInlineAsmIdentifier)
2291       return ExprError();
2292 
2293     // If this name wasn't predeclared and if this is not a function
2294     // call, diagnose the problem.
2295     TypoExpr *TE = nullptr;
2296     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2297                                                        : nullptr);
2298     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2299     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2300            "Typo correction callback misconfigured");
2301     if (CCC) {
2302       // Make sure the callback knows what the typo being diagnosed is.
2303       CCC->setTypoName(II);
2304       if (SS.isValid())
2305         CCC->setTypoNNS(SS.getScopeRep());
2306     }
2307     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2308     // a template name, but we happen to have always already looked up the name
2309     // before we get here if it must be a template name.
2310     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2311                             None, &TE)) {
2312       if (TE && KeywordReplacement) {
2313         auto &State = getTypoExprState(TE);
2314         auto BestTC = State.Consumer->getNextCorrection();
2315         if (BestTC.isKeyword()) {
2316           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2317           if (State.DiagHandler)
2318             State.DiagHandler(BestTC);
2319           KeywordReplacement->startToken();
2320           KeywordReplacement->setKind(II->getTokenID());
2321           KeywordReplacement->setIdentifierInfo(II);
2322           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2323           // Clean up the state associated with the TypoExpr, since it has
2324           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2325           clearDelayedTypo(TE);
2326           // Signal that a correction to a keyword was performed by returning a
2327           // valid-but-null ExprResult.
2328           return (Expr*)nullptr;
2329         }
2330         State.Consumer->resetCorrectionStream();
2331       }
2332       return TE ? TE : ExprError();
2333     }
2334 
2335     assert(!R.empty() &&
2336            "DiagnoseEmptyLookup returned false but added no results");
2337 
2338     // If we found an Objective-C instance variable, let
2339     // LookupInObjCMethod build the appropriate expression to
2340     // reference the ivar.
2341     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2342       R.clear();
2343       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2344       // In a hopelessly buggy code, Objective-C instance variable
2345       // lookup fails and no expression will be built to reference it.
2346       if (!E.isInvalid() && !E.get())
2347         return ExprError();
2348       return E;
2349     }
2350   }
2351 
2352   // This is guaranteed from this point on.
2353   assert(!R.empty() || ADL);
2354 
2355   // Check whether this might be a C++ implicit instance member access.
2356   // C++ [class.mfct.non-static]p3:
2357   //   When an id-expression that is not part of a class member access
2358   //   syntax and not used to form a pointer to member is used in the
2359   //   body of a non-static member function of class X, if name lookup
2360   //   resolves the name in the id-expression to a non-static non-type
2361   //   member of some class C, the id-expression is transformed into a
2362   //   class member access expression using (*this) as the
2363   //   postfix-expression to the left of the . operator.
2364   //
2365   // But we don't actually need to do this for '&' operands if R
2366   // resolved to a function or overloaded function set, because the
2367   // expression is ill-formed if it actually works out to be a
2368   // non-static member function:
2369   //
2370   // C++ [expr.ref]p4:
2371   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2372   //   [t]he expression can be used only as the left-hand operand of a
2373   //   member function call.
2374   //
2375   // There are other safeguards against such uses, but it's important
2376   // to get this right here so that we don't end up making a
2377   // spuriously dependent expression if we're inside a dependent
2378   // instance method.
2379   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2380     bool MightBeImplicitMember;
2381     if (!IsAddressOfOperand)
2382       MightBeImplicitMember = true;
2383     else if (!SS.isEmpty())
2384       MightBeImplicitMember = false;
2385     else if (R.isOverloadedResult())
2386       MightBeImplicitMember = false;
2387     else if (R.isUnresolvableResult())
2388       MightBeImplicitMember = true;
2389     else
2390       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2391                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2392                               isa<MSPropertyDecl>(R.getFoundDecl());
2393 
2394     if (MightBeImplicitMember)
2395       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2396                                              R, TemplateArgs, S);
2397   }
2398 
2399   if (TemplateArgs || TemplateKWLoc.isValid()) {
2400 
2401     // In C++1y, if this is a variable template id, then check it
2402     // in BuildTemplateIdExpr().
2403     // The single lookup result must be a variable template declaration.
2404     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2405         Id.TemplateId->Kind == TNK_Var_template) {
2406       assert(R.getAsSingle<VarTemplateDecl>() &&
2407              "There should only be one declaration found.");
2408     }
2409 
2410     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2411   }
2412 
2413   return BuildDeclarationNameExpr(SS, R, ADL);
2414 }
2415 
2416 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2417 /// declaration name, generally during template instantiation.
2418 /// There's a large number of things which don't need to be done along
2419 /// this path.
2420 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2421     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2422     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2423   DeclContext *DC = computeDeclContext(SS, false);
2424   if (!DC)
2425     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2426                                      NameInfo, /*TemplateArgs=*/nullptr);
2427 
2428   if (RequireCompleteDeclContext(SS, DC))
2429     return ExprError();
2430 
2431   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2432   LookupQualifiedName(R, DC);
2433 
2434   if (R.isAmbiguous())
2435     return ExprError();
2436 
2437   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2438     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2439                                      NameInfo, /*TemplateArgs=*/nullptr);
2440 
2441   if (R.empty()) {
2442     Diag(NameInfo.getLoc(), diag::err_no_member)
2443       << NameInfo.getName() << DC << SS.getRange();
2444     return ExprError();
2445   }
2446 
2447   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2448     // Diagnose a missing typename if this resolved unambiguously to a type in
2449     // a dependent context.  If we can recover with a type, downgrade this to
2450     // a warning in Microsoft compatibility mode.
2451     unsigned DiagID = diag::err_typename_missing;
2452     if (RecoveryTSI && getLangOpts().MSVCCompat)
2453       DiagID = diag::ext_typename_missing;
2454     SourceLocation Loc = SS.getBeginLoc();
2455     auto D = Diag(Loc, DiagID);
2456     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2457       << SourceRange(Loc, NameInfo.getEndLoc());
2458 
2459     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2460     // context.
2461     if (!RecoveryTSI)
2462       return ExprError();
2463 
2464     // Only issue the fixit if we're prepared to recover.
2465     D << FixItHint::CreateInsertion(Loc, "typename ");
2466 
2467     // Recover by pretending this was an elaborated type.
2468     QualType Ty = Context.getTypeDeclType(TD);
2469     TypeLocBuilder TLB;
2470     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2471 
2472     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2473     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2474     QTL.setElaboratedKeywordLoc(SourceLocation());
2475     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2476 
2477     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2478 
2479     return ExprEmpty();
2480   }
2481 
2482   // Defend against this resolving to an implicit member access. We usually
2483   // won't get here if this might be a legitimate a class member (we end up in
2484   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2485   // a pointer-to-member or in an unevaluated context in C++11.
2486   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2487     return BuildPossibleImplicitMemberExpr(SS,
2488                                            /*TemplateKWLoc=*/SourceLocation(),
2489                                            R, /*TemplateArgs=*/nullptr, S);
2490 
2491   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2492 }
2493 
2494 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2495 /// detected that we're currently inside an ObjC method.  Perform some
2496 /// additional lookup.
2497 ///
2498 /// Ideally, most of this would be done by lookup, but there's
2499 /// actually quite a lot of extra work involved.
2500 ///
2501 /// Returns a null sentinel to indicate trivial success.
2502 ExprResult
2503 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2504                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2505   SourceLocation Loc = Lookup.getNameLoc();
2506   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2507 
2508   // Check for error condition which is already reported.
2509   if (!CurMethod)
2510     return ExprError();
2511 
2512   // There are two cases to handle here.  1) scoped lookup could have failed,
2513   // in which case we should look for an ivar.  2) scoped lookup could have
2514   // found a decl, but that decl is outside the current instance method (i.e.
2515   // a global variable).  In these two cases, we do a lookup for an ivar with
2516   // this name, if the lookup sucedes, we replace it our current decl.
2517 
2518   // If we're in a class method, we don't normally want to look for
2519   // ivars.  But if we don't find anything else, and there's an
2520   // ivar, that's an error.
2521   bool IsClassMethod = CurMethod->isClassMethod();
2522 
2523   bool LookForIvars;
2524   if (Lookup.empty())
2525     LookForIvars = true;
2526   else if (IsClassMethod)
2527     LookForIvars = false;
2528   else
2529     LookForIvars = (Lookup.isSingleResult() &&
2530                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2531   ObjCInterfaceDecl *IFace = nullptr;
2532   if (LookForIvars) {
2533     IFace = CurMethod->getClassInterface();
2534     ObjCInterfaceDecl *ClassDeclared;
2535     ObjCIvarDecl *IV = nullptr;
2536     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2537       // Diagnose using an ivar in a class method.
2538       if (IsClassMethod)
2539         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2540                          << IV->getDeclName());
2541 
2542       // If we're referencing an invalid decl, just return this as a silent
2543       // error node.  The error diagnostic was already emitted on the decl.
2544       if (IV->isInvalidDecl())
2545         return ExprError();
2546 
2547       // Check if referencing a field with __attribute__((deprecated)).
2548       if (DiagnoseUseOfDecl(IV, Loc))
2549         return ExprError();
2550 
2551       // Diagnose the use of an ivar outside of the declaring class.
2552       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2553           !declaresSameEntity(ClassDeclared, IFace) &&
2554           !getLangOpts().DebuggerSupport)
2555         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2556 
2557       // FIXME: This should use a new expr for a direct reference, don't
2558       // turn this into Self->ivar, just return a BareIVarExpr or something.
2559       IdentifierInfo &II = Context.Idents.get("self");
2560       UnqualifiedId SelfName;
2561       SelfName.setIdentifier(&II, SourceLocation());
2562       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2563       CXXScopeSpec SelfScopeSpec;
2564       SourceLocation TemplateKWLoc;
2565       ExprResult SelfExpr =
2566           ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2567                             /*HasTrailingLParen=*/false,
2568                             /*IsAddressOfOperand=*/false);
2569       if (SelfExpr.isInvalid())
2570         return ExprError();
2571 
2572       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2573       if (SelfExpr.isInvalid())
2574         return ExprError();
2575 
2576       MarkAnyDeclReferenced(Loc, IV, true);
2577 
2578       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2579       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2580           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2581         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2582 
2583       ObjCIvarRefExpr *Result = new (Context)
2584           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2585                           IV->getLocation(), SelfExpr.get(), true, true);
2586 
2587       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2588         if (!isUnevaluatedContext() &&
2589             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2590           getCurFunction()->recordUseOfWeak(Result);
2591       }
2592       if (getLangOpts().ObjCAutoRefCount)
2593         if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2594           ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2595 
2596       return Result;
2597     }
2598   } else if (CurMethod->isInstanceMethod()) {
2599     // We should warn if a local variable hides an ivar.
2600     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2601       ObjCInterfaceDecl *ClassDeclared;
2602       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2603         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2604             declaresSameEntity(IFace, ClassDeclared))
2605           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2606       }
2607     }
2608   } else if (Lookup.isSingleResult() &&
2609              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2610     // If accessing a stand-alone ivar in a class method, this is an error.
2611     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2612       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2613                        << IV->getDeclName());
2614   }
2615 
2616   if (Lookup.empty() && II && AllowBuiltinCreation) {
2617     // FIXME. Consolidate this with similar code in LookupName.
2618     if (unsigned BuiltinID = II->getBuiltinID()) {
2619       if (!(getLangOpts().CPlusPlus &&
2620             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2621         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2622                                            S, Lookup.isForRedeclaration(),
2623                                            Lookup.getNameLoc());
2624         if (D) Lookup.addDecl(D);
2625       }
2626     }
2627   }
2628   // Sentinel value saying that we didn't do anything special.
2629   return ExprResult((Expr *)nullptr);
2630 }
2631 
2632 /// Cast a base object to a member's actual type.
2633 ///
2634 /// Logically this happens in three phases:
2635 ///
2636 /// * First we cast from the base type to the naming class.
2637 ///   The naming class is the class into which we were looking
2638 ///   when we found the member;  it's the qualifier type if a
2639 ///   qualifier was provided, and otherwise it's the base type.
2640 ///
2641 /// * Next we cast from the naming class to the declaring class.
2642 ///   If the member we found was brought into a class's scope by
2643 ///   a using declaration, this is that class;  otherwise it's
2644 ///   the class declaring the member.
2645 ///
2646 /// * Finally we cast from the declaring class to the "true"
2647 ///   declaring class of the member.  This conversion does not
2648 ///   obey access control.
2649 ExprResult
2650 Sema::PerformObjectMemberConversion(Expr *From,
2651                                     NestedNameSpecifier *Qualifier,
2652                                     NamedDecl *FoundDecl,
2653                                     NamedDecl *Member) {
2654   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2655   if (!RD)
2656     return From;
2657 
2658   QualType DestRecordType;
2659   QualType DestType;
2660   QualType FromRecordType;
2661   QualType FromType = From->getType();
2662   bool PointerConversions = false;
2663   if (isa<FieldDecl>(Member)) {
2664     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2665     auto FromPtrType = FromType->getAs<PointerType>();
2666     DestRecordType = Context.getAddrSpaceQualType(
2667         DestRecordType, FromPtrType
2668                             ? FromType->getPointeeType().getAddressSpace()
2669                             : FromType.getAddressSpace());
2670 
2671     if (FromPtrType) {
2672       DestType = Context.getPointerType(DestRecordType);
2673       FromRecordType = FromPtrType->getPointeeType();
2674       PointerConversions = true;
2675     } else {
2676       DestType = DestRecordType;
2677       FromRecordType = FromType;
2678     }
2679   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2680     if (Method->isStatic())
2681       return From;
2682 
2683     DestType = Method->getThisType();
2684     DestRecordType = DestType->getPointeeType();
2685 
2686     if (FromType->getAs<PointerType>()) {
2687       FromRecordType = FromType->getPointeeType();
2688       PointerConversions = true;
2689     } else {
2690       FromRecordType = FromType;
2691       DestType = DestRecordType;
2692     }
2693   } else {
2694     // No conversion necessary.
2695     return From;
2696   }
2697 
2698   if (DestType->isDependentType() || FromType->isDependentType())
2699     return From;
2700 
2701   // If the unqualified types are the same, no conversion is necessary.
2702   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2703     return From;
2704 
2705   SourceRange FromRange = From->getSourceRange();
2706   SourceLocation FromLoc = FromRange.getBegin();
2707 
2708   ExprValueKind VK = From->getValueKind();
2709 
2710   // C++ [class.member.lookup]p8:
2711   //   [...] Ambiguities can often be resolved by qualifying a name with its
2712   //   class name.
2713   //
2714   // If the member was a qualified name and the qualified referred to a
2715   // specific base subobject type, we'll cast to that intermediate type
2716   // first and then to the object in which the member is declared. That allows
2717   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2718   //
2719   //   class Base { public: int x; };
2720   //   class Derived1 : public Base { };
2721   //   class Derived2 : public Base { };
2722   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2723   //
2724   //   void VeryDerived::f() {
2725   //     x = 17; // error: ambiguous base subobjects
2726   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2727   //   }
2728   if (Qualifier && Qualifier->getAsType()) {
2729     QualType QType = QualType(Qualifier->getAsType(), 0);
2730     assert(QType->isRecordType() && "lookup done with non-record type");
2731 
2732     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2733 
2734     // In C++98, the qualifier type doesn't actually have to be a base
2735     // type of the object type, in which case we just ignore it.
2736     // Otherwise build the appropriate casts.
2737     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2738       CXXCastPath BasePath;
2739       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2740                                        FromLoc, FromRange, &BasePath))
2741         return ExprError();
2742 
2743       if (PointerConversions)
2744         QType = Context.getPointerType(QType);
2745       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2746                                VK, &BasePath).get();
2747 
2748       FromType = QType;
2749       FromRecordType = QRecordType;
2750 
2751       // If the qualifier type was the same as the destination type,
2752       // we're done.
2753       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2754         return From;
2755     }
2756   }
2757 
2758   bool IgnoreAccess = false;
2759 
2760   // If we actually found the member through a using declaration, cast
2761   // down to the using declaration's type.
2762   //
2763   // Pointer equality is fine here because only one declaration of a
2764   // class ever has member declarations.
2765   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2766     assert(isa<UsingShadowDecl>(FoundDecl));
2767     QualType URecordType = Context.getTypeDeclType(
2768                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2769 
2770     // We only need to do this if the naming-class to declaring-class
2771     // conversion is non-trivial.
2772     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2773       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2774       CXXCastPath BasePath;
2775       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2776                                        FromLoc, FromRange, &BasePath))
2777         return ExprError();
2778 
2779       QualType UType = URecordType;
2780       if (PointerConversions)
2781         UType = Context.getPointerType(UType);
2782       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2783                                VK, &BasePath).get();
2784       FromType = UType;
2785       FromRecordType = URecordType;
2786     }
2787 
2788     // We don't do access control for the conversion from the
2789     // declaring class to the true declaring class.
2790     IgnoreAccess = true;
2791   }
2792 
2793   CXXCastPath BasePath;
2794   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2795                                    FromLoc, FromRange, &BasePath,
2796                                    IgnoreAccess))
2797     return ExprError();
2798 
2799   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2800                            VK, &BasePath);
2801 }
2802 
2803 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2804                                       const LookupResult &R,
2805                                       bool HasTrailingLParen) {
2806   // Only when used directly as the postfix-expression of a call.
2807   if (!HasTrailingLParen)
2808     return false;
2809 
2810   // Never if a scope specifier was provided.
2811   if (SS.isSet())
2812     return false;
2813 
2814   // Only in C++ or ObjC++.
2815   if (!getLangOpts().CPlusPlus)
2816     return false;
2817 
2818   // Turn off ADL when we find certain kinds of declarations during
2819   // normal lookup:
2820   for (NamedDecl *D : R) {
2821     // C++0x [basic.lookup.argdep]p3:
2822     //     -- a declaration of a class member
2823     // Since using decls preserve this property, we check this on the
2824     // original decl.
2825     if (D->isCXXClassMember())
2826       return false;
2827 
2828     // C++0x [basic.lookup.argdep]p3:
2829     //     -- a block-scope function declaration that is not a
2830     //        using-declaration
2831     // NOTE: we also trigger this for function templates (in fact, we
2832     // don't check the decl type at all, since all other decl types
2833     // turn off ADL anyway).
2834     if (isa<UsingShadowDecl>(D))
2835       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2836     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2837       return false;
2838 
2839     // C++0x [basic.lookup.argdep]p3:
2840     //     -- a declaration that is neither a function or a function
2841     //        template
2842     // And also for builtin functions.
2843     if (isa<FunctionDecl>(D)) {
2844       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2845 
2846       // But also builtin functions.
2847       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2848         return false;
2849     } else if (!isa<FunctionTemplateDecl>(D))
2850       return false;
2851   }
2852 
2853   return true;
2854 }
2855 
2856 
2857 /// Diagnoses obvious problems with the use of the given declaration
2858 /// as an expression.  This is only actually called for lookups that
2859 /// were not overloaded, and it doesn't promise that the declaration
2860 /// will in fact be used.
2861 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2862   if (D->isInvalidDecl())
2863     return true;
2864 
2865   if (isa<TypedefNameDecl>(D)) {
2866     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2867     return true;
2868   }
2869 
2870   if (isa<ObjCInterfaceDecl>(D)) {
2871     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2872     return true;
2873   }
2874 
2875   if (isa<NamespaceDecl>(D)) {
2876     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2877     return true;
2878   }
2879 
2880   return false;
2881 }
2882 
2883 // Certain multiversion types should be treated as overloaded even when there is
2884 // only one result.
2885 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2886   assert(R.isSingleResult() && "Expected only a single result");
2887   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2888   return FD &&
2889          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2890 }
2891 
2892 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2893                                           LookupResult &R, bool NeedsADL,
2894                                           bool AcceptInvalidDecl) {
2895   // If this is a single, fully-resolved result and we don't need ADL,
2896   // just build an ordinary singleton decl ref.
2897   if (!NeedsADL && R.isSingleResult() &&
2898       !R.getAsSingle<FunctionTemplateDecl>() &&
2899       !ShouldLookupResultBeMultiVersionOverload(R))
2900     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2901                                     R.getRepresentativeDecl(), nullptr,
2902                                     AcceptInvalidDecl);
2903 
2904   // We only need to check the declaration if there's exactly one
2905   // result, because in the overloaded case the results can only be
2906   // functions and function templates.
2907   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2908       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2909     return ExprError();
2910 
2911   // Otherwise, just build an unresolved lookup expression.  Suppress
2912   // any lookup-related diagnostics; we'll hash these out later, when
2913   // we've picked a target.
2914   R.suppressDiagnostics();
2915 
2916   UnresolvedLookupExpr *ULE
2917     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2918                                    SS.getWithLocInContext(Context),
2919                                    R.getLookupNameInfo(),
2920                                    NeedsADL, R.isOverloadedResult(),
2921                                    R.begin(), R.end());
2922 
2923   return ULE;
2924 }
2925 
2926 static void
2927 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2928                                    ValueDecl *var, DeclContext *DC);
2929 
2930 /// Complete semantic analysis for a reference to the given declaration.
2931 ExprResult Sema::BuildDeclarationNameExpr(
2932     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2933     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2934     bool AcceptInvalidDecl) {
2935   assert(D && "Cannot refer to a NULL declaration");
2936   assert(!isa<FunctionTemplateDecl>(D) &&
2937          "Cannot refer unambiguously to a function template");
2938 
2939   SourceLocation Loc = NameInfo.getLoc();
2940   if (CheckDeclInExpr(*this, Loc, D))
2941     return ExprError();
2942 
2943   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2944     // Specifically diagnose references to class templates that are missing
2945     // a template argument list.
2946     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2947     return ExprError();
2948   }
2949 
2950   // Make sure that we're referring to a value.
2951   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2952   if (!VD) {
2953     Diag(Loc, diag::err_ref_non_value)
2954       << D << SS.getRange();
2955     Diag(D->getLocation(), diag::note_declared_at);
2956     return ExprError();
2957   }
2958 
2959   // Check whether this declaration can be used. Note that we suppress
2960   // this check when we're going to perform argument-dependent lookup
2961   // on this function name, because this might not be the function
2962   // that overload resolution actually selects.
2963   if (DiagnoseUseOfDecl(VD, Loc))
2964     return ExprError();
2965 
2966   // Only create DeclRefExpr's for valid Decl's.
2967   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2968     return ExprError();
2969 
2970   // Handle members of anonymous structs and unions.  If we got here,
2971   // and the reference is to a class member indirect field, then this
2972   // must be the subject of a pointer-to-member expression.
2973   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2974     if (!indirectField->isCXXClassMember())
2975       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2976                                                       indirectField);
2977 
2978   {
2979     QualType type = VD->getType();
2980     if (type.isNull())
2981       return ExprError();
2982     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2983       // C++ [except.spec]p17:
2984       //   An exception-specification is considered to be needed when:
2985       //   - in an expression, the function is the unique lookup result or
2986       //     the selected member of a set of overloaded functions.
2987       ResolveExceptionSpec(Loc, FPT);
2988       type = VD->getType();
2989     }
2990     ExprValueKind valueKind = VK_RValue;
2991 
2992     switch (D->getKind()) {
2993     // Ignore all the non-ValueDecl kinds.
2994 #define ABSTRACT_DECL(kind)
2995 #define VALUE(type, base)
2996 #define DECL(type, base) \
2997     case Decl::type:
2998 #include "clang/AST/DeclNodes.inc"
2999       llvm_unreachable("invalid value decl kind");
3000 
3001     // These shouldn't make it here.
3002     case Decl::ObjCAtDefsField:
3003       llvm_unreachable("forming non-member reference to ivar?");
3004 
3005     // Enum constants are always r-values and never references.
3006     // Unresolved using declarations are dependent.
3007     case Decl::EnumConstant:
3008     case Decl::UnresolvedUsingValue:
3009     case Decl::OMPDeclareReduction:
3010     case Decl::OMPDeclareMapper:
3011       valueKind = VK_RValue;
3012       break;
3013 
3014     // Fields and indirect fields that got here must be for
3015     // pointer-to-member expressions; we just call them l-values for
3016     // internal consistency, because this subexpression doesn't really
3017     // exist in the high-level semantics.
3018     case Decl::Field:
3019     case Decl::IndirectField:
3020     case Decl::ObjCIvar:
3021       assert(getLangOpts().CPlusPlus &&
3022              "building reference to field in C?");
3023 
3024       // These can't have reference type in well-formed programs, but
3025       // for internal consistency we do this anyway.
3026       type = type.getNonReferenceType();
3027       valueKind = VK_LValue;
3028       break;
3029 
3030     // Non-type template parameters are either l-values or r-values
3031     // depending on the type.
3032     case Decl::NonTypeTemplateParm: {
3033       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3034         type = reftype->getPointeeType();
3035         valueKind = VK_LValue; // even if the parameter is an r-value reference
3036         break;
3037       }
3038 
3039       // For non-references, we need to strip qualifiers just in case
3040       // the template parameter was declared as 'const int' or whatever.
3041       valueKind = VK_RValue;
3042       type = type.getUnqualifiedType();
3043       break;
3044     }
3045 
3046     case Decl::Var:
3047     case Decl::VarTemplateSpecialization:
3048     case Decl::VarTemplatePartialSpecialization:
3049     case Decl::Decomposition:
3050     case Decl::OMPCapturedExpr:
3051       // In C, "extern void blah;" is valid and is an r-value.
3052       if (!getLangOpts().CPlusPlus &&
3053           !type.hasQualifiers() &&
3054           type->isVoidType()) {
3055         valueKind = VK_RValue;
3056         break;
3057       }
3058       LLVM_FALLTHROUGH;
3059 
3060     case Decl::ImplicitParam:
3061     case Decl::ParmVar: {
3062       // These are always l-values.
3063       valueKind = VK_LValue;
3064       type = type.getNonReferenceType();
3065 
3066       // FIXME: Does the addition of const really only apply in
3067       // potentially-evaluated contexts? Since the variable isn't actually
3068       // captured in an unevaluated context, it seems that the answer is no.
3069       if (!isUnevaluatedContext()) {
3070         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3071         if (!CapturedType.isNull())
3072           type = CapturedType;
3073       }
3074 
3075       break;
3076     }
3077 
3078     case Decl::Binding: {
3079       // These are always lvalues.
3080       valueKind = VK_LValue;
3081       type = type.getNonReferenceType();
3082       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3083       // decides how that's supposed to work.
3084       auto *BD = cast<BindingDecl>(VD);
3085       if (BD->getDeclContext() != CurContext) {
3086         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3087         if (DD && DD->hasLocalStorage())
3088           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3089       }
3090       break;
3091     }
3092 
3093     case Decl::Function: {
3094       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3095         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3096           type = Context.BuiltinFnTy;
3097           valueKind = VK_RValue;
3098           break;
3099         }
3100       }
3101 
3102       const FunctionType *fty = type->castAs<FunctionType>();
3103 
3104       // If we're referring to a function with an __unknown_anytype
3105       // result type, make the entire expression __unknown_anytype.
3106       if (fty->getReturnType() == Context.UnknownAnyTy) {
3107         type = Context.UnknownAnyTy;
3108         valueKind = VK_RValue;
3109         break;
3110       }
3111 
3112       // Functions are l-values in C++.
3113       if (getLangOpts().CPlusPlus) {
3114         valueKind = VK_LValue;
3115         break;
3116       }
3117 
3118       // C99 DR 316 says that, if a function type comes from a
3119       // function definition (without a prototype), that type is only
3120       // used for checking compatibility. Therefore, when referencing
3121       // the function, we pretend that we don't have the full function
3122       // type.
3123       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3124           isa<FunctionProtoType>(fty))
3125         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3126                                               fty->getExtInfo());
3127 
3128       // Functions are r-values in C.
3129       valueKind = VK_RValue;
3130       break;
3131     }
3132 
3133     case Decl::CXXDeductionGuide:
3134       llvm_unreachable("building reference to deduction guide");
3135 
3136     case Decl::MSProperty:
3137       valueKind = VK_LValue;
3138       break;
3139 
3140     case Decl::CXXMethod:
3141       // If we're referring to a method with an __unknown_anytype
3142       // result type, make the entire expression __unknown_anytype.
3143       // This should only be possible with a type written directly.
3144       if (const FunctionProtoType *proto
3145             = dyn_cast<FunctionProtoType>(VD->getType()))
3146         if (proto->getReturnType() == Context.UnknownAnyTy) {
3147           type = Context.UnknownAnyTy;
3148           valueKind = VK_RValue;
3149           break;
3150         }
3151 
3152       // C++ methods are l-values if static, r-values if non-static.
3153       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3154         valueKind = VK_LValue;
3155         break;
3156       }
3157       LLVM_FALLTHROUGH;
3158 
3159     case Decl::CXXConversion:
3160     case Decl::CXXDestructor:
3161     case Decl::CXXConstructor:
3162       valueKind = VK_RValue;
3163       break;
3164     }
3165 
3166     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3167                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3168                             TemplateArgs);
3169   }
3170 }
3171 
3172 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3173                                     SmallString<32> &Target) {
3174   Target.resize(CharByteWidth * (Source.size() + 1));
3175   char *ResultPtr = &Target[0];
3176   const llvm::UTF8 *ErrorPtr;
3177   bool success =
3178       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3179   (void)success;
3180   assert(success);
3181   Target.resize(ResultPtr - &Target[0]);
3182 }
3183 
3184 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3185                                      PredefinedExpr::IdentKind IK) {
3186   // Pick the current block, lambda, captured statement or function.
3187   Decl *currentDecl = nullptr;
3188   if (const BlockScopeInfo *BSI = getCurBlock())
3189     currentDecl = BSI->TheDecl;
3190   else if (const LambdaScopeInfo *LSI = getCurLambda())
3191     currentDecl = LSI->CallOperator;
3192   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3193     currentDecl = CSI->TheCapturedDecl;
3194   else
3195     currentDecl = getCurFunctionOrMethodDecl();
3196 
3197   if (!currentDecl) {
3198     Diag(Loc, diag::ext_predef_outside_function);
3199     currentDecl = Context.getTranslationUnitDecl();
3200   }
3201 
3202   QualType ResTy;
3203   StringLiteral *SL = nullptr;
3204   if (cast<DeclContext>(currentDecl)->isDependentContext())
3205     ResTy = Context.DependentTy;
3206   else {
3207     // Pre-defined identifiers are of type char[x], where x is the length of
3208     // the string.
3209     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3210     unsigned Length = Str.length();
3211 
3212     llvm::APInt LengthI(32, Length + 1);
3213     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3214       ResTy =
3215           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3216       SmallString<32> RawChars;
3217       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3218                               Str, RawChars);
3219       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3220                                            /*IndexTypeQuals*/ 0);
3221       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3222                                  /*Pascal*/ false, ResTy, Loc);
3223     } else {
3224       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3225       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3226                                            /*IndexTypeQuals*/ 0);
3227       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3228                                  /*Pascal*/ false, ResTy, Loc);
3229     }
3230   }
3231 
3232   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3233 }
3234 
3235 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3236   PredefinedExpr::IdentKind IK;
3237 
3238   switch (Kind) {
3239   default: llvm_unreachable("Unknown simple primary expr!");
3240   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3241   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3242   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3243   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3244   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3245   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3246   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3247   }
3248 
3249   return BuildPredefinedExpr(Loc, IK);
3250 }
3251 
3252 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3253   SmallString<16> CharBuffer;
3254   bool Invalid = false;
3255   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3256   if (Invalid)
3257     return ExprError();
3258 
3259   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3260                             PP, Tok.getKind());
3261   if (Literal.hadError())
3262     return ExprError();
3263 
3264   QualType Ty;
3265   if (Literal.isWide())
3266     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3267   else if (Literal.isUTF8() && getLangOpts().Char8)
3268     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3269   else if (Literal.isUTF16())
3270     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3271   else if (Literal.isUTF32())
3272     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3273   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3274     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3275   else
3276     Ty = Context.CharTy;  // 'x' -> char in C++
3277 
3278   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3279   if (Literal.isWide())
3280     Kind = CharacterLiteral::Wide;
3281   else if (Literal.isUTF16())
3282     Kind = CharacterLiteral::UTF16;
3283   else if (Literal.isUTF32())
3284     Kind = CharacterLiteral::UTF32;
3285   else if (Literal.isUTF8())
3286     Kind = CharacterLiteral::UTF8;
3287 
3288   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3289                                              Tok.getLocation());
3290 
3291   if (Literal.getUDSuffix().empty())
3292     return Lit;
3293 
3294   // We're building a user-defined literal.
3295   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3296   SourceLocation UDSuffixLoc =
3297     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3298 
3299   // Make sure we're allowed user-defined literals here.
3300   if (!UDLScope)
3301     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3302 
3303   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3304   //   operator "" X (ch)
3305   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3306                                         Lit, Tok.getLocation());
3307 }
3308 
3309 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3310   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3311   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3312                                 Context.IntTy, Loc);
3313 }
3314 
3315 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3316                                   QualType Ty, SourceLocation Loc) {
3317   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3318 
3319   using llvm::APFloat;
3320   APFloat Val(Format);
3321 
3322   APFloat::opStatus result = Literal.GetFloatValue(Val);
3323 
3324   // Overflow is always an error, but underflow is only an error if
3325   // we underflowed to zero (APFloat reports denormals as underflow).
3326   if ((result & APFloat::opOverflow) ||
3327       ((result & APFloat::opUnderflow) && Val.isZero())) {
3328     unsigned diagnostic;
3329     SmallString<20> buffer;
3330     if (result & APFloat::opOverflow) {
3331       diagnostic = diag::warn_float_overflow;
3332       APFloat::getLargest(Format).toString(buffer);
3333     } else {
3334       diagnostic = diag::warn_float_underflow;
3335       APFloat::getSmallest(Format).toString(buffer);
3336     }
3337 
3338     S.Diag(Loc, diagnostic)
3339       << Ty
3340       << StringRef(buffer.data(), buffer.size());
3341   }
3342 
3343   bool isExact = (result == APFloat::opOK);
3344   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3345 }
3346 
3347 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3348   assert(E && "Invalid expression");
3349 
3350   if (E->isValueDependent())
3351     return false;
3352 
3353   QualType QT = E->getType();
3354   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3355     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3356     return true;
3357   }
3358 
3359   llvm::APSInt ValueAPS;
3360   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3361 
3362   if (R.isInvalid())
3363     return true;
3364 
3365   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3366   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3367     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3368         << ValueAPS.toString(10) << ValueIsPositive;
3369     return true;
3370   }
3371 
3372   return false;
3373 }
3374 
3375 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3376   // Fast path for a single digit (which is quite common).  A single digit
3377   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3378   if (Tok.getLength() == 1) {
3379     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3380     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3381   }
3382 
3383   SmallString<128> SpellingBuffer;
3384   // NumericLiteralParser wants to overread by one character.  Add padding to
3385   // the buffer in case the token is copied to the buffer.  If getSpelling()
3386   // returns a StringRef to the memory buffer, it should have a null char at
3387   // the EOF, so it is also safe.
3388   SpellingBuffer.resize(Tok.getLength() + 1);
3389 
3390   // Get the spelling of the token, which eliminates trigraphs, etc.
3391   bool Invalid = false;
3392   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3393   if (Invalid)
3394     return ExprError();
3395 
3396   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3397   if (Literal.hadError)
3398     return ExprError();
3399 
3400   if (Literal.hasUDSuffix()) {
3401     // We're building a user-defined literal.
3402     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3403     SourceLocation UDSuffixLoc =
3404       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3405 
3406     // Make sure we're allowed user-defined literals here.
3407     if (!UDLScope)
3408       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3409 
3410     QualType CookedTy;
3411     if (Literal.isFloatingLiteral()) {
3412       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3413       // long double, the literal is treated as a call of the form
3414       //   operator "" X (f L)
3415       CookedTy = Context.LongDoubleTy;
3416     } else {
3417       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3418       // unsigned long long, the literal is treated as a call of the form
3419       //   operator "" X (n ULL)
3420       CookedTy = Context.UnsignedLongLongTy;
3421     }
3422 
3423     DeclarationName OpName =
3424       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3425     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3426     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3427 
3428     SourceLocation TokLoc = Tok.getLocation();
3429 
3430     // Perform literal operator lookup to determine if we're building a raw
3431     // literal or a cooked one.
3432     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3433     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3434                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3435                                   /*AllowStringTemplate*/ false,
3436                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3437     case LOLR_ErrorNoDiagnostic:
3438       // Lookup failure for imaginary constants isn't fatal, there's still the
3439       // GNU extension producing _Complex types.
3440       break;
3441     case LOLR_Error:
3442       return ExprError();
3443     case LOLR_Cooked: {
3444       Expr *Lit;
3445       if (Literal.isFloatingLiteral()) {
3446         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3447       } else {
3448         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3449         if (Literal.GetIntegerValue(ResultVal))
3450           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3451               << /* Unsigned */ 1;
3452         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3453                                      Tok.getLocation());
3454       }
3455       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3456     }
3457 
3458     case LOLR_Raw: {
3459       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3460       // literal is treated as a call of the form
3461       //   operator "" X ("n")
3462       unsigned Length = Literal.getUDSuffixOffset();
3463       QualType StrTy = Context.getConstantArrayType(
3464           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3465           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3466       Expr *Lit = StringLiteral::Create(
3467           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3468           /*Pascal*/false, StrTy, &TokLoc, 1);
3469       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3470     }
3471 
3472     case LOLR_Template: {
3473       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3474       // template), L is treated as a call fo the form
3475       //   operator "" X <'c1', 'c2', ... 'ck'>()
3476       // where n is the source character sequence c1 c2 ... ck.
3477       TemplateArgumentListInfo ExplicitArgs;
3478       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3479       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3480       llvm::APSInt Value(CharBits, CharIsUnsigned);
3481       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3482         Value = TokSpelling[I];
3483         TemplateArgument Arg(Context, Value, Context.CharTy);
3484         TemplateArgumentLocInfo ArgInfo;
3485         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3486       }
3487       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3488                                       &ExplicitArgs);
3489     }
3490     case LOLR_StringTemplate:
3491       llvm_unreachable("unexpected literal operator lookup result");
3492     }
3493   }
3494 
3495   Expr *Res;
3496 
3497   if (Literal.isFixedPointLiteral()) {
3498     QualType Ty;
3499 
3500     if (Literal.isAccum) {
3501       if (Literal.isHalf) {
3502         Ty = Context.ShortAccumTy;
3503       } else if (Literal.isLong) {
3504         Ty = Context.LongAccumTy;
3505       } else {
3506         Ty = Context.AccumTy;
3507       }
3508     } else if (Literal.isFract) {
3509       if (Literal.isHalf) {
3510         Ty = Context.ShortFractTy;
3511       } else if (Literal.isLong) {
3512         Ty = Context.LongFractTy;
3513       } else {
3514         Ty = Context.FractTy;
3515       }
3516     }
3517 
3518     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3519 
3520     bool isSigned = !Literal.isUnsigned;
3521     unsigned scale = Context.getFixedPointScale(Ty);
3522     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3523 
3524     llvm::APInt Val(bit_width, 0, isSigned);
3525     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3526     bool ValIsZero = Val.isNullValue() && !Overflowed;
3527 
3528     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3529     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3530       // Clause 6.4.4 - The value of a constant shall be in the range of
3531       // representable values for its type, with exception for constants of a
3532       // fract type with a value of exactly 1; such a constant shall denote
3533       // the maximal value for the type.
3534       --Val;
3535     else if (Val.ugt(MaxVal) || Overflowed)
3536       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3537 
3538     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3539                                               Tok.getLocation(), scale);
3540   } else if (Literal.isFloatingLiteral()) {
3541     QualType Ty;
3542     if (Literal.isHalf){
3543       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3544         Ty = Context.HalfTy;
3545       else {
3546         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3547         return ExprError();
3548       }
3549     } else if (Literal.isFloat)
3550       Ty = Context.FloatTy;
3551     else if (Literal.isLong)
3552       Ty = Context.LongDoubleTy;
3553     else if (Literal.isFloat16)
3554       Ty = Context.Float16Ty;
3555     else if (Literal.isFloat128)
3556       Ty = Context.Float128Ty;
3557     else
3558       Ty = Context.DoubleTy;
3559 
3560     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3561 
3562     if (Ty == Context.DoubleTy) {
3563       if (getLangOpts().SinglePrecisionConstants) {
3564         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3565         if (BTy->getKind() != BuiltinType::Float) {
3566           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3567         }
3568       } else if (getLangOpts().OpenCL &&
3569                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3570         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3571         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3572         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3573       }
3574     }
3575   } else if (!Literal.isIntegerLiteral()) {
3576     return ExprError();
3577   } else {
3578     QualType Ty;
3579 
3580     // 'long long' is a C99 or C++11 feature.
3581     if (!getLangOpts().C99 && Literal.isLongLong) {
3582       if (getLangOpts().CPlusPlus)
3583         Diag(Tok.getLocation(),
3584              getLangOpts().CPlusPlus11 ?
3585              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3586       else
3587         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3588     }
3589 
3590     // Get the value in the widest-possible width.
3591     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3592     llvm::APInt ResultVal(MaxWidth, 0);
3593 
3594     if (Literal.GetIntegerValue(ResultVal)) {
3595       // If this value didn't fit into uintmax_t, error and force to ull.
3596       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3597           << /* Unsigned */ 1;
3598       Ty = Context.UnsignedLongLongTy;
3599       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3600              "long long is not intmax_t?");
3601     } else {
3602       // If this value fits into a ULL, try to figure out what else it fits into
3603       // according to the rules of C99 6.4.4.1p5.
3604 
3605       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3606       // be an unsigned int.
3607       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3608 
3609       // Check from smallest to largest, picking the smallest type we can.
3610       unsigned Width = 0;
3611 
3612       // Microsoft specific integer suffixes are explicitly sized.
3613       if (Literal.MicrosoftInteger) {
3614         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3615           Width = 8;
3616           Ty = Context.CharTy;
3617         } else {
3618           Width = Literal.MicrosoftInteger;
3619           Ty = Context.getIntTypeForBitwidth(Width,
3620                                              /*Signed=*/!Literal.isUnsigned);
3621         }
3622       }
3623 
3624       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3625         // Are int/unsigned possibilities?
3626         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3627 
3628         // Does it fit in a unsigned int?
3629         if (ResultVal.isIntN(IntSize)) {
3630           // Does it fit in a signed int?
3631           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3632             Ty = Context.IntTy;
3633           else if (AllowUnsigned)
3634             Ty = Context.UnsignedIntTy;
3635           Width = IntSize;
3636         }
3637       }
3638 
3639       // Are long/unsigned long possibilities?
3640       if (Ty.isNull() && !Literal.isLongLong) {
3641         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3642 
3643         // Does it fit in a unsigned long?
3644         if (ResultVal.isIntN(LongSize)) {
3645           // Does it fit in a signed long?
3646           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3647             Ty = Context.LongTy;
3648           else if (AllowUnsigned)
3649             Ty = Context.UnsignedLongTy;
3650           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3651           // is compatible.
3652           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3653             const unsigned LongLongSize =
3654                 Context.getTargetInfo().getLongLongWidth();
3655             Diag(Tok.getLocation(),
3656                  getLangOpts().CPlusPlus
3657                      ? Literal.isLong
3658                            ? diag::warn_old_implicitly_unsigned_long_cxx
3659                            : /*C++98 UB*/ diag::
3660                                  ext_old_implicitly_unsigned_long_cxx
3661                      : diag::warn_old_implicitly_unsigned_long)
3662                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3663                                             : /*will be ill-formed*/ 1);
3664             Ty = Context.UnsignedLongTy;
3665           }
3666           Width = LongSize;
3667         }
3668       }
3669 
3670       // Check long long if needed.
3671       if (Ty.isNull()) {
3672         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3673 
3674         // Does it fit in a unsigned long long?
3675         if (ResultVal.isIntN(LongLongSize)) {
3676           // Does it fit in a signed long long?
3677           // To be compatible with MSVC, hex integer literals ending with the
3678           // LL or i64 suffix are always signed in Microsoft mode.
3679           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3680               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3681             Ty = Context.LongLongTy;
3682           else if (AllowUnsigned)
3683             Ty = Context.UnsignedLongLongTy;
3684           Width = LongLongSize;
3685         }
3686       }
3687 
3688       // If we still couldn't decide a type, we probably have something that
3689       // does not fit in a signed long long, but has no U suffix.
3690       if (Ty.isNull()) {
3691         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3692         Ty = Context.UnsignedLongLongTy;
3693         Width = Context.getTargetInfo().getLongLongWidth();
3694       }
3695 
3696       if (ResultVal.getBitWidth() != Width)
3697         ResultVal = ResultVal.trunc(Width);
3698     }
3699     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3700   }
3701 
3702   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3703   if (Literal.isImaginary) {
3704     Res = new (Context) ImaginaryLiteral(Res,
3705                                         Context.getComplexType(Res->getType()));
3706 
3707     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3708   }
3709   return Res;
3710 }
3711 
3712 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3713   assert(E && "ActOnParenExpr() missing expr");
3714   return new (Context) ParenExpr(L, R, E);
3715 }
3716 
3717 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3718                                          SourceLocation Loc,
3719                                          SourceRange ArgRange) {
3720   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3721   // scalar or vector data type argument..."
3722   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3723   // type (C99 6.2.5p18) or void.
3724   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3725     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3726       << T << ArgRange;
3727     return true;
3728   }
3729 
3730   assert((T->isVoidType() || !T->isIncompleteType()) &&
3731          "Scalar types should always be complete");
3732   return false;
3733 }
3734 
3735 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3736                                            SourceLocation Loc,
3737                                            SourceRange ArgRange,
3738                                            UnaryExprOrTypeTrait TraitKind) {
3739   // Invalid types must be hard errors for SFINAE in C++.
3740   if (S.LangOpts.CPlusPlus)
3741     return true;
3742 
3743   // C99 6.5.3.4p1:
3744   if (T->isFunctionType() &&
3745       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3746        TraitKind == UETT_PreferredAlignOf)) {
3747     // sizeof(function)/alignof(function) is allowed as an extension.
3748     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3749       << TraitKind << ArgRange;
3750     return false;
3751   }
3752 
3753   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3754   // this is an error (OpenCL v1.1 s6.3.k)
3755   if (T->isVoidType()) {
3756     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3757                                         : diag::ext_sizeof_alignof_void_type;
3758     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3759     return false;
3760   }
3761 
3762   return true;
3763 }
3764 
3765 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3766                                              SourceLocation Loc,
3767                                              SourceRange ArgRange,
3768                                              UnaryExprOrTypeTrait TraitKind) {
3769   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3770   // runtime doesn't allow it.
3771   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3772     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3773       << T << (TraitKind == UETT_SizeOf)
3774       << ArgRange;
3775     return true;
3776   }
3777 
3778   return false;
3779 }
3780 
3781 /// Check whether E is a pointer from a decayed array type (the decayed
3782 /// pointer type is equal to T) and emit a warning if it is.
3783 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3784                                      Expr *E) {
3785   // Don't warn if the operation changed the type.
3786   if (T != E->getType())
3787     return;
3788 
3789   // Now look for array decays.
3790   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3791   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3792     return;
3793 
3794   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3795                                              << ICE->getType()
3796                                              << ICE->getSubExpr()->getType();
3797 }
3798 
3799 /// Check the constraints on expression operands to unary type expression
3800 /// and type traits.
3801 ///
3802 /// Completes any types necessary and validates the constraints on the operand
3803 /// expression. The logic mostly mirrors the type-based overload, but may modify
3804 /// the expression as it completes the type for that expression through template
3805 /// instantiation, etc.
3806 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3807                                             UnaryExprOrTypeTrait ExprKind) {
3808   QualType ExprTy = E->getType();
3809   assert(!ExprTy->isReferenceType());
3810 
3811   if (ExprKind == UETT_VecStep)
3812     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3813                                         E->getSourceRange());
3814 
3815   // Whitelist some types as extensions
3816   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3817                                       E->getSourceRange(), ExprKind))
3818     return false;
3819 
3820   // 'alignof' applied to an expression only requires the base element type of
3821   // the expression to be complete. 'sizeof' requires the expression's type to
3822   // be complete (and will attempt to complete it if it's an array of unknown
3823   // bound).
3824   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3825     if (RequireCompleteType(E->getExprLoc(),
3826                             Context.getBaseElementType(E->getType()),
3827                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3828                             E->getSourceRange()))
3829       return true;
3830   } else {
3831     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3832                                 ExprKind, E->getSourceRange()))
3833       return true;
3834   }
3835 
3836   // Completing the expression's type may have changed it.
3837   ExprTy = E->getType();
3838   assert(!ExprTy->isReferenceType());
3839 
3840   if (ExprTy->isFunctionType()) {
3841     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3842       << ExprKind << E->getSourceRange();
3843     return true;
3844   }
3845 
3846   // The operand for sizeof and alignof is in an unevaluated expression context,
3847   // so side effects could result in unintended consequences.
3848   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3849        ExprKind == UETT_PreferredAlignOf) &&
3850       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3851     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3852 
3853   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3854                                        E->getSourceRange(), ExprKind))
3855     return true;
3856 
3857   if (ExprKind == UETT_SizeOf) {
3858     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3859       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3860         QualType OType = PVD->getOriginalType();
3861         QualType Type = PVD->getType();
3862         if (Type->isPointerType() && OType->isArrayType()) {
3863           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3864             << Type << OType;
3865           Diag(PVD->getLocation(), diag::note_declared_at);
3866         }
3867       }
3868     }
3869 
3870     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3871     // decays into a pointer and returns an unintended result. This is most
3872     // likely a typo for "sizeof(array) op x".
3873     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3874       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3875                                BO->getLHS());
3876       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3877                                BO->getRHS());
3878     }
3879   }
3880 
3881   return false;
3882 }
3883 
3884 /// Check the constraints on operands to unary expression and type
3885 /// traits.
3886 ///
3887 /// This will complete any types necessary, and validate the various constraints
3888 /// on those operands.
3889 ///
3890 /// The UsualUnaryConversions() function is *not* called by this routine.
3891 /// C99 6.3.2.1p[2-4] all state:
3892 ///   Except when it is the operand of the sizeof operator ...
3893 ///
3894 /// C++ [expr.sizeof]p4
3895 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3896 ///   standard conversions are not applied to the operand of sizeof.
3897 ///
3898 /// This policy is followed for all of the unary trait expressions.
3899 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3900                                             SourceLocation OpLoc,
3901                                             SourceRange ExprRange,
3902                                             UnaryExprOrTypeTrait ExprKind) {
3903   if (ExprType->isDependentType())
3904     return false;
3905 
3906   // C++ [expr.sizeof]p2:
3907   //     When applied to a reference or a reference type, the result
3908   //     is the size of the referenced type.
3909   // C++11 [expr.alignof]p3:
3910   //     When alignof is applied to a reference type, the result
3911   //     shall be the alignment of the referenced type.
3912   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3913     ExprType = Ref->getPointeeType();
3914 
3915   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3916   //   When alignof or _Alignof is applied to an array type, the result
3917   //   is the alignment of the element type.
3918   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3919       ExprKind == UETT_OpenMPRequiredSimdAlign)
3920     ExprType = Context.getBaseElementType(ExprType);
3921 
3922   if (ExprKind == UETT_VecStep)
3923     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3924 
3925   // Whitelist some types as extensions
3926   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3927                                       ExprKind))
3928     return false;
3929 
3930   if (RequireCompleteType(OpLoc, ExprType,
3931                           diag::err_sizeof_alignof_incomplete_type,
3932                           ExprKind, ExprRange))
3933     return true;
3934 
3935   if (ExprType->isFunctionType()) {
3936     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3937       << ExprKind << ExprRange;
3938     return true;
3939   }
3940 
3941   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3942                                        ExprKind))
3943     return true;
3944 
3945   return false;
3946 }
3947 
3948 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3949   E = E->IgnoreParens();
3950 
3951   // Cannot know anything else if the expression is dependent.
3952   if (E->isTypeDependent())
3953     return false;
3954 
3955   if (E->getObjectKind() == OK_BitField) {
3956     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3957        << 1 << E->getSourceRange();
3958     return true;
3959   }
3960 
3961   ValueDecl *D = nullptr;
3962   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3963     D = DRE->getDecl();
3964   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3965     D = ME->getMemberDecl();
3966   }
3967 
3968   // If it's a field, require the containing struct to have a
3969   // complete definition so that we can compute the layout.
3970   //
3971   // This can happen in C++11 onwards, either by naming the member
3972   // in a way that is not transformed into a member access expression
3973   // (in an unevaluated operand, for instance), or by naming the member
3974   // in a trailing-return-type.
3975   //
3976   // For the record, since __alignof__ on expressions is a GCC
3977   // extension, GCC seems to permit this but always gives the
3978   // nonsensical answer 0.
3979   //
3980   // We don't really need the layout here --- we could instead just
3981   // directly check for all the appropriate alignment-lowing
3982   // attributes --- but that would require duplicating a lot of
3983   // logic that just isn't worth duplicating for such a marginal
3984   // use-case.
3985   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3986     // Fast path this check, since we at least know the record has a
3987     // definition if we can find a member of it.
3988     if (!FD->getParent()->isCompleteDefinition()) {
3989       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3990         << E->getSourceRange();
3991       return true;
3992     }
3993 
3994     // Otherwise, if it's a field, and the field doesn't have
3995     // reference type, then it must have a complete type (or be a
3996     // flexible array member, which we explicitly want to
3997     // white-list anyway), which makes the following checks trivial.
3998     if (!FD->getType()->isReferenceType())
3999       return false;
4000   }
4001 
4002   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4003 }
4004 
4005 bool Sema::CheckVecStepExpr(Expr *E) {
4006   E = E->IgnoreParens();
4007 
4008   // Cannot know anything else if the expression is dependent.
4009   if (E->isTypeDependent())
4010     return false;
4011 
4012   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4013 }
4014 
4015 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4016                                         CapturingScopeInfo *CSI) {
4017   assert(T->isVariablyModifiedType());
4018   assert(CSI != nullptr);
4019 
4020   // We're going to walk down into the type and look for VLA expressions.
4021   do {
4022     const Type *Ty = T.getTypePtr();
4023     switch (Ty->getTypeClass()) {
4024 #define TYPE(Class, Base)
4025 #define ABSTRACT_TYPE(Class, Base)
4026 #define NON_CANONICAL_TYPE(Class, Base)
4027 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4028 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4029 #include "clang/AST/TypeNodes.def"
4030       T = QualType();
4031       break;
4032     // These types are never variably-modified.
4033     case Type::Builtin:
4034     case Type::Complex:
4035     case Type::Vector:
4036     case Type::ExtVector:
4037     case Type::Record:
4038     case Type::Enum:
4039     case Type::Elaborated:
4040     case Type::TemplateSpecialization:
4041     case Type::ObjCObject:
4042     case Type::ObjCInterface:
4043     case Type::ObjCObjectPointer:
4044     case Type::ObjCTypeParam:
4045     case Type::Pipe:
4046       llvm_unreachable("type class is never variably-modified!");
4047     case Type::Adjusted:
4048       T = cast<AdjustedType>(Ty)->getOriginalType();
4049       break;
4050     case Type::Decayed:
4051       T = cast<DecayedType>(Ty)->getPointeeType();
4052       break;
4053     case Type::Pointer:
4054       T = cast<PointerType>(Ty)->getPointeeType();
4055       break;
4056     case Type::BlockPointer:
4057       T = cast<BlockPointerType>(Ty)->getPointeeType();
4058       break;
4059     case Type::LValueReference:
4060     case Type::RValueReference:
4061       T = cast<ReferenceType>(Ty)->getPointeeType();
4062       break;
4063     case Type::MemberPointer:
4064       T = cast<MemberPointerType>(Ty)->getPointeeType();
4065       break;
4066     case Type::ConstantArray:
4067     case Type::IncompleteArray:
4068       // Losing element qualification here is fine.
4069       T = cast<ArrayType>(Ty)->getElementType();
4070       break;
4071     case Type::VariableArray: {
4072       // Losing element qualification here is fine.
4073       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4074 
4075       // Unknown size indication requires no size computation.
4076       // Otherwise, evaluate and record it.
4077       auto Size = VAT->getSizeExpr();
4078       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4079           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4080         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4081 
4082       T = VAT->getElementType();
4083       break;
4084     }
4085     case Type::FunctionProto:
4086     case Type::FunctionNoProto:
4087       T = cast<FunctionType>(Ty)->getReturnType();
4088       break;
4089     case Type::Paren:
4090     case Type::TypeOf:
4091     case Type::UnaryTransform:
4092     case Type::Attributed:
4093     case Type::SubstTemplateTypeParm:
4094     case Type::PackExpansion:
4095     case Type::MacroQualified:
4096       // Keep walking after single level desugaring.
4097       T = T.getSingleStepDesugaredType(Context);
4098       break;
4099     case Type::Typedef:
4100       T = cast<TypedefType>(Ty)->desugar();
4101       break;
4102     case Type::Decltype:
4103       T = cast<DecltypeType>(Ty)->desugar();
4104       break;
4105     case Type::Auto:
4106     case Type::DeducedTemplateSpecialization:
4107       T = cast<DeducedType>(Ty)->getDeducedType();
4108       break;
4109     case Type::TypeOfExpr:
4110       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4111       break;
4112     case Type::Atomic:
4113       T = cast<AtomicType>(Ty)->getValueType();
4114       break;
4115     }
4116   } while (!T.isNull() && T->isVariablyModifiedType());
4117 }
4118 
4119 /// Build a sizeof or alignof expression given a type operand.
4120 ExprResult
4121 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4122                                      SourceLocation OpLoc,
4123                                      UnaryExprOrTypeTrait ExprKind,
4124                                      SourceRange R) {
4125   if (!TInfo)
4126     return ExprError();
4127 
4128   QualType T = TInfo->getType();
4129 
4130   if (!T->isDependentType() &&
4131       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4132     return ExprError();
4133 
4134   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4135     if (auto *TT = T->getAs<TypedefType>()) {
4136       for (auto I = FunctionScopes.rbegin(),
4137                 E = std::prev(FunctionScopes.rend());
4138            I != E; ++I) {
4139         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4140         if (CSI == nullptr)
4141           break;
4142         DeclContext *DC = nullptr;
4143         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4144           DC = LSI->CallOperator;
4145         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4146           DC = CRSI->TheCapturedDecl;
4147         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4148           DC = BSI->TheDecl;
4149         if (DC) {
4150           if (DC->containsDecl(TT->getDecl()))
4151             break;
4152           captureVariablyModifiedType(Context, T, CSI);
4153         }
4154       }
4155     }
4156   }
4157 
4158   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4159   return new (Context) UnaryExprOrTypeTraitExpr(
4160       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4161 }
4162 
4163 /// Build a sizeof or alignof expression given an expression
4164 /// operand.
4165 ExprResult
4166 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4167                                      UnaryExprOrTypeTrait ExprKind) {
4168   ExprResult PE = CheckPlaceholderExpr(E);
4169   if (PE.isInvalid())
4170     return ExprError();
4171 
4172   E = PE.get();
4173 
4174   // Verify that the operand is valid.
4175   bool isInvalid = false;
4176   if (E->isTypeDependent()) {
4177     // Delay type-checking for type-dependent expressions.
4178   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4179     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4180   } else if (ExprKind == UETT_VecStep) {
4181     isInvalid = CheckVecStepExpr(E);
4182   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4183       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4184       isInvalid = true;
4185   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4186     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4187     isInvalid = true;
4188   } else {
4189     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4190   }
4191 
4192   if (isInvalid)
4193     return ExprError();
4194 
4195   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4196     PE = TransformToPotentiallyEvaluated(E);
4197     if (PE.isInvalid()) return ExprError();
4198     E = PE.get();
4199   }
4200 
4201   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4202   return new (Context) UnaryExprOrTypeTraitExpr(
4203       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4204 }
4205 
4206 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4207 /// expr and the same for @c alignof and @c __alignof
4208 /// Note that the ArgRange is invalid if isType is false.
4209 ExprResult
4210 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4211                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4212                                     void *TyOrEx, SourceRange ArgRange) {
4213   // If error parsing type, ignore.
4214   if (!TyOrEx) return ExprError();
4215 
4216   if (IsType) {
4217     TypeSourceInfo *TInfo;
4218     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4219     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4220   }
4221 
4222   Expr *ArgEx = (Expr *)TyOrEx;
4223   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4224   return Result;
4225 }
4226 
4227 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4228                                      bool IsReal) {
4229   if (V.get()->isTypeDependent())
4230     return S.Context.DependentTy;
4231 
4232   // _Real and _Imag are only l-values for normal l-values.
4233   if (V.get()->getObjectKind() != OK_Ordinary) {
4234     V = S.DefaultLvalueConversion(V.get());
4235     if (V.isInvalid())
4236       return QualType();
4237   }
4238 
4239   // These operators return the element type of a complex type.
4240   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4241     return CT->getElementType();
4242 
4243   // Otherwise they pass through real integer and floating point types here.
4244   if (V.get()->getType()->isArithmeticType())
4245     return V.get()->getType();
4246 
4247   // Test for placeholders.
4248   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4249   if (PR.isInvalid()) return QualType();
4250   if (PR.get() != V.get()) {
4251     V = PR;
4252     return CheckRealImagOperand(S, V, Loc, IsReal);
4253   }
4254 
4255   // Reject anything else.
4256   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4257     << (IsReal ? "__real" : "__imag");
4258   return QualType();
4259 }
4260 
4261 
4262 
4263 ExprResult
4264 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4265                           tok::TokenKind Kind, Expr *Input) {
4266   UnaryOperatorKind Opc;
4267   switch (Kind) {
4268   default: llvm_unreachable("Unknown unary op!");
4269   case tok::plusplus:   Opc = UO_PostInc; break;
4270   case tok::minusminus: Opc = UO_PostDec; break;
4271   }
4272 
4273   // Since this might is a postfix expression, get rid of ParenListExprs.
4274   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4275   if (Result.isInvalid()) return ExprError();
4276   Input = Result.get();
4277 
4278   return BuildUnaryOp(S, OpLoc, Opc, Input);
4279 }
4280 
4281 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4282 ///
4283 /// \return true on error
4284 static bool checkArithmeticOnObjCPointer(Sema &S,
4285                                          SourceLocation opLoc,
4286                                          Expr *op) {
4287   assert(op->getType()->isObjCObjectPointerType());
4288   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4289       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4290     return false;
4291 
4292   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4293     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4294     << op->getSourceRange();
4295   return true;
4296 }
4297 
4298 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4299   auto *BaseNoParens = Base->IgnoreParens();
4300   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4301     return MSProp->getPropertyDecl()->getType()->isArrayType();
4302   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4303 }
4304 
4305 ExprResult
4306 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4307                               Expr *idx, SourceLocation rbLoc) {
4308   if (base && !base->getType().isNull() &&
4309       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4310     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4311                                     /*Length=*/nullptr, rbLoc);
4312 
4313   // Since this might be a postfix expression, get rid of ParenListExprs.
4314   if (isa<ParenListExpr>(base)) {
4315     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4316     if (result.isInvalid()) return ExprError();
4317     base = result.get();
4318   }
4319 
4320   // A comma-expression as the index is deprecated in C++2a onwards.
4321   if (getLangOpts().CPlusPlus2a &&
4322       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4323        (isa<CXXOperatorCallExpr>(idx) &&
4324         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4325     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4326       << SourceRange(base->getBeginLoc(), rbLoc);
4327   }
4328 
4329   // Handle any non-overload placeholder types in the base and index
4330   // expressions.  We can't handle overloads here because the other
4331   // operand might be an overloadable type, in which case the overload
4332   // resolution for the operator overload should get the first crack
4333   // at the overload.
4334   bool IsMSPropertySubscript = false;
4335   if (base->getType()->isNonOverloadPlaceholderType()) {
4336     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4337     if (!IsMSPropertySubscript) {
4338       ExprResult result = CheckPlaceholderExpr(base);
4339       if (result.isInvalid())
4340         return ExprError();
4341       base = result.get();
4342     }
4343   }
4344   if (idx->getType()->isNonOverloadPlaceholderType()) {
4345     ExprResult result = CheckPlaceholderExpr(idx);
4346     if (result.isInvalid()) return ExprError();
4347     idx = result.get();
4348   }
4349 
4350   // Build an unanalyzed expression if either operand is type-dependent.
4351   if (getLangOpts().CPlusPlus &&
4352       (base->isTypeDependent() || idx->isTypeDependent())) {
4353     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4354                                             VK_LValue, OK_Ordinary, rbLoc);
4355   }
4356 
4357   // MSDN, property (C++)
4358   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4359   // This attribute can also be used in the declaration of an empty array in a
4360   // class or structure definition. For example:
4361   // __declspec(property(get=GetX, put=PutX)) int x[];
4362   // The above statement indicates that x[] can be used with one or more array
4363   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4364   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4365   if (IsMSPropertySubscript) {
4366     // Build MS property subscript expression if base is MS property reference
4367     // or MS property subscript.
4368     return new (Context) MSPropertySubscriptExpr(
4369         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4370   }
4371 
4372   // Use C++ overloaded-operator rules if either operand has record
4373   // type.  The spec says to do this if either type is *overloadable*,
4374   // but enum types can't declare subscript operators or conversion
4375   // operators, so there's nothing interesting for overload resolution
4376   // to do if there aren't any record types involved.
4377   //
4378   // ObjC pointers have their own subscripting logic that is not tied
4379   // to overload resolution and so should not take this path.
4380   if (getLangOpts().CPlusPlus &&
4381       (base->getType()->isRecordType() ||
4382        (!base->getType()->isObjCObjectPointerType() &&
4383         idx->getType()->isRecordType()))) {
4384     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4385   }
4386 
4387   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4388 
4389   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4390     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4391 
4392   return Res;
4393 }
4394 
4395 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4396   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4397   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4398 
4399   // For expressions like `&(*s).b`, the base is recorded and what should be
4400   // checked.
4401   const MemberExpr *Member = nullptr;
4402   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4403     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4404 
4405   LastRecord.PossibleDerefs.erase(StrippedExpr);
4406 }
4407 
4408 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4409   QualType ResultTy = E->getType();
4410   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4411 
4412   // Bail if the element is an array since it is not memory access.
4413   if (isa<ArrayType>(ResultTy))
4414     return;
4415 
4416   if (ResultTy->hasAttr(attr::NoDeref)) {
4417     LastRecord.PossibleDerefs.insert(E);
4418     return;
4419   }
4420 
4421   // Check if the base type is a pointer to a member access of a struct
4422   // marked with noderef.
4423   const Expr *Base = E->getBase();
4424   QualType BaseTy = Base->getType();
4425   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4426     // Not a pointer access
4427     return;
4428 
4429   const MemberExpr *Member = nullptr;
4430   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4431          Member->isArrow())
4432     Base = Member->getBase();
4433 
4434   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4435     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4436       LastRecord.PossibleDerefs.insert(E);
4437   }
4438 }
4439 
4440 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4441                                           Expr *LowerBound,
4442                                           SourceLocation ColonLoc, Expr *Length,
4443                                           SourceLocation RBLoc) {
4444   if (Base->getType()->isPlaceholderType() &&
4445       !Base->getType()->isSpecificPlaceholderType(
4446           BuiltinType::OMPArraySection)) {
4447     ExprResult Result = CheckPlaceholderExpr(Base);
4448     if (Result.isInvalid())
4449       return ExprError();
4450     Base = Result.get();
4451   }
4452   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4453     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4454     if (Result.isInvalid())
4455       return ExprError();
4456     Result = DefaultLvalueConversion(Result.get());
4457     if (Result.isInvalid())
4458       return ExprError();
4459     LowerBound = Result.get();
4460   }
4461   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4462     ExprResult Result = CheckPlaceholderExpr(Length);
4463     if (Result.isInvalid())
4464       return ExprError();
4465     Result = DefaultLvalueConversion(Result.get());
4466     if (Result.isInvalid())
4467       return ExprError();
4468     Length = Result.get();
4469   }
4470 
4471   // Build an unanalyzed expression if either operand is type-dependent.
4472   if (Base->isTypeDependent() ||
4473       (LowerBound &&
4474        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4475       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4476     return new (Context)
4477         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4478                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4479   }
4480 
4481   // Perform default conversions.
4482   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4483   QualType ResultTy;
4484   if (OriginalTy->isAnyPointerType()) {
4485     ResultTy = OriginalTy->getPointeeType();
4486   } else if (OriginalTy->isArrayType()) {
4487     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4488   } else {
4489     return ExprError(
4490         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4491         << Base->getSourceRange());
4492   }
4493   // C99 6.5.2.1p1
4494   if (LowerBound) {
4495     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4496                                                       LowerBound);
4497     if (Res.isInvalid())
4498       return ExprError(Diag(LowerBound->getExprLoc(),
4499                             diag::err_omp_typecheck_section_not_integer)
4500                        << 0 << LowerBound->getSourceRange());
4501     LowerBound = Res.get();
4502 
4503     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4504         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4505       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4506           << 0 << LowerBound->getSourceRange();
4507   }
4508   if (Length) {
4509     auto Res =
4510         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4511     if (Res.isInvalid())
4512       return ExprError(Diag(Length->getExprLoc(),
4513                             diag::err_omp_typecheck_section_not_integer)
4514                        << 1 << Length->getSourceRange());
4515     Length = Res.get();
4516 
4517     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4518         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4519       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4520           << 1 << Length->getSourceRange();
4521   }
4522 
4523   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4524   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4525   // type. Note that functions are not objects, and that (in C99 parlance)
4526   // incomplete types are not object types.
4527   if (ResultTy->isFunctionType()) {
4528     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4529         << ResultTy << Base->getSourceRange();
4530     return ExprError();
4531   }
4532 
4533   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4534                           diag::err_omp_section_incomplete_type, Base))
4535     return ExprError();
4536 
4537   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4538     Expr::EvalResult Result;
4539     if (LowerBound->EvaluateAsInt(Result, Context)) {
4540       // OpenMP 4.5, [2.4 Array Sections]
4541       // The array section must be a subset of the original array.
4542       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4543       if (LowerBoundValue.isNegative()) {
4544         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4545             << LowerBound->getSourceRange();
4546         return ExprError();
4547       }
4548     }
4549   }
4550 
4551   if (Length) {
4552     Expr::EvalResult Result;
4553     if (Length->EvaluateAsInt(Result, Context)) {
4554       // OpenMP 4.5, [2.4 Array Sections]
4555       // The length must evaluate to non-negative integers.
4556       llvm::APSInt LengthValue = Result.Val.getInt();
4557       if (LengthValue.isNegative()) {
4558         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4559             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4560             << Length->getSourceRange();
4561         return ExprError();
4562       }
4563     }
4564   } else if (ColonLoc.isValid() &&
4565              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4566                                       !OriginalTy->isVariableArrayType()))) {
4567     // OpenMP 4.5, [2.4 Array Sections]
4568     // When the size of the array dimension is not known, the length must be
4569     // specified explicitly.
4570     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4571         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4572     return ExprError();
4573   }
4574 
4575   if (!Base->getType()->isSpecificPlaceholderType(
4576           BuiltinType::OMPArraySection)) {
4577     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4578     if (Result.isInvalid())
4579       return ExprError();
4580     Base = Result.get();
4581   }
4582   return new (Context)
4583       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4584                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4585 }
4586 
4587 ExprResult
4588 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4589                                       Expr *Idx, SourceLocation RLoc) {
4590   Expr *LHSExp = Base;
4591   Expr *RHSExp = Idx;
4592 
4593   ExprValueKind VK = VK_LValue;
4594   ExprObjectKind OK = OK_Ordinary;
4595 
4596   // Per C++ core issue 1213, the result is an xvalue if either operand is
4597   // a non-lvalue array, and an lvalue otherwise.
4598   if (getLangOpts().CPlusPlus11) {
4599     for (auto *Op : {LHSExp, RHSExp}) {
4600       Op = Op->IgnoreImplicit();
4601       if (Op->getType()->isArrayType() && !Op->isLValue())
4602         VK = VK_XValue;
4603     }
4604   }
4605 
4606   // Perform default conversions.
4607   if (!LHSExp->getType()->getAs<VectorType>()) {
4608     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4609     if (Result.isInvalid())
4610       return ExprError();
4611     LHSExp = Result.get();
4612   }
4613   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4614   if (Result.isInvalid())
4615     return ExprError();
4616   RHSExp = Result.get();
4617 
4618   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4619 
4620   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4621   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4622   // in the subscript position. As a result, we need to derive the array base
4623   // and index from the expression types.
4624   Expr *BaseExpr, *IndexExpr;
4625   QualType ResultType;
4626   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4627     BaseExpr = LHSExp;
4628     IndexExpr = RHSExp;
4629     ResultType = Context.DependentTy;
4630   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4631     BaseExpr = LHSExp;
4632     IndexExpr = RHSExp;
4633     ResultType = PTy->getPointeeType();
4634   } else if (const ObjCObjectPointerType *PTy =
4635                LHSTy->getAs<ObjCObjectPointerType>()) {
4636     BaseExpr = LHSExp;
4637     IndexExpr = RHSExp;
4638 
4639     // Use custom logic if this should be the pseudo-object subscript
4640     // expression.
4641     if (!LangOpts.isSubscriptPointerArithmetic())
4642       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4643                                           nullptr);
4644 
4645     ResultType = PTy->getPointeeType();
4646   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4647      // Handle the uncommon case of "123[Ptr]".
4648     BaseExpr = RHSExp;
4649     IndexExpr = LHSExp;
4650     ResultType = PTy->getPointeeType();
4651   } else if (const ObjCObjectPointerType *PTy =
4652                RHSTy->getAs<ObjCObjectPointerType>()) {
4653      // Handle the uncommon case of "123[Ptr]".
4654     BaseExpr = RHSExp;
4655     IndexExpr = LHSExp;
4656     ResultType = PTy->getPointeeType();
4657     if (!LangOpts.isSubscriptPointerArithmetic()) {
4658       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4659         << ResultType << BaseExpr->getSourceRange();
4660       return ExprError();
4661     }
4662   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4663     BaseExpr = LHSExp;    // vectors: V[123]
4664     IndexExpr = RHSExp;
4665     // We apply C++ DR1213 to vector subscripting too.
4666     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4667       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4668       if (Materialized.isInvalid())
4669         return ExprError();
4670       LHSExp = Materialized.get();
4671     }
4672     VK = LHSExp->getValueKind();
4673     if (VK != VK_RValue)
4674       OK = OK_VectorComponent;
4675 
4676     ResultType = VTy->getElementType();
4677     QualType BaseType = BaseExpr->getType();
4678     Qualifiers BaseQuals = BaseType.getQualifiers();
4679     Qualifiers MemberQuals = ResultType.getQualifiers();
4680     Qualifiers Combined = BaseQuals + MemberQuals;
4681     if (Combined != MemberQuals)
4682       ResultType = Context.getQualifiedType(ResultType, Combined);
4683   } else if (LHSTy->isArrayType()) {
4684     // If we see an array that wasn't promoted by
4685     // DefaultFunctionArrayLvalueConversion, it must be an array that
4686     // wasn't promoted because of the C90 rule that doesn't
4687     // allow promoting non-lvalue arrays.  Warn, then
4688     // force the promotion here.
4689     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4690         << LHSExp->getSourceRange();
4691     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4692                                CK_ArrayToPointerDecay).get();
4693     LHSTy = LHSExp->getType();
4694 
4695     BaseExpr = LHSExp;
4696     IndexExpr = RHSExp;
4697     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4698   } else if (RHSTy->isArrayType()) {
4699     // Same as previous, except for 123[f().a] case
4700     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4701         << RHSExp->getSourceRange();
4702     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4703                                CK_ArrayToPointerDecay).get();
4704     RHSTy = RHSExp->getType();
4705 
4706     BaseExpr = RHSExp;
4707     IndexExpr = LHSExp;
4708     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4709   } else {
4710     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4711        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4712   }
4713   // C99 6.5.2.1p1
4714   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4715     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4716                      << IndexExpr->getSourceRange());
4717 
4718   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4719        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4720          && !IndexExpr->isTypeDependent())
4721     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4722 
4723   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4724   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4725   // type. Note that Functions are not objects, and that (in C99 parlance)
4726   // incomplete types are not object types.
4727   if (ResultType->isFunctionType()) {
4728     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4729         << ResultType << BaseExpr->getSourceRange();
4730     return ExprError();
4731   }
4732 
4733   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4734     // GNU extension: subscripting on pointer to void
4735     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4736       << BaseExpr->getSourceRange();
4737 
4738     // C forbids expressions of unqualified void type from being l-values.
4739     // See IsCForbiddenLValueType.
4740     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4741   } else if (!ResultType->isDependentType() &&
4742       RequireCompleteType(LLoc, ResultType,
4743                           diag::err_subscript_incomplete_type, BaseExpr))
4744     return ExprError();
4745 
4746   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4747          !ResultType.isCForbiddenLValueType());
4748 
4749   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4750       FunctionScopes.size() > 1) {
4751     if (auto *TT =
4752             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4753       for (auto I = FunctionScopes.rbegin(),
4754                 E = std::prev(FunctionScopes.rend());
4755            I != E; ++I) {
4756         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4757         if (CSI == nullptr)
4758           break;
4759         DeclContext *DC = nullptr;
4760         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4761           DC = LSI->CallOperator;
4762         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4763           DC = CRSI->TheCapturedDecl;
4764         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4765           DC = BSI->TheDecl;
4766         if (DC) {
4767           if (DC->containsDecl(TT->getDecl()))
4768             break;
4769           captureVariablyModifiedType(
4770               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4771         }
4772       }
4773     }
4774   }
4775 
4776   return new (Context)
4777       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4778 }
4779 
4780 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4781                                   ParmVarDecl *Param) {
4782   if (Param->hasUnparsedDefaultArg()) {
4783     Diag(CallLoc,
4784          diag::err_use_of_default_argument_to_function_declared_later) <<
4785       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4786     Diag(UnparsedDefaultArgLocs[Param],
4787          diag::note_default_argument_declared_here);
4788     return true;
4789   }
4790 
4791   if (Param->hasUninstantiatedDefaultArg()) {
4792     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4793 
4794     EnterExpressionEvaluationContext EvalContext(
4795         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4796 
4797     // Instantiate the expression.
4798     //
4799     // FIXME: Pass in a correct Pattern argument, otherwise
4800     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4801     //
4802     // template<typename T>
4803     // struct A {
4804     //   static int FooImpl();
4805     //
4806     //   template<typename Tp>
4807     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4808     //   // template argument list [[T], [Tp]], should be [[Tp]].
4809     //   friend A<Tp> Foo(int a);
4810     // };
4811     //
4812     // template<typename T>
4813     // A<T> Foo(int a = A<T>::FooImpl());
4814     MultiLevelTemplateArgumentList MutiLevelArgList
4815       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4816 
4817     InstantiatingTemplate Inst(*this, CallLoc, Param,
4818                                MutiLevelArgList.getInnermost());
4819     if (Inst.isInvalid())
4820       return true;
4821     if (Inst.isAlreadyInstantiating()) {
4822       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4823       Param->setInvalidDecl();
4824       return true;
4825     }
4826 
4827     ExprResult Result;
4828     {
4829       // C++ [dcl.fct.default]p5:
4830       //   The names in the [default argument] expression are bound, and
4831       //   the semantic constraints are checked, at the point where the
4832       //   default argument expression appears.
4833       ContextRAII SavedContext(*this, FD);
4834       LocalInstantiationScope Local(*this);
4835       runWithSufficientStackSpace(CallLoc, [&] {
4836         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4837                                   /*DirectInit*/false);
4838       });
4839     }
4840     if (Result.isInvalid())
4841       return true;
4842 
4843     // Check the expression as an initializer for the parameter.
4844     InitializedEntity Entity
4845       = InitializedEntity::InitializeParameter(Context, Param);
4846     InitializationKind Kind = InitializationKind::CreateCopy(
4847         Param->getLocation(),
4848         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4849     Expr *ResultE = Result.getAs<Expr>();
4850 
4851     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4852     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4853     if (Result.isInvalid())
4854       return true;
4855 
4856     Result =
4857         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4858                             /*DiscardedValue*/ false);
4859     if (Result.isInvalid())
4860       return true;
4861 
4862     // Remember the instantiated default argument.
4863     Param->setDefaultArg(Result.getAs<Expr>());
4864     if (ASTMutationListener *L = getASTMutationListener()) {
4865       L->DefaultArgumentInstantiated(Param);
4866     }
4867   }
4868 
4869   // If the default argument expression is not set yet, we are building it now.
4870   if (!Param->hasInit()) {
4871     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4872     Param->setInvalidDecl();
4873     return true;
4874   }
4875 
4876   // If the default expression creates temporaries, we need to
4877   // push them to the current stack of expression temporaries so they'll
4878   // be properly destroyed.
4879   // FIXME: We should really be rebuilding the default argument with new
4880   // bound temporaries; see the comment in PR5810.
4881   // We don't need to do that with block decls, though, because
4882   // blocks in default argument expression can never capture anything.
4883   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4884     // Set the "needs cleanups" bit regardless of whether there are
4885     // any explicit objects.
4886     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4887 
4888     // Append all the objects to the cleanup list.  Right now, this
4889     // should always be a no-op, because blocks in default argument
4890     // expressions should never be able to capture anything.
4891     assert(!Init->getNumObjects() &&
4892            "default argument expression has capturing blocks?");
4893   }
4894 
4895   // We already type-checked the argument, so we know it works.
4896   // Just mark all of the declarations in this potentially-evaluated expression
4897   // as being "referenced".
4898   EnterExpressionEvaluationContext EvalContext(
4899       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4900   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4901                                    /*SkipLocalVariables=*/true);
4902   return false;
4903 }
4904 
4905 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4906                                         FunctionDecl *FD, ParmVarDecl *Param) {
4907   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4908     return ExprError();
4909   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4910 }
4911 
4912 Sema::VariadicCallType
4913 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4914                           Expr *Fn) {
4915   if (Proto && Proto->isVariadic()) {
4916     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4917       return VariadicConstructor;
4918     else if (Fn && Fn->getType()->isBlockPointerType())
4919       return VariadicBlock;
4920     else if (FDecl) {
4921       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4922         if (Method->isInstance())
4923           return VariadicMethod;
4924     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4925       return VariadicMethod;
4926     return VariadicFunction;
4927   }
4928   return VariadicDoesNotApply;
4929 }
4930 
4931 namespace {
4932 class FunctionCallCCC final : public FunctionCallFilterCCC {
4933 public:
4934   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4935                   unsigned NumArgs, MemberExpr *ME)
4936       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4937         FunctionName(FuncName) {}
4938 
4939   bool ValidateCandidate(const TypoCorrection &candidate) override {
4940     if (!candidate.getCorrectionSpecifier() ||
4941         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4942       return false;
4943     }
4944 
4945     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4946   }
4947 
4948   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4949     return std::make_unique<FunctionCallCCC>(*this);
4950   }
4951 
4952 private:
4953   const IdentifierInfo *const FunctionName;
4954 };
4955 }
4956 
4957 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4958                                                FunctionDecl *FDecl,
4959                                                ArrayRef<Expr *> Args) {
4960   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4961   DeclarationName FuncName = FDecl->getDeclName();
4962   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4963 
4964   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4965   if (TypoCorrection Corrected = S.CorrectTypo(
4966           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4967           S.getScopeForContext(S.CurContext), nullptr, CCC,
4968           Sema::CTK_ErrorRecovery)) {
4969     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4970       if (Corrected.isOverloaded()) {
4971         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4972         OverloadCandidateSet::iterator Best;
4973         for (NamedDecl *CD : Corrected) {
4974           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4975             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4976                                    OCS);
4977         }
4978         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4979         case OR_Success:
4980           ND = Best->FoundDecl;
4981           Corrected.setCorrectionDecl(ND);
4982           break;
4983         default:
4984           break;
4985         }
4986       }
4987       ND = ND->getUnderlyingDecl();
4988       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4989         return Corrected;
4990     }
4991   }
4992   return TypoCorrection();
4993 }
4994 
4995 /// ConvertArgumentsForCall - Converts the arguments specified in
4996 /// Args/NumArgs to the parameter types of the function FDecl with
4997 /// function prototype Proto. Call is the call expression itself, and
4998 /// Fn is the function expression. For a C++ member function, this
4999 /// routine does not attempt to convert the object argument. Returns
5000 /// true if the call is ill-formed.
5001 bool
5002 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5003                               FunctionDecl *FDecl,
5004                               const FunctionProtoType *Proto,
5005                               ArrayRef<Expr *> Args,
5006                               SourceLocation RParenLoc,
5007                               bool IsExecConfig) {
5008   // Bail out early if calling a builtin with custom typechecking.
5009   if (FDecl)
5010     if (unsigned ID = FDecl->getBuiltinID())
5011       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5012         return false;
5013 
5014   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5015   // assignment, to the types of the corresponding parameter, ...
5016   unsigned NumParams = Proto->getNumParams();
5017   bool Invalid = false;
5018   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5019   unsigned FnKind = Fn->getType()->isBlockPointerType()
5020                        ? 1 /* block */
5021                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5022                                        : 0 /* function */);
5023 
5024   // If too few arguments are available (and we don't have default
5025   // arguments for the remaining parameters), don't make the call.
5026   if (Args.size() < NumParams) {
5027     if (Args.size() < MinArgs) {
5028       TypoCorrection TC;
5029       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5030         unsigned diag_id =
5031             MinArgs == NumParams && !Proto->isVariadic()
5032                 ? diag::err_typecheck_call_too_few_args_suggest
5033                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5034         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5035                                         << static_cast<unsigned>(Args.size())
5036                                         << TC.getCorrectionRange());
5037       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5038         Diag(RParenLoc,
5039              MinArgs == NumParams && !Proto->isVariadic()
5040                  ? diag::err_typecheck_call_too_few_args_one
5041                  : diag::err_typecheck_call_too_few_args_at_least_one)
5042             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5043       else
5044         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5045                             ? diag::err_typecheck_call_too_few_args
5046                             : diag::err_typecheck_call_too_few_args_at_least)
5047             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5048             << Fn->getSourceRange();
5049 
5050       // Emit the location of the prototype.
5051       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5052         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5053 
5054       return true;
5055     }
5056     // We reserve space for the default arguments when we create
5057     // the call expression, before calling ConvertArgumentsForCall.
5058     assert((Call->getNumArgs() == NumParams) &&
5059            "We should have reserved space for the default arguments before!");
5060   }
5061 
5062   // If too many are passed and not variadic, error on the extras and drop
5063   // them.
5064   if (Args.size() > NumParams) {
5065     if (!Proto->isVariadic()) {
5066       TypoCorrection TC;
5067       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5068         unsigned diag_id =
5069             MinArgs == NumParams && !Proto->isVariadic()
5070                 ? diag::err_typecheck_call_too_many_args_suggest
5071                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5072         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5073                                         << static_cast<unsigned>(Args.size())
5074                                         << TC.getCorrectionRange());
5075       } else if (NumParams == 1 && FDecl &&
5076                  FDecl->getParamDecl(0)->getDeclName())
5077         Diag(Args[NumParams]->getBeginLoc(),
5078              MinArgs == NumParams
5079                  ? diag::err_typecheck_call_too_many_args_one
5080                  : diag::err_typecheck_call_too_many_args_at_most_one)
5081             << FnKind << FDecl->getParamDecl(0)
5082             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5083             << SourceRange(Args[NumParams]->getBeginLoc(),
5084                            Args.back()->getEndLoc());
5085       else
5086         Diag(Args[NumParams]->getBeginLoc(),
5087              MinArgs == NumParams
5088                  ? diag::err_typecheck_call_too_many_args
5089                  : diag::err_typecheck_call_too_many_args_at_most)
5090             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5091             << Fn->getSourceRange()
5092             << SourceRange(Args[NumParams]->getBeginLoc(),
5093                            Args.back()->getEndLoc());
5094 
5095       // Emit the location of the prototype.
5096       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5097         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5098 
5099       // This deletes the extra arguments.
5100       Call->shrinkNumArgs(NumParams);
5101       return true;
5102     }
5103   }
5104   SmallVector<Expr *, 8> AllArgs;
5105   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5106 
5107   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5108                                    AllArgs, CallType);
5109   if (Invalid)
5110     return true;
5111   unsigned TotalNumArgs = AllArgs.size();
5112   for (unsigned i = 0; i < TotalNumArgs; ++i)
5113     Call->setArg(i, AllArgs[i]);
5114 
5115   return false;
5116 }
5117 
5118 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5119                                   const FunctionProtoType *Proto,
5120                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5121                                   SmallVectorImpl<Expr *> &AllArgs,
5122                                   VariadicCallType CallType, bool AllowExplicit,
5123                                   bool IsListInitialization) {
5124   unsigned NumParams = Proto->getNumParams();
5125   bool Invalid = false;
5126   size_t ArgIx = 0;
5127   // Continue to check argument types (even if we have too few/many args).
5128   for (unsigned i = FirstParam; i < NumParams; i++) {
5129     QualType ProtoArgType = Proto->getParamType(i);
5130 
5131     Expr *Arg;
5132     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5133     if (ArgIx < Args.size()) {
5134       Arg = Args[ArgIx++];
5135 
5136       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5137                               diag::err_call_incomplete_argument, Arg))
5138         return true;
5139 
5140       // Strip the unbridged-cast placeholder expression off, if applicable.
5141       bool CFAudited = false;
5142       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5143           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5144           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5145         Arg = stripARCUnbridgedCast(Arg);
5146       else if (getLangOpts().ObjCAutoRefCount &&
5147                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5148                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5149         CFAudited = true;
5150 
5151       if (Proto->getExtParameterInfo(i).isNoEscape())
5152         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5153           BE->getBlockDecl()->setDoesNotEscape();
5154 
5155       InitializedEntity Entity =
5156           Param ? InitializedEntity::InitializeParameter(Context, Param,
5157                                                          ProtoArgType)
5158                 : InitializedEntity::InitializeParameter(
5159                       Context, ProtoArgType, Proto->isParamConsumed(i));
5160 
5161       // Remember that parameter belongs to a CF audited API.
5162       if (CFAudited)
5163         Entity.setParameterCFAudited();
5164 
5165       ExprResult ArgE = PerformCopyInitialization(
5166           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5167       if (ArgE.isInvalid())
5168         return true;
5169 
5170       Arg = ArgE.getAs<Expr>();
5171     } else {
5172       assert(Param && "can't use default arguments without a known callee");
5173 
5174       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5175       if (ArgExpr.isInvalid())
5176         return true;
5177 
5178       Arg = ArgExpr.getAs<Expr>();
5179     }
5180 
5181     // Check for array bounds violations for each argument to the call. This
5182     // check only triggers warnings when the argument isn't a more complex Expr
5183     // with its own checking, such as a BinaryOperator.
5184     CheckArrayAccess(Arg);
5185 
5186     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5187     CheckStaticArrayArgument(CallLoc, Param, Arg);
5188 
5189     AllArgs.push_back(Arg);
5190   }
5191 
5192   // If this is a variadic call, handle args passed through "...".
5193   if (CallType != VariadicDoesNotApply) {
5194     // Assume that extern "C" functions with variadic arguments that
5195     // return __unknown_anytype aren't *really* variadic.
5196     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5197         FDecl->isExternC()) {
5198       for (Expr *A : Args.slice(ArgIx)) {
5199         QualType paramType; // ignored
5200         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5201         Invalid |= arg.isInvalid();
5202         AllArgs.push_back(arg.get());
5203       }
5204 
5205     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5206     } else {
5207       for (Expr *A : Args.slice(ArgIx)) {
5208         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5209         Invalid |= Arg.isInvalid();
5210         AllArgs.push_back(Arg.get());
5211       }
5212     }
5213 
5214     // Check for array bounds violations.
5215     for (Expr *A : Args.slice(ArgIx))
5216       CheckArrayAccess(A);
5217   }
5218   return Invalid;
5219 }
5220 
5221 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5222   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5223   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5224     TL = DTL.getOriginalLoc();
5225   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5226     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5227       << ATL.getLocalSourceRange();
5228 }
5229 
5230 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5231 /// array parameter, check that it is non-null, and that if it is formed by
5232 /// array-to-pointer decay, the underlying array is sufficiently large.
5233 ///
5234 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5235 /// array type derivation, then for each call to the function, the value of the
5236 /// corresponding actual argument shall provide access to the first element of
5237 /// an array with at least as many elements as specified by the size expression.
5238 void
5239 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5240                                ParmVarDecl *Param,
5241                                const Expr *ArgExpr) {
5242   // Static array parameters are not supported in C++.
5243   if (!Param || getLangOpts().CPlusPlus)
5244     return;
5245 
5246   QualType OrigTy = Param->getOriginalType();
5247 
5248   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5249   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5250     return;
5251 
5252   if (ArgExpr->isNullPointerConstant(Context,
5253                                      Expr::NPC_NeverValueDependent)) {
5254     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5255     DiagnoseCalleeStaticArrayParam(*this, Param);
5256     return;
5257   }
5258 
5259   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5260   if (!CAT)
5261     return;
5262 
5263   const ConstantArrayType *ArgCAT =
5264     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5265   if (!ArgCAT)
5266     return;
5267 
5268   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5269                                              ArgCAT->getElementType())) {
5270     if (ArgCAT->getSize().ult(CAT->getSize())) {
5271       Diag(CallLoc, diag::warn_static_array_too_small)
5272           << ArgExpr->getSourceRange()
5273           << (unsigned)ArgCAT->getSize().getZExtValue()
5274           << (unsigned)CAT->getSize().getZExtValue() << 0;
5275       DiagnoseCalleeStaticArrayParam(*this, Param);
5276     }
5277     return;
5278   }
5279 
5280   Optional<CharUnits> ArgSize =
5281       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5282   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5283   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5284     Diag(CallLoc, diag::warn_static_array_too_small)
5285         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5286         << (unsigned)ParmSize->getQuantity() << 1;
5287     DiagnoseCalleeStaticArrayParam(*this, Param);
5288   }
5289 }
5290 
5291 /// Given a function expression of unknown-any type, try to rebuild it
5292 /// to have a function type.
5293 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5294 
5295 /// Is the given type a placeholder that we need to lower out
5296 /// immediately during argument processing?
5297 static bool isPlaceholderToRemoveAsArg(QualType type) {
5298   // Placeholders are never sugared.
5299   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5300   if (!placeholder) return false;
5301 
5302   switch (placeholder->getKind()) {
5303   // Ignore all the non-placeholder types.
5304 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5305   case BuiltinType::Id:
5306 #include "clang/Basic/OpenCLImageTypes.def"
5307 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5308   case BuiltinType::Id:
5309 #include "clang/Basic/OpenCLExtensionTypes.def"
5310   // In practice we'll never use this, since all SVE types are sugared
5311   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5312 #define SVE_TYPE(Name, Id, SingletonId) \
5313   case BuiltinType::Id:
5314 #include "clang/Basic/AArch64SVEACLETypes.def"
5315 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5316 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5317 #include "clang/AST/BuiltinTypes.def"
5318     return false;
5319 
5320   // We cannot lower out overload sets; they might validly be resolved
5321   // by the call machinery.
5322   case BuiltinType::Overload:
5323     return false;
5324 
5325   // Unbridged casts in ARC can be handled in some call positions and
5326   // should be left in place.
5327   case BuiltinType::ARCUnbridgedCast:
5328     return false;
5329 
5330   // Pseudo-objects should be converted as soon as possible.
5331   case BuiltinType::PseudoObject:
5332     return true;
5333 
5334   // The debugger mode could theoretically but currently does not try
5335   // to resolve unknown-typed arguments based on known parameter types.
5336   case BuiltinType::UnknownAny:
5337     return true;
5338 
5339   // These are always invalid as call arguments and should be reported.
5340   case BuiltinType::BoundMember:
5341   case BuiltinType::BuiltinFn:
5342   case BuiltinType::OMPArraySection:
5343     return true;
5344 
5345   }
5346   llvm_unreachable("bad builtin type kind");
5347 }
5348 
5349 /// Check an argument list for placeholders that we won't try to
5350 /// handle later.
5351 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5352   // Apply this processing to all the arguments at once instead of
5353   // dying at the first failure.
5354   bool hasInvalid = false;
5355   for (size_t i = 0, e = args.size(); i != e; i++) {
5356     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5357       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5358       if (result.isInvalid()) hasInvalid = true;
5359       else args[i] = result.get();
5360     } else if (hasInvalid) {
5361       (void)S.CorrectDelayedTyposInExpr(args[i]);
5362     }
5363   }
5364   return hasInvalid;
5365 }
5366 
5367 /// If a builtin function has a pointer argument with no explicit address
5368 /// space, then it should be able to accept a pointer to any address
5369 /// space as input.  In order to do this, we need to replace the
5370 /// standard builtin declaration with one that uses the same address space
5371 /// as the call.
5372 ///
5373 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5374 ///                  it does not contain any pointer arguments without
5375 ///                  an address space qualifer.  Otherwise the rewritten
5376 ///                  FunctionDecl is returned.
5377 /// TODO: Handle pointer return types.
5378 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5379                                                 FunctionDecl *FDecl,
5380                                                 MultiExprArg ArgExprs) {
5381 
5382   QualType DeclType = FDecl->getType();
5383   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5384 
5385   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5386       ArgExprs.size() < FT->getNumParams())
5387     return nullptr;
5388 
5389   bool NeedsNewDecl = false;
5390   unsigned i = 0;
5391   SmallVector<QualType, 8> OverloadParams;
5392 
5393   for (QualType ParamType : FT->param_types()) {
5394 
5395     // Convert array arguments to pointer to simplify type lookup.
5396     ExprResult ArgRes =
5397         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5398     if (ArgRes.isInvalid())
5399       return nullptr;
5400     Expr *Arg = ArgRes.get();
5401     QualType ArgType = Arg->getType();
5402     if (!ParamType->isPointerType() ||
5403         ParamType.getQualifiers().hasAddressSpace() ||
5404         !ArgType->isPointerType() ||
5405         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5406       OverloadParams.push_back(ParamType);
5407       continue;
5408     }
5409 
5410     QualType PointeeType = ParamType->getPointeeType();
5411     if (PointeeType.getQualifiers().hasAddressSpace())
5412       continue;
5413 
5414     NeedsNewDecl = true;
5415     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5416 
5417     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5418     OverloadParams.push_back(Context.getPointerType(PointeeType));
5419   }
5420 
5421   if (!NeedsNewDecl)
5422     return nullptr;
5423 
5424   FunctionProtoType::ExtProtoInfo EPI;
5425   EPI.Variadic = FT->isVariadic();
5426   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5427                                                 OverloadParams, EPI);
5428   DeclContext *Parent = FDecl->getParent();
5429   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5430                                                     FDecl->getLocation(),
5431                                                     FDecl->getLocation(),
5432                                                     FDecl->getIdentifier(),
5433                                                     OverloadTy,
5434                                                     /*TInfo=*/nullptr,
5435                                                     SC_Extern, false,
5436                                                     /*hasPrototype=*/true);
5437   SmallVector<ParmVarDecl*, 16> Params;
5438   FT = cast<FunctionProtoType>(OverloadTy);
5439   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5440     QualType ParamType = FT->getParamType(i);
5441     ParmVarDecl *Parm =
5442         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5443                                 SourceLocation(), nullptr, ParamType,
5444                                 /*TInfo=*/nullptr, SC_None, nullptr);
5445     Parm->setScopeInfo(0, i);
5446     Params.push_back(Parm);
5447   }
5448   OverloadDecl->setParams(Params);
5449   return OverloadDecl;
5450 }
5451 
5452 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5453                                     FunctionDecl *Callee,
5454                                     MultiExprArg ArgExprs) {
5455   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5456   // similar attributes) really don't like it when functions are called with an
5457   // invalid number of args.
5458   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5459                          /*PartialOverloading=*/false) &&
5460       !Callee->isVariadic())
5461     return;
5462   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5463     return;
5464 
5465   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5466     S.Diag(Fn->getBeginLoc(),
5467            isa<CXXMethodDecl>(Callee)
5468                ? diag::err_ovl_no_viable_member_function_in_call
5469                : diag::err_ovl_no_viable_function_in_call)
5470         << Callee << Callee->getSourceRange();
5471     S.Diag(Callee->getLocation(),
5472            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5473         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5474     return;
5475   }
5476 }
5477 
5478 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5479     const UnresolvedMemberExpr *const UME, Sema &S) {
5480 
5481   const auto GetFunctionLevelDCIfCXXClass =
5482       [](Sema &S) -> const CXXRecordDecl * {
5483     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5484     if (!DC || !DC->getParent())
5485       return nullptr;
5486 
5487     // If the call to some member function was made from within a member
5488     // function body 'M' return return 'M's parent.
5489     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5490       return MD->getParent()->getCanonicalDecl();
5491     // else the call was made from within a default member initializer of a
5492     // class, so return the class.
5493     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5494       return RD->getCanonicalDecl();
5495     return nullptr;
5496   };
5497   // If our DeclContext is neither a member function nor a class (in the
5498   // case of a lambda in a default member initializer), we can't have an
5499   // enclosing 'this'.
5500 
5501   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5502   if (!CurParentClass)
5503     return false;
5504 
5505   // The naming class for implicit member functions call is the class in which
5506   // name lookup starts.
5507   const CXXRecordDecl *const NamingClass =
5508       UME->getNamingClass()->getCanonicalDecl();
5509   assert(NamingClass && "Must have naming class even for implicit access");
5510 
5511   // If the unresolved member functions were found in a 'naming class' that is
5512   // related (either the same or derived from) to the class that contains the
5513   // member function that itself contained the implicit member access.
5514 
5515   return CurParentClass == NamingClass ||
5516          CurParentClass->isDerivedFrom(NamingClass);
5517 }
5518 
5519 static void
5520 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5521     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5522 
5523   if (!UME)
5524     return;
5525 
5526   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5527   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5528   // already been captured, or if this is an implicit member function call (if
5529   // it isn't, an attempt to capture 'this' should already have been made).
5530   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5531       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5532     return;
5533 
5534   // Check if the naming class in which the unresolved members were found is
5535   // related (same as or is a base of) to the enclosing class.
5536 
5537   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5538     return;
5539 
5540 
5541   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5542   // If the enclosing function is not dependent, then this lambda is
5543   // capture ready, so if we can capture this, do so.
5544   if (!EnclosingFunctionCtx->isDependentContext()) {
5545     // If the current lambda and all enclosing lambdas can capture 'this' -
5546     // then go ahead and capture 'this' (since our unresolved overload set
5547     // contains at least one non-static member function).
5548     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5549       S.CheckCXXThisCapture(CallLoc);
5550   } else if (S.CurContext->isDependentContext()) {
5551     // ... since this is an implicit member reference, that might potentially
5552     // involve a 'this' capture, mark 'this' for potential capture in
5553     // enclosing lambdas.
5554     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5555       CurLSI->addPotentialThisCapture(CallLoc);
5556   }
5557 }
5558 
5559 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5560                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5561                                Expr *ExecConfig) {
5562   ExprResult Call =
5563       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5564   if (Call.isInvalid())
5565     return Call;
5566 
5567   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5568   // language modes.
5569   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5570     if (ULE->hasExplicitTemplateArgs() &&
5571         ULE->decls_begin() == ULE->decls_end()) {
5572       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5573                                  ? diag::warn_cxx17_compat_adl_only_template_id
5574                                  : diag::ext_adl_only_template_id)
5575           << ULE->getName();
5576     }
5577   }
5578 
5579   return Call;
5580 }
5581 
5582 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5583 /// This provides the location of the left/right parens and a list of comma
5584 /// locations.
5585 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5586                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5587                                Expr *ExecConfig, bool IsExecConfig) {
5588   // Since this might be a postfix expression, get rid of ParenListExprs.
5589   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5590   if (Result.isInvalid()) return ExprError();
5591   Fn = Result.get();
5592 
5593   if (checkArgsForPlaceholders(*this, ArgExprs))
5594     return ExprError();
5595 
5596   if (getLangOpts().CPlusPlus) {
5597     // If this is a pseudo-destructor expression, build the call immediately.
5598     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5599       if (!ArgExprs.empty()) {
5600         // Pseudo-destructor calls should not have any arguments.
5601         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5602             << FixItHint::CreateRemoval(
5603                    SourceRange(ArgExprs.front()->getBeginLoc(),
5604                                ArgExprs.back()->getEndLoc()));
5605       }
5606 
5607       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5608                               VK_RValue, RParenLoc);
5609     }
5610     if (Fn->getType() == Context.PseudoObjectTy) {
5611       ExprResult result = CheckPlaceholderExpr(Fn);
5612       if (result.isInvalid()) return ExprError();
5613       Fn = result.get();
5614     }
5615 
5616     // Determine whether this is a dependent call inside a C++ template,
5617     // in which case we won't do any semantic analysis now.
5618     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5619       if (ExecConfig) {
5620         return CUDAKernelCallExpr::Create(
5621             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5622             Context.DependentTy, VK_RValue, RParenLoc);
5623       } else {
5624 
5625         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5626             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5627             Fn->getBeginLoc());
5628 
5629         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5630                                 VK_RValue, RParenLoc);
5631       }
5632     }
5633 
5634     // Determine whether this is a call to an object (C++ [over.call.object]).
5635     if (Fn->getType()->isRecordType())
5636       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5637                                           RParenLoc);
5638 
5639     if (Fn->getType() == Context.UnknownAnyTy) {
5640       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5641       if (result.isInvalid()) return ExprError();
5642       Fn = result.get();
5643     }
5644 
5645     if (Fn->getType() == Context.BoundMemberTy) {
5646       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5647                                        RParenLoc);
5648     }
5649   }
5650 
5651   // Check for overloaded calls.  This can happen even in C due to extensions.
5652   if (Fn->getType() == Context.OverloadTy) {
5653     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5654 
5655     // We aren't supposed to apply this logic if there's an '&' involved.
5656     if (!find.HasFormOfMemberPointer) {
5657       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5658         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5659                                 VK_RValue, RParenLoc);
5660       OverloadExpr *ovl = find.Expression;
5661       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5662         return BuildOverloadedCallExpr(
5663             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5664             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5665       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5666                                        RParenLoc);
5667     }
5668   }
5669 
5670   // If we're directly calling a function, get the appropriate declaration.
5671   if (Fn->getType() == Context.UnknownAnyTy) {
5672     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5673     if (result.isInvalid()) return ExprError();
5674     Fn = result.get();
5675   }
5676 
5677   Expr *NakedFn = Fn->IgnoreParens();
5678 
5679   bool CallingNDeclIndirectly = false;
5680   NamedDecl *NDecl = nullptr;
5681   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5682     if (UnOp->getOpcode() == UO_AddrOf) {
5683       CallingNDeclIndirectly = true;
5684       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5685     }
5686   }
5687 
5688   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5689     NDecl = DRE->getDecl();
5690 
5691     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5692     if (FDecl && FDecl->getBuiltinID()) {
5693       // Rewrite the function decl for this builtin by replacing parameters
5694       // with no explicit address space with the address space of the arguments
5695       // in ArgExprs.
5696       if ((FDecl =
5697                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5698         NDecl = FDecl;
5699         Fn = DeclRefExpr::Create(
5700             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5701             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5702             nullptr, DRE->isNonOdrUse());
5703       }
5704     }
5705   } else if (isa<MemberExpr>(NakedFn))
5706     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5707 
5708   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5709     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5710                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5711       return ExprError();
5712 
5713     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5714       return ExprError();
5715 
5716     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5717   }
5718 
5719   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5720                                ExecConfig, IsExecConfig);
5721 }
5722 
5723 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5724 ///
5725 /// __builtin_astype( value, dst type )
5726 ///
5727 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5728                                  SourceLocation BuiltinLoc,
5729                                  SourceLocation RParenLoc) {
5730   ExprValueKind VK = VK_RValue;
5731   ExprObjectKind OK = OK_Ordinary;
5732   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5733   QualType SrcTy = E->getType();
5734   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5735     return ExprError(Diag(BuiltinLoc,
5736                           diag::err_invalid_astype_of_different_size)
5737                      << DstTy
5738                      << SrcTy
5739                      << E->getSourceRange());
5740   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5741 }
5742 
5743 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5744 /// provided arguments.
5745 ///
5746 /// __builtin_convertvector( value, dst type )
5747 ///
5748 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5749                                         SourceLocation BuiltinLoc,
5750                                         SourceLocation RParenLoc) {
5751   TypeSourceInfo *TInfo;
5752   GetTypeFromParser(ParsedDestTy, &TInfo);
5753   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5754 }
5755 
5756 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5757 /// i.e. an expression not of \p OverloadTy.  The expression should
5758 /// unary-convert to an expression of function-pointer or
5759 /// block-pointer type.
5760 ///
5761 /// \param NDecl the declaration being called, if available
5762 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5763                                        SourceLocation LParenLoc,
5764                                        ArrayRef<Expr *> Args,
5765                                        SourceLocation RParenLoc, Expr *Config,
5766                                        bool IsExecConfig, ADLCallKind UsesADL) {
5767   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5768   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5769 
5770   // Functions with 'interrupt' attribute cannot be called directly.
5771   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5772     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5773     return ExprError();
5774   }
5775 
5776   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5777   // so there's some risk when calling out to non-interrupt handler functions
5778   // that the callee might not preserve them. This is easy to diagnose here,
5779   // but can be very challenging to debug.
5780   if (auto *Caller = getCurFunctionDecl())
5781     if (Caller->hasAttr<ARMInterruptAttr>()) {
5782       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5783       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5784         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5785     }
5786 
5787   // Promote the function operand.
5788   // We special-case function promotion here because we only allow promoting
5789   // builtin functions to function pointers in the callee of a call.
5790   ExprResult Result;
5791   QualType ResultTy;
5792   if (BuiltinID &&
5793       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5794     // Extract the return type from the (builtin) function pointer type.
5795     // FIXME Several builtins still have setType in
5796     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5797     // Builtins.def to ensure they are correct before removing setType calls.
5798     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5799     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5800     ResultTy = FDecl->getCallResultType();
5801   } else {
5802     Result = CallExprUnaryConversions(Fn);
5803     ResultTy = Context.BoolTy;
5804   }
5805   if (Result.isInvalid())
5806     return ExprError();
5807   Fn = Result.get();
5808 
5809   // Check for a valid function type, but only if it is not a builtin which
5810   // requires custom type checking. These will be handled by
5811   // CheckBuiltinFunctionCall below just after creation of the call expression.
5812   const FunctionType *FuncT = nullptr;
5813   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5814   retry:
5815     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5816       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5817       // have type pointer to function".
5818       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5819       if (!FuncT)
5820         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5821                          << Fn->getType() << Fn->getSourceRange());
5822     } else if (const BlockPointerType *BPT =
5823                    Fn->getType()->getAs<BlockPointerType>()) {
5824       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5825     } else {
5826       // Handle calls to expressions of unknown-any type.
5827       if (Fn->getType() == Context.UnknownAnyTy) {
5828         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5829         if (rewrite.isInvalid())
5830           return ExprError();
5831         Fn = rewrite.get();
5832         goto retry;
5833       }
5834 
5835       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5836                        << Fn->getType() << Fn->getSourceRange());
5837     }
5838   }
5839 
5840   // Get the number of parameters in the function prototype, if any.
5841   // We will allocate space for max(Args.size(), NumParams) arguments
5842   // in the call expression.
5843   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5844   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5845 
5846   CallExpr *TheCall;
5847   if (Config) {
5848     assert(UsesADL == ADLCallKind::NotADL &&
5849            "CUDAKernelCallExpr should not use ADL");
5850     TheCall =
5851         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5852                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5853   } else {
5854     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5855                                RParenLoc, NumParams, UsesADL);
5856   }
5857 
5858   if (!getLangOpts().CPlusPlus) {
5859     // Forget about the nulled arguments since typo correction
5860     // do not handle them well.
5861     TheCall->shrinkNumArgs(Args.size());
5862     // C cannot always handle TypoExpr nodes in builtin calls and direct
5863     // function calls as their argument checking don't necessarily handle
5864     // dependent types properly, so make sure any TypoExprs have been
5865     // dealt with.
5866     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5867     if (!Result.isUsable()) return ExprError();
5868     CallExpr *TheOldCall = TheCall;
5869     TheCall = dyn_cast<CallExpr>(Result.get());
5870     bool CorrectedTypos = TheCall != TheOldCall;
5871     if (!TheCall) return Result;
5872     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5873 
5874     // A new call expression node was created if some typos were corrected.
5875     // However it may not have been constructed with enough storage. In this
5876     // case, rebuild the node with enough storage. The waste of space is
5877     // immaterial since this only happens when some typos were corrected.
5878     if (CorrectedTypos && Args.size() < NumParams) {
5879       if (Config)
5880         TheCall = CUDAKernelCallExpr::Create(
5881             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5882             RParenLoc, NumParams);
5883       else
5884         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5885                                    RParenLoc, NumParams, UsesADL);
5886     }
5887     // We can now handle the nulled arguments for the default arguments.
5888     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5889   }
5890 
5891   // Bail out early if calling a builtin with custom type checking.
5892   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5893     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5894 
5895   if (getLangOpts().CUDA) {
5896     if (Config) {
5897       // CUDA: Kernel calls must be to global functions
5898       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5899         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5900             << FDecl << Fn->getSourceRange());
5901 
5902       // CUDA: Kernel function must have 'void' return type
5903       if (!FuncT->getReturnType()->isVoidType())
5904         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5905             << Fn->getType() << Fn->getSourceRange());
5906     } else {
5907       // CUDA: Calls to global functions must be configured
5908       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5909         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5910             << FDecl << Fn->getSourceRange());
5911     }
5912   }
5913 
5914   // Check for a valid return type
5915   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5916                           FDecl))
5917     return ExprError();
5918 
5919   // We know the result type of the call, set it.
5920   TheCall->setType(FuncT->getCallResultType(Context));
5921   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5922 
5923   if (Proto) {
5924     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5925                                 IsExecConfig))
5926       return ExprError();
5927   } else {
5928     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5929 
5930     if (FDecl) {
5931       // Check if we have too few/too many template arguments, based
5932       // on our knowledge of the function definition.
5933       const FunctionDecl *Def = nullptr;
5934       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5935         Proto = Def->getType()->getAs<FunctionProtoType>();
5936        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5937           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5938           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5939       }
5940 
5941       // If the function we're calling isn't a function prototype, but we have
5942       // a function prototype from a prior declaratiom, use that prototype.
5943       if (!FDecl->hasPrototype())
5944         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5945     }
5946 
5947     // Promote the arguments (C99 6.5.2.2p6).
5948     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5949       Expr *Arg = Args[i];
5950 
5951       if (Proto && i < Proto->getNumParams()) {
5952         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5953             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5954         ExprResult ArgE =
5955             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5956         if (ArgE.isInvalid())
5957           return true;
5958 
5959         Arg = ArgE.getAs<Expr>();
5960 
5961       } else {
5962         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5963 
5964         if (ArgE.isInvalid())
5965           return true;
5966 
5967         Arg = ArgE.getAs<Expr>();
5968       }
5969 
5970       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5971                               diag::err_call_incomplete_argument, Arg))
5972         return ExprError();
5973 
5974       TheCall->setArg(i, Arg);
5975     }
5976   }
5977 
5978   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5979     if (!Method->isStatic())
5980       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5981         << Fn->getSourceRange());
5982 
5983   // Check for sentinels
5984   if (NDecl)
5985     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5986 
5987   // Do special checking on direct calls to functions.
5988   if (FDecl) {
5989     if (CheckFunctionCall(FDecl, TheCall, Proto))
5990       return ExprError();
5991 
5992     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5993 
5994     if (BuiltinID)
5995       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5996   } else if (NDecl) {
5997     if (CheckPointerCall(NDecl, TheCall, Proto))
5998       return ExprError();
5999   } else {
6000     if (CheckOtherCall(TheCall, Proto))
6001       return ExprError();
6002   }
6003 
6004   return MaybeBindToTemporary(TheCall);
6005 }
6006 
6007 ExprResult
6008 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6009                            SourceLocation RParenLoc, Expr *InitExpr) {
6010   assert(Ty && "ActOnCompoundLiteral(): missing type");
6011   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6012 
6013   TypeSourceInfo *TInfo;
6014   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6015   if (!TInfo)
6016     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6017 
6018   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6019 }
6020 
6021 ExprResult
6022 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6023                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6024   QualType literalType = TInfo->getType();
6025 
6026   if (literalType->isArrayType()) {
6027     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6028           diag::err_illegal_decl_array_incomplete_type,
6029           SourceRange(LParenLoc,
6030                       LiteralExpr->getSourceRange().getEnd())))
6031       return ExprError();
6032     if (literalType->isVariableArrayType())
6033       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6034         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6035   } else if (!literalType->isDependentType() &&
6036              RequireCompleteType(LParenLoc, literalType,
6037                diag::err_typecheck_decl_incomplete_type,
6038                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6039     return ExprError();
6040 
6041   InitializedEntity Entity
6042     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6043   InitializationKind Kind
6044     = InitializationKind::CreateCStyleCast(LParenLoc,
6045                                            SourceRange(LParenLoc, RParenLoc),
6046                                            /*InitList=*/true);
6047   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6048   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6049                                       &literalType);
6050   if (Result.isInvalid())
6051     return ExprError();
6052   LiteralExpr = Result.get();
6053 
6054   bool isFileScope = !CurContext->isFunctionOrMethod();
6055 
6056   // In C, compound literals are l-values for some reason.
6057   // For GCC compatibility, in C++, file-scope array compound literals with
6058   // constant initializers are also l-values, and compound literals are
6059   // otherwise prvalues.
6060   //
6061   // (GCC also treats C++ list-initialized file-scope array prvalues with
6062   // constant initializers as l-values, but that's non-conforming, so we don't
6063   // follow it there.)
6064   //
6065   // FIXME: It would be better to handle the lvalue cases as materializing and
6066   // lifetime-extending a temporary object, but our materialized temporaries
6067   // representation only supports lifetime extension from a variable, not "out
6068   // of thin air".
6069   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6070   // is bound to the result of applying array-to-pointer decay to the compound
6071   // literal.
6072   // FIXME: GCC supports compound literals of reference type, which should
6073   // obviously have a value kind derived from the kind of reference involved.
6074   ExprValueKind VK =
6075       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6076           ? VK_RValue
6077           : VK_LValue;
6078 
6079   if (isFileScope)
6080     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6081       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6082         Expr *Init = ILE->getInit(i);
6083         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6084       }
6085 
6086   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6087                                               VK, LiteralExpr, isFileScope);
6088   if (isFileScope) {
6089     if (!LiteralExpr->isTypeDependent() &&
6090         !LiteralExpr->isValueDependent() &&
6091         !literalType->isDependentType()) // C99 6.5.2.5p3
6092       if (CheckForConstantInitializer(LiteralExpr, literalType))
6093         return ExprError();
6094   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6095              literalType.getAddressSpace() != LangAS::Default) {
6096     // Embedded-C extensions to C99 6.5.2.5:
6097     //   "If the compound literal occurs inside the body of a function, the
6098     //   type name shall not be qualified by an address-space qualifier."
6099     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6100       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6101     return ExprError();
6102   }
6103 
6104   return MaybeBindToTemporary(E);
6105 }
6106 
6107 ExprResult
6108 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6109                     SourceLocation RBraceLoc) {
6110   // Immediately handle non-overload placeholders.  Overloads can be
6111   // resolved contextually, but everything else here can't.
6112   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6113     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6114       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6115 
6116       // Ignore failures; dropping the entire initializer list because
6117       // of one failure would be terrible for indexing/etc.
6118       if (result.isInvalid()) continue;
6119 
6120       InitArgList[I] = result.get();
6121     }
6122   }
6123 
6124   // Semantic analysis for initializers is done by ActOnDeclarator() and
6125   // CheckInitializer() - it requires knowledge of the object being initialized.
6126 
6127   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6128                                                RBraceLoc);
6129   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6130   return E;
6131 }
6132 
6133 /// Do an explicit extend of the given block pointer if we're in ARC.
6134 void Sema::maybeExtendBlockObject(ExprResult &E) {
6135   assert(E.get()->getType()->isBlockPointerType());
6136   assert(E.get()->isRValue());
6137 
6138   // Only do this in an r-value context.
6139   if (!getLangOpts().ObjCAutoRefCount) return;
6140 
6141   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6142                                CK_ARCExtendBlockObject, E.get(),
6143                                /*base path*/ nullptr, VK_RValue);
6144   Cleanup.setExprNeedsCleanups(true);
6145 }
6146 
6147 /// Prepare a conversion of the given expression to an ObjC object
6148 /// pointer type.
6149 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6150   QualType type = E.get()->getType();
6151   if (type->isObjCObjectPointerType()) {
6152     return CK_BitCast;
6153   } else if (type->isBlockPointerType()) {
6154     maybeExtendBlockObject(E);
6155     return CK_BlockPointerToObjCPointerCast;
6156   } else {
6157     assert(type->isPointerType());
6158     return CK_CPointerToObjCPointerCast;
6159   }
6160 }
6161 
6162 /// Prepares for a scalar cast, performing all the necessary stages
6163 /// except the final cast and returning the kind required.
6164 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6165   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6166   // Also, callers should have filtered out the invalid cases with
6167   // pointers.  Everything else should be possible.
6168 
6169   QualType SrcTy = Src.get()->getType();
6170   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6171     return CK_NoOp;
6172 
6173   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6174   case Type::STK_MemberPointer:
6175     llvm_unreachable("member pointer type in C");
6176 
6177   case Type::STK_CPointer:
6178   case Type::STK_BlockPointer:
6179   case Type::STK_ObjCObjectPointer:
6180     switch (DestTy->getScalarTypeKind()) {
6181     case Type::STK_CPointer: {
6182       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6183       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6184       if (SrcAS != DestAS)
6185         return CK_AddressSpaceConversion;
6186       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6187         return CK_NoOp;
6188       return CK_BitCast;
6189     }
6190     case Type::STK_BlockPointer:
6191       return (SrcKind == Type::STK_BlockPointer
6192                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6193     case Type::STK_ObjCObjectPointer:
6194       if (SrcKind == Type::STK_ObjCObjectPointer)
6195         return CK_BitCast;
6196       if (SrcKind == Type::STK_CPointer)
6197         return CK_CPointerToObjCPointerCast;
6198       maybeExtendBlockObject(Src);
6199       return CK_BlockPointerToObjCPointerCast;
6200     case Type::STK_Bool:
6201       return CK_PointerToBoolean;
6202     case Type::STK_Integral:
6203       return CK_PointerToIntegral;
6204     case Type::STK_Floating:
6205     case Type::STK_FloatingComplex:
6206     case Type::STK_IntegralComplex:
6207     case Type::STK_MemberPointer:
6208     case Type::STK_FixedPoint:
6209       llvm_unreachable("illegal cast from pointer");
6210     }
6211     llvm_unreachable("Should have returned before this");
6212 
6213   case Type::STK_FixedPoint:
6214     switch (DestTy->getScalarTypeKind()) {
6215     case Type::STK_FixedPoint:
6216       return CK_FixedPointCast;
6217     case Type::STK_Bool:
6218       return CK_FixedPointToBoolean;
6219     case Type::STK_Integral:
6220       return CK_FixedPointToIntegral;
6221     case Type::STK_Floating:
6222     case Type::STK_IntegralComplex:
6223     case Type::STK_FloatingComplex:
6224       Diag(Src.get()->getExprLoc(),
6225            diag::err_unimplemented_conversion_with_fixed_point_type)
6226           << DestTy;
6227       return CK_IntegralCast;
6228     case Type::STK_CPointer:
6229     case Type::STK_ObjCObjectPointer:
6230     case Type::STK_BlockPointer:
6231     case Type::STK_MemberPointer:
6232       llvm_unreachable("illegal cast to pointer type");
6233     }
6234     llvm_unreachable("Should have returned before this");
6235 
6236   case Type::STK_Bool: // casting from bool is like casting from an integer
6237   case Type::STK_Integral:
6238     switch (DestTy->getScalarTypeKind()) {
6239     case Type::STK_CPointer:
6240     case Type::STK_ObjCObjectPointer:
6241     case Type::STK_BlockPointer:
6242       if (Src.get()->isNullPointerConstant(Context,
6243                                            Expr::NPC_ValueDependentIsNull))
6244         return CK_NullToPointer;
6245       return CK_IntegralToPointer;
6246     case Type::STK_Bool:
6247       return CK_IntegralToBoolean;
6248     case Type::STK_Integral:
6249       return CK_IntegralCast;
6250     case Type::STK_Floating:
6251       return CK_IntegralToFloating;
6252     case Type::STK_IntegralComplex:
6253       Src = ImpCastExprToType(Src.get(),
6254                       DestTy->castAs<ComplexType>()->getElementType(),
6255                       CK_IntegralCast);
6256       return CK_IntegralRealToComplex;
6257     case Type::STK_FloatingComplex:
6258       Src = ImpCastExprToType(Src.get(),
6259                       DestTy->castAs<ComplexType>()->getElementType(),
6260                       CK_IntegralToFloating);
6261       return CK_FloatingRealToComplex;
6262     case Type::STK_MemberPointer:
6263       llvm_unreachable("member pointer type in C");
6264     case Type::STK_FixedPoint:
6265       return CK_IntegralToFixedPoint;
6266     }
6267     llvm_unreachable("Should have returned before this");
6268 
6269   case Type::STK_Floating:
6270     switch (DestTy->getScalarTypeKind()) {
6271     case Type::STK_Floating:
6272       return CK_FloatingCast;
6273     case Type::STK_Bool:
6274       return CK_FloatingToBoolean;
6275     case Type::STK_Integral:
6276       return CK_FloatingToIntegral;
6277     case Type::STK_FloatingComplex:
6278       Src = ImpCastExprToType(Src.get(),
6279                               DestTy->castAs<ComplexType>()->getElementType(),
6280                               CK_FloatingCast);
6281       return CK_FloatingRealToComplex;
6282     case Type::STK_IntegralComplex:
6283       Src = ImpCastExprToType(Src.get(),
6284                               DestTy->castAs<ComplexType>()->getElementType(),
6285                               CK_FloatingToIntegral);
6286       return CK_IntegralRealToComplex;
6287     case Type::STK_CPointer:
6288     case Type::STK_ObjCObjectPointer:
6289     case Type::STK_BlockPointer:
6290       llvm_unreachable("valid float->pointer cast?");
6291     case Type::STK_MemberPointer:
6292       llvm_unreachable("member pointer type in C");
6293     case Type::STK_FixedPoint:
6294       Diag(Src.get()->getExprLoc(),
6295            diag::err_unimplemented_conversion_with_fixed_point_type)
6296           << SrcTy;
6297       return CK_IntegralCast;
6298     }
6299     llvm_unreachable("Should have returned before this");
6300 
6301   case Type::STK_FloatingComplex:
6302     switch (DestTy->getScalarTypeKind()) {
6303     case Type::STK_FloatingComplex:
6304       return CK_FloatingComplexCast;
6305     case Type::STK_IntegralComplex:
6306       return CK_FloatingComplexToIntegralComplex;
6307     case Type::STK_Floating: {
6308       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6309       if (Context.hasSameType(ET, DestTy))
6310         return CK_FloatingComplexToReal;
6311       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6312       return CK_FloatingCast;
6313     }
6314     case Type::STK_Bool:
6315       return CK_FloatingComplexToBoolean;
6316     case Type::STK_Integral:
6317       Src = ImpCastExprToType(Src.get(),
6318                               SrcTy->castAs<ComplexType>()->getElementType(),
6319                               CK_FloatingComplexToReal);
6320       return CK_FloatingToIntegral;
6321     case Type::STK_CPointer:
6322     case Type::STK_ObjCObjectPointer:
6323     case Type::STK_BlockPointer:
6324       llvm_unreachable("valid complex float->pointer cast?");
6325     case Type::STK_MemberPointer:
6326       llvm_unreachable("member pointer type in C");
6327     case Type::STK_FixedPoint:
6328       Diag(Src.get()->getExprLoc(),
6329            diag::err_unimplemented_conversion_with_fixed_point_type)
6330           << SrcTy;
6331       return CK_IntegralCast;
6332     }
6333     llvm_unreachable("Should have returned before this");
6334 
6335   case Type::STK_IntegralComplex:
6336     switch (DestTy->getScalarTypeKind()) {
6337     case Type::STK_FloatingComplex:
6338       return CK_IntegralComplexToFloatingComplex;
6339     case Type::STK_IntegralComplex:
6340       return CK_IntegralComplexCast;
6341     case Type::STK_Integral: {
6342       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6343       if (Context.hasSameType(ET, DestTy))
6344         return CK_IntegralComplexToReal;
6345       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6346       return CK_IntegralCast;
6347     }
6348     case Type::STK_Bool:
6349       return CK_IntegralComplexToBoolean;
6350     case Type::STK_Floating:
6351       Src = ImpCastExprToType(Src.get(),
6352                               SrcTy->castAs<ComplexType>()->getElementType(),
6353                               CK_IntegralComplexToReal);
6354       return CK_IntegralToFloating;
6355     case Type::STK_CPointer:
6356     case Type::STK_ObjCObjectPointer:
6357     case Type::STK_BlockPointer:
6358       llvm_unreachable("valid complex int->pointer cast?");
6359     case Type::STK_MemberPointer:
6360       llvm_unreachable("member pointer type in C");
6361     case Type::STK_FixedPoint:
6362       Diag(Src.get()->getExprLoc(),
6363            diag::err_unimplemented_conversion_with_fixed_point_type)
6364           << SrcTy;
6365       return CK_IntegralCast;
6366     }
6367     llvm_unreachable("Should have returned before this");
6368   }
6369 
6370   llvm_unreachable("Unhandled scalar cast");
6371 }
6372 
6373 static bool breakDownVectorType(QualType type, uint64_t &len,
6374                                 QualType &eltType) {
6375   // Vectors are simple.
6376   if (const VectorType *vecType = type->getAs<VectorType>()) {
6377     len = vecType->getNumElements();
6378     eltType = vecType->getElementType();
6379     assert(eltType->isScalarType());
6380     return true;
6381   }
6382 
6383   // We allow lax conversion to and from non-vector types, but only if
6384   // they're real types (i.e. non-complex, non-pointer scalar types).
6385   if (!type->isRealType()) return false;
6386 
6387   len = 1;
6388   eltType = type;
6389   return true;
6390 }
6391 
6392 /// Are the two types lax-compatible vector types?  That is, given
6393 /// that one of them is a vector, do they have equal storage sizes,
6394 /// where the storage size is the number of elements times the element
6395 /// size?
6396 ///
6397 /// This will also return false if either of the types is neither a
6398 /// vector nor a real type.
6399 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6400   assert(destTy->isVectorType() || srcTy->isVectorType());
6401 
6402   // Disallow lax conversions between scalars and ExtVectors (these
6403   // conversions are allowed for other vector types because common headers
6404   // depend on them).  Most scalar OP ExtVector cases are handled by the
6405   // splat path anyway, which does what we want (convert, not bitcast).
6406   // What this rules out for ExtVectors is crazy things like char4*float.
6407   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6408   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6409 
6410   uint64_t srcLen, destLen;
6411   QualType srcEltTy, destEltTy;
6412   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6413   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6414 
6415   // ASTContext::getTypeSize will return the size rounded up to a
6416   // power of 2, so instead of using that, we need to use the raw
6417   // element size multiplied by the element count.
6418   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6419   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6420 
6421   return (srcLen * srcEltSize == destLen * destEltSize);
6422 }
6423 
6424 /// Is this a legal conversion between two types, one of which is
6425 /// known to be a vector type?
6426 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6427   assert(destTy->isVectorType() || srcTy->isVectorType());
6428 
6429   if (!Context.getLangOpts().LaxVectorConversions)
6430     return false;
6431   return areLaxCompatibleVectorTypes(srcTy, destTy);
6432 }
6433 
6434 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6435                            CastKind &Kind) {
6436   assert(VectorTy->isVectorType() && "Not a vector type!");
6437 
6438   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6439     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6440       return Diag(R.getBegin(),
6441                   Ty->isVectorType() ?
6442                   diag::err_invalid_conversion_between_vectors :
6443                   diag::err_invalid_conversion_between_vector_and_integer)
6444         << VectorTy << Ty << R;
6445   } else
6446     return Diag(R.getBegin(),
6447                 diag::err_invalid_conversion_between_vector_and_scalar)
6448       << VectorTy << Ty << R;
6449 
6450   Kind = CK_BitCast;
6451   return false;
6452 }
6453 
6454 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6455   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6456 
6457   if (DestElemTy == SplattedExpr->getType())
6458     return SplattedExpr;
6459 
6460   assert(DestElemTy->isFloatingType() ||
6461          DestElemTy->isIntegralOrEnumerationType());
6462 
6463   CastKind CK;
6464   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6465     // OpenCL requires that we convert `true` boolean expressions to -1, but
6466     // only when splatting vectors.
6467     if (DestElemTy->isFloatingType()) {
6468       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6469       // in two steps: boolean to signed integral, then to floating.
6470       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6471                                                  CK_BooleanToSignedIntegral);
6472       SplattedExpr = CastExprRes.get();
6473       CK = CK_IntegralToFloating;
6474     } else {
6475       CK = CK_BooleanToSignedIntegral;
6476     }
6477   } else {
6478     ExprResult CastExprRes = SplattedExpr;
6479     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6480     if (CastExprRes.isInvalid())
6481       return ExprError();
6482     SplattedExpr = CastExprRes.get();
6483   }
6484   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6485 }
6486 
6487 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6488                                     Expr *CastExpr, CastKind &Kind) {
6489   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6490 
6491   QualType SrcTy = CastExpr->getType();
6492 
6493   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6494   // an ExtVectorType.
6495   // In OpenCL, casts between vectors of different types are not allowed.
6496   // (See OpenCL 6.2).
6497   if (SrcTy->isVectorType()) {
6498     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6499         (getLangOpts().OpenCL &&
6500          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6501       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6502         << DestTy << SrcTy << R;
6503       return ExprError();
6504     }
6505     Kind = CK_BitCast;
6506     return CastExpr;
6507   }
6508 
6509   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6510   // conversion will take place first from scalar to elt type, and then
6511   // splat from elt type to vector.
6512   if (SrcTy->isPointerType())
6513     return Diag(R.getBegin(),
6514                 diag::err_invalid_conversion_between_vector_and_scalar)
6515       << DestTy << SrcTy << R;
6516 
6517   Kind = CK_VectorSplat;
6518   return prepareVectorSplat(DestTy, CastExpr);
6519 }
6520 
6521 ExprResult
6522 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6523                     Declarator &D, ParsedType &Ty,
6524                     SourceLocation RParenLoc, Expr *CastExpr) {
6525   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6526          "ActOnCastExpr(): missing type or expr");
6527 
6528   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6529   if (D.isInvalidType())
6530     return ExprError();
6531 
6532   if (getLangOpts().CPlusPlus) {
6533     // Check that there are no default arguments (C++ only).
6534     CheckExtraCXXDefaultArguments(D);
6535   } else {
6536     // Make sure any TypoExprs have been dealt with.
6537     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6538     if (!Res.isUsable())
6539       return ExprError();
6540     CastExpr = Res.get();
6541   }
6542 
6543   checkUnusedDeclAttributes(D);
6544 
6545   QualType castType = castTInfo->getType();
6546   Ty = CreateParsedType(castType, castTInfo);
6547 
6548   bool isVectorLiteral = false;
6549 
6550   // Check for an altivec or OpenCL literal,
6551   // i.e. all the elements are integer constants.
6552   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6553   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6554   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6555        && castType->isVectorType() && (PE || PLE)) {
6556     if (PLE && PLE->getNumExprs() == 0) {
6557       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6558       return ExprError();
6559     }
6560     if (PE || PLE->getNumExprs() == 1) {
6561       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6562       if (!E->getType()->isVectorType())
6563         isVectorLiteral = true;
6564     }
6565     else
6566       isVectorLiteral = true;
6567   }
6568 
6569   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6570   // then handle it as such.
6571   if (isVectorLiteral)
6572     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6573 
6574   // If the Expr being casted is a ParenListExpr, handle it specially.
6575   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6576   // sequence of BinOp comma operators.
6577   if (isa<ParenListExpr>(CastExpr)) {
6578     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6579     if (Result.isInvalid()) return ExprError();
6580     CastExpr = Result.get();
6581   }
6582 
6583   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6584       !getSourceManager().isInSystemMacro(LParenLoc))
6585     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6586 
6587   CheckTollFreeBridgeCast(castType, CastExpr);
6588 
6589   CheckObjCBridgeRelatedCast(castType, CastExpr);
6590 
6591   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6592 
6593   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6594 }
6595 
6596 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6597                                     SourceLocation RParenLoc, Expr *E,
6598                                     TypeSourceInfo *TInfo) {
6599   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6600          "Expected paren or paren list expression");
6601 
6602   Expr **exprs;
6603   unsigned numExprs;
6604   Expr *subExpr;
6605   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6606   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6607     LiteralLParenLoc = PE->getLParenLoc();
6608     LiteralRParenLoc = PE->getRParenLoc();
6609     exprs = PE->getExprs();
6610     numExprs = PE->getNumExprs();
6611   } else { // isa<ParenExpr> by assertion at function entrance
6612     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6613     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6614     subExpr = cast<ParenExpr>(E)->getSubExpr();
6615     exprs = &subExpr;
6616     numExprs = 1;
6617   }
6618 
6619   QualType Ty = TInfo->getType();
6620   assert(Ty->isVectorType() && "Expected vector type");
6621 
6622   SmallVector<Expr *, 8> initExprs;
6623   const VectorType *VTy = Ty->getAs<VectorType>();
6624   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6625 
6626   // '(...)' form of vector initialization in AltiVec: the number of
6627   // initializers must be one or must match the size of the vector.
6628   // If a single value is specified in the initializer then it will be
6629   // replicated to all the components of the vector
6630   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6631     // The number of initializers must be one or must match the size of the
6632     // vector. If a single value is specified in the initializer then it will
6633     // be replicated to all the components of the vector
6634     if (numExprs == 1) {
6635       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6636       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6637       if (Literal.isInvalid())
6638         return ExprError();
6639       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6640                                   PrepareScalarCast(Literal, ElemTy));
6641       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6642     }
6643     else if (numExprs < numElems) {
6644       Diag(E->getExprLoc(),
6645            diag::err_incorrect_number_of_vector_initializers);
6646       return ExprError();
6647     }
6648     else
6649       initExprs.append(exprs, exprs + numExprs);
6650   }
6651   else {
6652     // For OpenCL, when the number of initializers is a single value,
6653     // it will be replicated to all components of the vector.
6654     if (getLangOpts().OpenCL &&
6655         VTy->getVectorKind() == VectorType::GenericVector &&
6656         numExprs == 1) {
6657         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6658         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6659         if (Literal.isInvalid())
6660           return ExprError();
6661         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6662                                     PrepareScalarCast(Literal, ElemTy));
6663         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6664     }
6665 
6666     initExprs.append(exprs, exprs + numExprs);
6667   }
6668   // FIXME: This means that pretty-printing the final AST will produce curly
6669   // braces instead of the original commas.
6670   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6671                                                    initExprs, LiteralRParenLoc);
6672   initE->setType(Ty);
6673   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6674 }
6675 
6676 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6677 /// the ParenListExpr into a sequence of comma binary operators.
6678 ExprResult
6679 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6680   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6681   if (!E)
6682     return OrigExpr;
6683 
6684   ExprResult Result(E->getExpr(0));
6685 
6686   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6687     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6688                         E->getExpr(i));
6689 
6690   if (Result.isInvalid()) return ExprError();
6691 
6692   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6693 }
6694 
6695 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6696                                     SourceLocation R,
6697                                     MultiExprArg Val) {
6698   return ParenListExpr::Create(Context, L, Val, R);
6699 }
6700 
6701 /// Emit a specialized diagnostic when one expression is a null pointer
6702 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6703 /// emitted.
6704 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6705                                       SourceLocation QuestionLoc) {
6706   Expr *NullExpr = LHSExpr;
6707   Expr *NonPointerExpr = RHSExpr;
6708   Expr::NullPointerConstantKind NullKind =
6709       NullExpr->isNullPointerConstant(Context,
6710                                       Expr::NPC_ValueDependentIsNotNull);
6711 
6712   if (NullKind == Expr::NPCK_NotNull) {
6713     NullExpr = RHSExpr;
6714     NonPointerExpr = LHSExpr;
6715     NullKind =
6716         NullExpr->isNullPointerConstant(Context,
6717                                         Expr::NPC_ValueDependentIsNotNull);
6718   }
6719 
6720   if (NullKind == Expr::NPCK_NotNull)
6721     return false;
6722 
6723   if (NullKind == Expr::NPCK_ZeroExpression)
6724     return false;
6725 
6726   if (NullKind == Expr::NPCK_ZeroLiteral) {
6727     // In this case, check to make sure that we got here from a "NULL"
6728     // string in the source code.
6729     NullExpr = NullExpr->IgnoreParenImpCasts();
6730     SourceLocation loc = NullExpr->getExprLoc();
6731     if (!findMacroSpelling(loc, "NULL"))
6732       return false;
6733   }
6734 
6735   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6736   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6737       << NonPointerExpr->getType() << DiagType
6738       << NonPointerExpr->getSourceRange();
6739   return true;
6740 }
6741 
6742 /// Return false if the condition expression is valid, true otherwise.
6743 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6744   QualType CondTy = Cond->getType();
6745 
6746   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6747   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6748     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6749       << CondTy << Cond->getSourceRange();
6750     return true;
6751   }
6752 
6753   // C99 6.5.15p2
6754   if (CondTy->isScalarType()) return false;
6755 
6756   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6757     << CondTy << Cond->getSourceRange();
6758   return true;
6759 }
6760 
6761 /// Handle when one or both operands are void type.
6762 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6763                                          ExprResult &RHS) {
6764     Expr *LHSExpr = LHS.get();
6765     Expr *RHSExpr = RHS.get();
6766 
6767     if (!LHSExpr->getType()->isVoidType())
6768       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6769           << RHSExpr->getSourceRange();
6770     if (!RHSExpr->getType()->isVoidType())
6771       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6772           << LHSExpr->getSourceRange();
6773     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6774     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6775     return S.Context.VoidTy;
6776 }
6777 
6778 /// Return false if the NullExpr can be promoted to PointerTy,
6779 /// true otherwise.
6780 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6781                                         QualType PointerTy) {
6782   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6783       !NullExpr.get()->isNullPointerConstant(S.Context,
6784                                             Expr::NPC_ValueDependentIsNull))
6785     return true;
6786 
6787   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6788   return false;
6789 }
6790 
6791 /// Checks compatibility between two pointers and return the resulting
6792 /// type.
6793 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6794                                                      ExprResult &RHS,
6795                                                      SourceLocation Loc) {
6796   QualType LHSTy = LHS.get()->getType();
6797   QualType RHSTy = RHS.get()->getType();
6798 
6799   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6800     // Two identical pointers types are always compatible.
6801     return LHSTy;
6802   }
6803 
6804   QualType lhptee, rhptee;
6805 
6806   // Get the pointee types.
6807   bool IsBlockPointer = false;
6808   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6809     lhptee = LHSBTy->getPointeeType();
6810     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6811     IsBlockPointer = true;
6812   } else {
6813     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6814     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6815   }
6816 
6817   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6818   // differently qualified versions of compatible types, the result type is
6819   // a pointer to an appropriately qualified version of the composite
6820   // type.
6821 
6822   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6823   // clause doesn't make sense for our extensions. E.g. address space 2 should
6824   // be incompatible with address space 3: they may live on different devices or
6825   // anything.
6826   Qualifiers lhQual = lhptee.getQualifiers();
6827   Qualifiers rhQual = rhptee.getQualifiers();
6828 
6829   LangAS ResultAddrSpace = LangAS::Default;
6830   LangAS LAddrSpace = lhQual.getAddressSpace();
6831   LangAS RAddrSpace = rhQual.getAddressSpace();
6832 
6833   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6834   // spaces is disallowed.
6835   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6836     ResultAddrSpace = LAddrSpace;
6837   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6838     ResultAddrSpace = RAddrSpace;
6839   else {
6840     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6841         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6842         << RHS.get()->getSourceRange();
6843     return QualType();
6844   }
6845 
6846   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6847   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6848   lhQual.removeCVRQualifiers();
6849   rhQual.removeCVRQualifiers();
6850 
6851   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6852   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6853   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6854   // qual types are compatible iff
6855   //  * corresponded types are compatible
6856   //  * CVR qualifiers are equal
6857   //  * address spaces are equal
6858   // Thus for conditional operator we merge CVR and address space unqualified
6859   // pointees and if there is a composite type we return a pointer to it with
6860   // merged qualifiers.
6861   LHSCastKind =
6862       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6863   RHSCastKind =
6864       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6865   lhQual.removeAddressSpace();
6866   rhQual.removeAddressSpace();
6867 
6868   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6869   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6870 
6871   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6872 
6873   if (CompositeTy.isNull()) {
6874     // In this situation, we assume void* type. No especially good
6875     // reason, but this is what gcc does, and we do have to pick
6876     // to get a consistent AST.
6877     QualType incompatTy;
6878     incompatTy = S.Context.getPointerType(
6879         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6880     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6881     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6882 
6883     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6884     // for casts between types with incompatible address space qualifiers.
6885     // For the following code the compiler produces casts between global and
6886     // local address spaces of the corresponded innermost pointees:
6887     // local int *global *a;
6888     // global int *global *b;
6889     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6890     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6891         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6892         << RHS.get()->getSourceRange();
6893 
6894     return incompatTy;
6895   }
6896 
6897   // The pointer types are compatible.
6898   // In case of OpenCL ResultTy should have the address space qualifier
6899   // which is a superset of address spaces of both the 2nd and the 3rd
6900   // operands of the conditional operator.
6901   QualType ResultTy = [&, ResultAddrSpace]() {
6902     if (S.getLangOpts().OpenCL) {
6903       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6904       CompositeQuals.setAddressSpace(ResultAddrSpace);
6905       return S.Context
6906           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6907           .withCVRQualifiers(MergedCVRQual);
6908     }
6909     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6910   }();
6911   if (IsBlockPointer)
6912     ResultTy = S.Context.getBlockPointerType(ResultTy);
6913   else
6914     ResultTy = S.Context.getPointerType(ResultTy);
6915 
6916   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6917   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6918   return ResultTy;
6919 }
6920 
6921 /// Return the resulting type when the operands are both block pointers.
6922 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6923                                                           ExprResult &LHS,
6924                                                           ExprResult &RHS,
6925                                                           SourceLocation Loc) {
6926   QualType LHSTy = LHS.get()->getType();
6927   QualType RHSTy = RHS.get()->getType();
6928 
6929   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6930     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6931       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6932       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6933       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6934       return destType;
6935     }
6936     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6937       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6938       << RHS.get()->getSourceRange();
6939     return QualType();
6940   }
6941 
6942   // We have 2 block pointer types.
6943   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6944 }
6945 
6946 /// Return the resulting type when the operands are both pointers.
6947 static QualType
6948 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6949                                             ExprResult &RHS,
6950                                             SourceLocation Loc) {
6951   // get the pointer types
6952   QualType LHSTy = LHS.get()->getType();
6953   QualType RHSTy = RHS.get()->getType();
6954 
6955   // get the "pointed to" types
6956   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6957   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6958 
6959   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6960   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6961     // Figure out necessary qualifiers (C99 6.5.15p6)
6962     QualType destPointee
6963       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6964     QualType destType = S.Context.getPointerType(destPointee);
6965     // Add qualifiers if necessary.
6966     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6967     // Promote to void*.
6968     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6969     return destType;
6970   }
6971   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6972     QualType destPointee
6973       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6974     QualType destType = S.Context.getPointerType(destPointee);
6975     // Add qualifiers if necessary.
6976     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6977     // Promote to void*.
6978     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6979     return destType;
6980   }
6981 
6982   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6983 }
6984 
6985 /// Return false if the first expression is not an integer and the second
6986 /// expression is not a pointer, true otherwise.
6987 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6988                                         Expr* PointerExpr, SourceLocation Loc,
6989                                         bool IsIntFirstExpr) {
6990   if (!PointerExpr->getType()->isPointerType() ||
6991       !Int.get()->getType()->isIntegerType())
6992     return false;
6993 
6994   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6995   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6996 
6997   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6998     << Expr1->getType() << Expr2->getType()
6999     << Expr1->getSourceRange() << Expr2->getSourceRange();
7000   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7001                             CK_IntegralToPointer);
7002   return true;
7003 }
7004 
7005 /// Simple conversion between integer and floating point types.
7006 ///
7007 /// Used when handling the OpenCL conditional operator where the
7008 /// condition is a vector while the other operands are scalar.
7009 ///
7010 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7011 /// types are either integer or floating type. Between the two
7012 /// operands, the type with the higher rank is defined as the "result
7013 /// type". The other operand needs to be promoted to the same type. No
7014 /// other type promotion is allowed. We cannot use
7015 /// UsualArithmeticConversions() for this purpose, since it always
7016 /// promotes promotable types.
7017 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7018                                             ExprResult &RHS,
7019                                             SourceLocation QuestionLoc) {
7020   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7021   if (LHS.isInvalid())
7022     return QualType();
7023   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7024   if (RHS.isInvalid())
7025     return QualType();
7026 
7027   // For conversion purposes, we ignore any qualifiers.
7028   // For example, "const float" and "float" are equivalent.
7029   QualType LHSType =
7030     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7031   QualType RHSType =
7032     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7033 
7034   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7035     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7036       << LHSType << LHS.get()->getSourceRange();
7037     return QualType();
7038   }
7039 
7040   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7041     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7042       << RHSType << RHS.get()->getSourceRange();
7043     return QualType();
7044   }
7045 
7046   // If both types are identical, no conversion is needed.
7047   if (LHSType == RHSType)
7048     return LHSType;
7049 
7050   // Now handle "real" floating types (i.e. float, double, long double).
7051   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7052     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7053                                  /*IsCompAssign = */ false);
7054 
7055   // Finally, we have two differing integer types.
7056   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7057   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7058 }
7059 
7060 /// Convert scalar operands to a vector that matches the
7061 ///        condition in length.
7062 ///
7063 /// Used when handling the OpenCL conditional operator where the
7064 /// condition is a vector while the other operands are scalar.
7065 ///
7066 /// We first compute the "result type" for the scalar operands
7067 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7068 /// into a vector of that type where the length matches the condition
7069 /// vector type. s6.11.6 requires that the element types of the result
7070 /// and the condition must have the same number of bits.
7071 static QualType
7072 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7073                               QualType CondTy, SourceLocation QuestionLoc) {
7074   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7075   if (ResTy.isNull()) return QualType();
7076 
7077   const VectorType *CV = CondTy->getAs<VectorType>();
7078   assert(CV);
7079 
7080   // Determine the vector result type
7081   unsigned NumElements = CV->getNumElements();
7082   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7083 
7084   // Ensure that all types have the same number of bits
7085   if (S.Context.getTypeSize(CV->getElementType())
7086       != S.Context.getTypeSize(ResTy)) {
7087     // Since VectorTy is created internally, it does not pretty print
7088     // with an OpenCL name. Instead, we just print a description.
7089     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7090     SmallString<64> Str;
7091     llvm::raw_svector_ostream OS(Str);
7092     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7093     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7094       << CondTy << OS.str();
7095     return QualType();
7096   }
7097 
7098   // Convert operands to the vector result type
7099   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7100   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7101 
7102   return VectorTy;
7103 }
7104 
7105 /// Return false if this is a valid OpenCL condition vector
7106 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7107                                        SourceLocation QuestionLoc) {
7108   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7109   // integral type.
7110   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7111   assert(CondTy);
7112   QualType EleTy = CondTy->getElementType();
7113   if (EleTy->isIntegerType()) return false;
7114 
7115   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7116     << Cond->getType() << Cond->getSourceRange();
7117   return true;
7118 }
7119 
7120 /// Return false if the vector condition type and the vector
7121 ///        result type are compatible.
7122 ///
7123 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7124 /// number of elements, and their element types have the same number
7125 /// of bits.
7126 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7127                               SourceLocation QuestionLoc) {
7128   const VectorType *CV = CondTy->getAs<VectorType>();
7129   const VectorType *RV = VecResTy->getAs<VectorType>();
7130   assert(CV && RV);
7131 
7132   if (CV->getNumElements() != RV->getNumElements()) {
7133     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7134       << CondTy << VecResTy;
7135     return true;
7136   }
7137 
7138   QualType CVE = CV->getElementType();
7139   QualType RVE = RV->getElementType();
7140 
7141   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7142     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7143       << CondTy << VecResTy;
7144     return true;
7145   }
7146 
7147   return false;
7148 }
7149 
7150 /// Return the resulting type for the conditional operator in
7151 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7152 ///        s6.3.i) when the condition is a vector type.
7153 static QualType
7154 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7155                              ExprResult &LHS, ExprResult &RHS,
7156                              SourceLocation QuestionLoc) {
7157   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7158   if (Cond.isInvalid())
7159     return QualType();
7160   QualType CondTy = Cond.get()->getType();
7161 
7162   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7163     return QualType();
7164 
7165   // If either operand is a vector then find the vector type of the
7166   // result as specified in OpenCL v1.1 s6.3.i.
7167   if (LHS.get()->getType()->isVectorType() ||
7168       RHS.get()->getType()->isVectorType()) {
7169     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7170                                               /*isCompAssign*/false,
7171                                               /*AllowBothBool*/true,
7172                                               /*AllowBoolConversions*/false);
7173     if (VecResTy.isNull()) return QualType();
7174     // The result type must match the condition type as specified in
7175     // OpenCL v1.1 s6.11.6.
7176     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7177       return QualType();
7178     return VecResTy;
7179   }
7180 
7181   // Both operands are scalar.
7182   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7183 }
7184 
7185 /// Return true if the Expr is block type
7186 static bool checkBlockType(Sema &S, const Expr *E) {
7187   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7188     QualType Ty = CE->getCallee()->getType();
7189     if (Ty->isBlockPointerType()) {
7190       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7191       return true;
7192     }
7193   }
7194   return false;
7195 }
7196 
7197 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7198 /// In that case, LHS = cond.
7199 /// C99 6.5.15
7200 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7201                                         ExprResult &RHS, ExprValueKind &VK,
7202                                         ExprObjectKind &OK,
7203                                         SourceLocation QuestionLoc) {
7204 
7205   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7206   if (!LHSResult.isUsable()) return QualType();
7207   LHS = LHSResult;
7208 
7209   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7210   if (!RHSResult.isUsable()) return QualType();
7211   RHS = RHSResult;
7212 
7213   // C++ is sufficiently different to merit its own checker.
7214   if (getLangOpts().CPlusPlus)
7215     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7216 
7217   VK = VK_RValue;
7218   OK = OK_Ordinary;
7219 
7220   // The OpenCL operator with a vector condition is sufficiently
7221   // different to merit its own checker.
7222   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7223     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7224 
7225   // First, check the condition.
7226   Cond = UsualUnaryConversions(Cond.get());
7227   if (Cond.isInvalid())
7228     return QualType();
7229   if (checkCondition(*this, Cond.get(), QuestionLoc))
7230     return QualType();
7231 
7232   // Now check the two expressions.
7233   if (LHS.get()->getType()->isVectorType() ||
7234       RHS.get()->getType()->isVectorType())
7235     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7236                                /*AllowBothBool*/true,
7237                                /*AllowBoolConversions*/false);
7238 
7239   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7240   if (LHS.isInvalid() || RHS.isInvalid())
7241     return QualType();
7242 
7243   QualType LHSTy = LHS.get()->getType();
7244   QualType RHSTy = RHS.get()->getType();
7245 
7246   // Diagnose attempts to convert between __float128 and long double where
7247   // such conversions currently can't be handled.
7248   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7249     Diag(QuestionLoc,
7250          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7251       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7252     return QualType();
7253   }
7254 
7255   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7256   // selection operator (?:).
7257   if (getLangOpts().OpenCL &&
7258       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7259     return QualType();
7260   }
7261 
7262   // If both operands have arithmetic type, do the usual arithmetic conversions
7263   // to find a common type: C99 6.5.15p3,5.
7264   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7265     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7266     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7267 
7268     return ResTy;
7269   }
7270 
7271   // If both operands are the same structure or union type, the result is that
7272   // type.
7273   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7274     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7275       if (LHSRT->getDecl() == RHSRT->getDecl())
7276         // "If both the operands have structure or union type, the result has
7277         // that type."  This implies that CV qualifiers are dropped.
7278         return LHSTy.getUnqualifiedType();
7279     // FIXME: Type of conditional expression must be complete in C mode.
7280   }
7281 
7282   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7283   // The following || allows only one side to be void (a GCC-ism).
7284   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7285     return checkConditionalVoidType(*this, LHS, RHS);
7286   }
7287 
7288   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7289   // the type of the other operand."
7290   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7291   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7292 
7293   // All objective-c pointer type analysis is done here.
7294   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7295                                                         QuestionLoc);
7296   if (LHS.isInvalid() || RHS.isInvalid())
7297     return QualType();
7298   if (!compositeType.isNull())
7299     return compositeType;
7300 
7301 
7302   // Handle block pointer types.
7303   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7304     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7305                                                      QuestionLoc);
7306 
7307   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7308   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7309     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7310                                                        QuestionLoc);
7311 
7312   // GCC compatibility: soften pointer/integer mismatch.  Note that
7313   // null pointers have been filtered out by this point.
7314   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7315       /*IsIntFirstExpr=*/true))
7316     return RHSTy;
7317   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7318       /*IsIntFirstExpr=*/false))
7319     return LHSTy;
7320 
7321   // Emit a better diagnostic if one of the expressions is a null pointer
7322   // constant and the other is not a pointer type. In this case, the user most
7323   // likely forgot to take the address of the other expression.
7324   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7325     return QualType();
7326 
7327   // Otherwise, the operands are not compatible.
7328   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7329     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7330     << RHS.get()->getSourceRange();
7331   return QualType();
7332 }
7333 
7334 /// FindCompositeObjCPointerType - Helper method to find composite type of
7335 /// two objective-c pointer types of the two input expressions.
7336 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7337                                             SourceLocation QuestionLoc) {
7338   QualType LHSTy = LHS.get()->getType();
7339   QualType RHSTy = RHS.get()->getType();
7340 
7341   // Handle things like Class and struct objc_class*.  Here we case the result
7342   // to the pseudo-builtin, because that will be implicitly cast back to the
7343   // redefinition type if an attempt is made to access its fields.
7344   if (LHSTy->isObjCClassType() &&
7345       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7346     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7347     return LHSTy;
7348   }
7349   if (RHSTy->isObjCClassType() &&
7350       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7351     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7352     return RHSTy;
7353   }
7354   // And the same for struct objc_object* / id
7355   if (LHSTy->isObjCIdType() &&
7356       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7357     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7358     return LHSTy;
7359   }
7360   if (RHSTy->isObjCIdType() &&
7361       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7362     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7363     return RHSTy;
7364   }
7365   // And the same for struct objc_selector* / SEL
7366   if (Context.isObjCSelType(LHSTy) &&
7367       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7368     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7369     return LHSTy;
7370   }
7371   if (Context.isObjCSelType(RHSTy) &&
7372       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7373     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7374     return RHSTy;
7375   }
7376   // Check constraints for Objective-C object pointers types.
7377   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7378 
7379     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7380       // Two identical object pointer types are always compatible.
7381       return LHSTy;
7382     }
7383     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7384     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7385     QualType compositeType = LHSTy;
7386 
7387     // If both operands are interfaces and either operand can be
7388     // assigned to the other, use that type as the composite
7389     // type. This allows
7390     //   xxx ? (A*) a : (B*) b
7391     // where B is a subclass of A.
7392     //
7393     // Additionally, as for assignment, if either type is 'id'
7394     // allow silent coercion. Finally, if the types are
7395     // incompatible then make sure to use 'id' as the composite
7396     // type so the result is acceptable for sending messages to.
7397 
7398     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7399     // It could return the composite type.
7400     if (!(compositeType =
7401           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7402       // Nothing more to do.
7403     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7404       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7405     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7406       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7407     } else if ((LHSTy->isObjCQualifiedIdType() ||
7408                 RHSTy->isObjCQualifiedIdType()) &&
7409                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7410       // Need to handle "id<xx>" explicitly.
7411       // GCC allows qualified id and any Objective-C type to devolve to
7412       // id. Currently localizing to here until clear this should be
7413       // part of ObjCQualifiedIdTypesAreCompatible.
7414       compositeType = Context.getObjCIdType();
7415     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7416       compositeType = Context.getObjCIdType();
7417     } else {
7418       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7419       << LHSTy << RHSTy
7420       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7421       QualType incompatTy = Context.getObjCIdType();
7422       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7423       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7424       return incompatTy;
7425     }
7426     // The object pointer types are compatible.
7427     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7428     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7429     return compositeType;
7430   }
7431   // Check Objective-C object pointer types and 'void *'
7432   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7433     if (getLangOpts().ObjCAutoRefCount) {
7434       // ARC forbids the implicit conversion of object pointers to 'void *',
7435       // so these types are not compatible.
7436       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7437           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7438       LHS = RHS = true;
7439       return QualType();
7440     }
7441     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7442     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7443     QualType destPointee
7444     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7445     QualType destType = Context.getPointerType(destPointee);
7446     // Add qualifiers if necessary.
7447     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7448     // Promote to void*.
7449     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7450     return destType;
7451   }
7452   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7453     if (getLangOpts().ObjCAutoRefCount) {
7454       // ARC forbids the implicit conversion of object pointers to 'void *',
7455       // so these types are not compatible.
7456       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7457           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7458       LHS = RHS = true;
7459       return QualType();
7460     }
7461     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7462     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7463     QualType destPointee
7464     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7465     QualType destType = Context.getPointerType(destPointee);
7466     // Add qualifiers if necessary.
7467     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7468     // Promote to void*.
7469     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7470     return destType;
7471   }
7472   return QualType();
7473 }
7474 
7475 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7476 /// ParenRange in parentheses.
7477 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7478                                const PartialDiagnostic &Note,
7479                                SourceRange ParenRange) {
7480   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7481   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7482       EndLoc.isValid()) {
7483     Self.Diag(Loc, Note)
7484       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7485       << FixItHint::CreateInsertion(EndLoc, ")");
7486   } else {
7487     // We can't display the parentheses, so just show the bare note.
7488     Self.Diag(Loc, Note) << ParenRange;
7489   }
7490 }
7491 
7492 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7493   return BinaryOperator::isAdditiveOp(Opc) ||
7494          BinaryOperator::isMultiplicativeOp(Opc) ||
7495          BinaryOperator::isShiftOp(Opc);
7496 }
7497 
7498 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7499 /// expression, either using a built-in or overloaded operator,
7500 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7501 /// expression.
7502 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7503                                    Expr **RHSExprs) {
7504   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7505   E = E->IgnoreImpCasts();
7506   E = E->IgnoreConversionOperator();
7507   E = E->IgnoreImpCasts();
7508   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7509     E = MTE->GetTemporaryExpr();
7510     E = E->IgnoreImpCasts();
7511   }
7512 
7513   // Built-in binary operator.
7514   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7515     if (IsArithmeticOp(OP->getOpcode())) {
7516       *Opcode = OP->getOpcode();
7517       *RHSExprs = OP->getRHS();
7518       return true;
7519     }
7520   }
7521 
7522   // Overloaded operator.
7523   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7524     if (Call->getNumArgs() != 2)
7525       return false;
7526 
7527     // Make sure this is really a binary operator that is safe to pass into
7528     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7529     OverloadedOperatorKind OO = Call->getOperator();
7530     if (OO < OO_Plus || OO > OO_Arrow ||
7531         OO == OO_PlusPlus || OO == OO_MinusMinus)
7532       return false;
7533 
7534     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7535     if (IsArithmeticOp(OpKind)) {
7536       *Opcode = OpKind;
7537       *RHSExprs = Call->getArg(1);
7538       return true;
7539     }
7540   }
7541 
7542   return false;
7543 }
7544 
7545 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7546 /// or is a logical expression such as (x==y) which has int type, but is
7547 /// commonly interpreted as boolean.
7548 static bool ExprLooksBoolean(Expr *E) {
7549   E = E->IgnoreParenImpCasts();
7550 
7551   if (E->getType()->isBooleanType())
7552     return true;
7553   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7554     return OP->isComparisonOp() || OP->isLogicalOp();
7555   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7556     return OP->getOpcode() == UO_LNot;
7557   if (E->getType()->isPointerType())
7558     return true;
7559   // FIXME: What about overloaded operator calls returning "unspecified boolean
7560   // type"s (commonly pointer-to-members)?
7561 
7562   return false;
7563 }
7564 
7565 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7566 /// and binary operator are mixed in a way that suggests the programmer assumed
7567 /// the conditional operator has higher precedence, for example:
7568 /// "int x = a + someBinaryCondition ? 1 : 2".
7569 static void DiagnoseConditionalPrecedence(Sema &Self,
7570                                           SourceLocation OpLoc,
7571                                           Expr *Condition,
7572                                           Expr *LHSExpr,
7573                                           Expr *RHSExpr) {
7574   BinaryOperatorKind CondOpcode;
7575   Expr *CondRHS;
7576 
7577   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7578     return;
7579   if (!ExprLooksBoolean(CondRHS))
7580     return;
7581 
7582   // The condition is an arithmetic binary expression, with a right-
7583   // hand side that looks boolean, so warn.
7584 
7585   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7586       << Condition->getSourceRange()
7587       << BinaryOperator::getOpcodeStr(CondOpcode);
7588 
7589   SuggestParentheses(
7590       Self, OpLoc,
7591       Self.PDiag(diag::note_precedence_silence)
7592           << BinaryOperator::getOpcodeStr(CondOpcode),
7593       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7594 
7595   SuggestParentheses(Self, OpLoc,
7596                      Self.PDiag(diag::note_precedence_conditional_first),
7597                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7598 }
7599 
7600 /// Compute the nullability of a conditional expression.
7601 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7602                                               QualType LHSTy, QualType RHSTy,
7603                                               ASTContext &Ctx) {
7604   if (!ResTy->isAnyPointerType())
7605     return ResTy;
7606 
7607   auto GetNullability = [&Ctx](QualType Ty) {
7608     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7609     if (Kind)
7610       return *Kind;
7611     return NullabilityKind::Unspecified;
7612   };
7613 
7614   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7615   NullabilityKind MergedKind;
7616 
7617   // Compute nullability of a binary conditional expression.
7618   if (IsBin) {
7619     if (LHSKind == NullabilityKind::NonNull)
7620       MergedKind = NullabilityKind::NonNull;
7621     else
7622       MergedKind = RHSKind;
7623   // Compute nullability of a normal conditional expression.
7624   } else {
7625     if (LHSKind == NullabilityKind::Nullable ||
7626         RHSKind == NullabilityKind::Nullable)
7627       MergedKind = NullabilityKind::Nullable;
7628     else if (LHSKind == NullabilityKind::NonNull)
7629       MergedKind = RHSKind;
7630     else if (RHSKind == NullabilityKind::NonNull)
7631       MergedKind = LHSKind;
7632     else
7633       MergedKind = NullabilityKind::Unspecified;
7634   }
7635 
7636   // Return if ResTy already has the correct nullability.
7637   if (GetNullability(ResTy) == MergedKind)
7638     return ResTy;
7639 
7640   // Strip all nullability from ResTy.
7641   while (ResTy->getNullability(Ctx))
7642     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7643 
7644   // Create a new AttributedType with the new nullability kind.
7645   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7646   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7647 }
7648 
7649 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7650 /// in the case of a the GNU conditional expr extension.
7651 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7652                                     SourceLocation ColonLoc,
7653                                     Expr *CondExpr, Expr *LHSExpr,
7654                                     Expr *RHSExpr) {
7655   if (!getLangOpts().CPlusPlus) {
7656     // C cannot handle TypoExpr nodes in the condition because it
7657     // doesn't handle dependent types properly, so make sure any TypoExprs have
7658     // been dealt with before checking the operands.
7659     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7660     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7661     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7662 
7663     if (!CondResult.isUsable())
7664       return ExprError();
7665 
7666     if (LHSExpr) {
7667       if (!LHSResult.isUsable())
7668         return ExprError();
7669     }
7670 
7671     if (!RHSResult.isUsable())
7672       return ExprError();
7673 
7674     CondExpr = CondResult.get();
7675     LHSExpr = LHSResult.get();
7676     RHSExpr = RHSResult.get();
7677   }
7678 
7679   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7680   // was the condition.
7681   OpaqueValueExpr *opaqueValue = nullptr;
7682   Expr *commonExpr = nullptr;
7683   if (!LHSExpr) {
7684     commonExpr = CondExpr;
7685     // Lower out placeholder types first.  This is important so that we don't
7686     // try to capture a placeholder. This happens in few cases in C++; such
7687     // as Objective-C++'s dictionary subscripting syntax.
7688     if (commonExpr->hasPlaceholderType()) {
7689       ExprResult result = CheckPlaceholderExpr(commonExpr);
7690       if (!result.isUsable()) return ExprError();
7691       commonExpr = result.get();
7692     }
7693     // We usually want to apply unary conversions *before* saving, except
7694     // in the special case of a C++ l-value conditional.
7695     if (!(getLangOpts().CPlusPlus
7696           && !commonExpr->isTypeDependent()
7697           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7698           && commonExpr->isGLValue()
7699           && commonExpr->isOrdinaryOrBitFieldObject()
7700           && RHSExpr->isOrdinaryOrBitFieldObject()
7701           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7702       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7703       if (commonRes.isInvalid())
7704         return ExprError();
7705       commonExpr = commonRes.get();
7706     }
7707 
7708     // If the common expression is a class or array prvalue, materialize it
7709     // so that we can safely refer to it multiple times.
7710     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7711                                    commonExpr->getType()->isArrayType())) {
7712       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7713       if (MatExpr.isInvalid())
7714         return ExprError();
7715       commonExpr = MatExpr.get();
7716     }
7717 
7718     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7719                                                 commonExpr->getType(),
7720                                                 commonExpr->getValueKind(),
7721                                                 commonExpr->getObjectKind(),
7722                                                 commonExpr);
7723     LHSExpr = CondExpr = opaqueValue;
7724   }
7725 
7726   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7727   ExprValueKind VK = VK_RValue;
7728   ExprObjectKind OK = OK_Ordinary;
7729   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7730   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7731                                              VK, OK, QuestionLoc);
7732   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7733       RHS.isInvalid())
7734     return ExprError();
7735 
7736   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7737                                 RHS.get());
7738 
7739   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7740 
7741   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7742                                          Context);
7743 
7744   if (!commonExpr)
7745     return new (Context)
7746         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7747                             RHS.get(), result, VK, OK);
7748 
7749   return new (Context) BinaryConditionalOperator(
7750       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7751       ColonLoc, result, VK, OK);
7752 }
7753 
7754 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7755 // being closely modeled after the C99 spec:-). The odd characteristic of this
7756 // routine is it effectively iqnores the qualifiers on the top level pointee.
7757 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7758 // FIXME: add a couple examples in this comment.
7759 static Sema::AssignConvertType
7760 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7761   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7762   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7763 
7764   // get the "pointed to" type (ignoring qualifiers at the top level)
7765   const Type *lhptee, *rhptee;
7766   Qualifiers lhq, rhq;
7767   std::tie(lhptee, lhq) =
7768       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7769   std::tie(rhptee, rhq) =
7770       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7771 
7772   Sema::AssignConvertType ConvTy = Sema::Compatible;
7773 
7774   // C99 6.5.16.1p1: This following citation is common to constraints
7775   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7776   // qualifiers of the type *pointed to* by the right;
7777 
7778   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7779   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7780       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7781     // Ignore lifetime for further calculation.
7782     lhq.removeObjCLifetime();
7783     rhq.removeObjCLifetime();
7784   }
7785 
7786   if (!lhq.compatiblyIncludes(rhq)) {
7787     // Treat address-space mismatches as fatal.
7788     if (!lhq.isAddressSpaceSupersetOf(rhq))
7789       return Sema::IncompatiblePointerDiscardsQualifiers;
7790 
7791     // It's okay to add or remove GC or lifetime qualifiers when converting to
7792     // and from void*.
7793     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7794                         .compatiblyIncludes(
7795                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7796              && (lhptee->isVoidType() || rhptee->isVoidType()))
7797       ; // keep old
7798 
7799     // Treat lifetime mismatches as fatal.
7800     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7801       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7802 
7803     // For GCC/MS compatibility, other qualifier mismatches are treated
7804     // as still compatible in C.
7805     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7806   }
7807 
7808   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7809   // incomplete type and the other is a pointer to a qualified or unqualified
7810   // version of void...
7811   if (lhptee->isVoidType()) {
7812     if (rhptee->isIncompleteOrObjectType())
7813       return ConvTy;
7814 
7815     // As an extension, we allow cast to/from void* to function pointer.
7816     assert(rhptee->isFunctionType());
7817     return Sema::FunctionVoidPointer;
7818   }
7819 
7820   if (rhptee->isVoidType()) {
7821     if (lhptee->isIncompleteOrObjectType())
7822       return ConvTy;
7823 
7824     // As an extension, we allow cast to/from void* to function pointer.
7825     assert(lhptee->isFunctionType());
7826     return Sema::FunctionVoidPointer;
7827   }
7828 
7829   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7830   // unqualified versions of compatible types, ...
7831   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7832   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7833     // Check if the pointee types are compatible ignoring the sign.
7834     // We explicitly check for char so that we catch "char" vs
7835     // "unsigned char" on systems where "char" is unsigned.
7836     if (lhptee->isCharType())
7837       ltrans = S.Context.UnsignedCharTy;
7838     else if (lhptee->hasSignedIntegerRepresentation())
7839       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7840 
7841     if (rhptee->isCharType())
7842       rtrans = S.Context.UnsignedCharTy;
7843     else if (rhptee->hasSignedIntegerRepresentation())
7844       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7845 
7846     if (ltrans == rtrans) {
7847       // Types are compatible ignoring the sign. Qualifier incompatibility
7848       // takes priority over sign incompatibility because the sign
7849       // warning can be disabled.
7850       if (ConvTy != Sema::Compatible)
7851         return ConvTy;
7852 
7853       return Sema::IncompatiblePointerSign;
7854     }
7855 
7856     // If we are a multi-level pointer, it's possible that our issue is simply
7857     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7858     // the eventual target type is the same and the pointers have the same
7859     // level of indirection, this must be the issue.
7860     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7861       do {
7862         std::tie(lhptee, lhq) =
7863           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7864         std::tie(rhptee, rhq) =
7865           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7866 
7867         // Inconsistent address spaces at this point is invalid, even if the
7868         // address spaces would be compatible.
7869         // FIXME: This doesn't catch address space mismatches for pointers of
7870         // different nesting levels, like:
7871         //   __local int *** a;
7872         //   int ** b = a;
7873         // It's not clear how to actually determine when such pointers are
7874         // invalidly incompatible.
7875         if (lhq.getAddressSpace() != rhq.getAddressSpace())
7876           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
7877 
7878       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7879 
7880       if (lhptee == rhptee)
7881         return Sema::IncompatibleNestedPointerQualifiers;
7882     }
7883 
7884     // General pointer incompatibility takes priority over qualifiers.
7885     return Sema::IncompatiblePointer;
7886   }
7887   if (!S.getLangOpts().CPlusPlus &&
7888       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7889     return Sema::IncompatiblePointer;
7890   return ConvTy;
7891 }
7892 
7893 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7894 /// block pointer types are compatible or whether a block and normal pointer
7895 /// are compatible. It is more restrict than comparing two function pointer
7896 // types.
7897 static Sema::AssignConvertType
7898 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7899                                     QualType RHSType) {
7900   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7901   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7902 
7903   QualType lhptee, rhptee;
7904 
7905   // get the "pointed to" type (ignoring qualifiers at the top level)
7906   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7907   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7908 
7909   // In C++, the types have to match exactly.
7910   if (S.getLangOpts().CPlusPlus)
7911     return Sema::IncompatibleBlockPointer;
7912 
7913   Sema::AssignConvertType ConvTy = Sema::Compatible;
7914 
7915   // For blocks we enforce that qualifiers are identical.
7916   Qualifiers LQuals = lhptee.getLocalQualifiers();
7917   Qualifiers RQuals = rhptee.getLocalQualifiers();
7918   if (S.getLangOpts().OpenCL) {
7919     LQuals.removeAddressSpace();
7920     RQuals.removeAddressSpace();
7921   }
7922   if (LQuals != RQuals)
7923     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7924 
7925   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7926   // assignment.
7927   // The current behavior is similar to C++ lambdas. A block might be
7928   // assigned to a variable iff its return type and parameters are compatible
7929   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7930   // an assignment. Presumably it should behave in way that a function pointer
7931   // assignment does in C, so for each parameter and return type:
7932   //  * CVR and address space of LHS should be a superset of CVR and address
7933   //  space of RHS.
7934   //  * unqualified types should be compatible.
7935   if (S.getLangOpts().OpenCL) {
7936     if (!S.Context.typesAreBlockPointerCompatible(
7937             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7938             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7939       return Sema::IncompatibleBlockPointer;
7940   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7941     return Sema::IncompatibleBlockPointer;
7942 
7943   return ConvTy;
7944 }
7945 
7946 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7947 /// for assignment compatibility.
7948 static Sema::AssignConvertType
7949 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7950                                    QualType RHSType) {
7951   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7952   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7953 
7954   if (LHSType->isObjCBuiltinType()) {
7955     // Class is not compatible with ObjC object pointers.
7956     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7957         !RHSType->isObjCQualifiedClassType())
7958       return Sema::IncompatiblePointer;
7959     return Sema::Compatible;
7960   }
7961   if (RHSType->isObjCBuiltinType()) {
7962     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7963         !LHSType->isObjCQualifiedClassType())
7964       return Sema::IncompatiblePointer;
7965     return Sema::Compatible;
7966   }
7967   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7968   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7969 
7970   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7971       // make an exception for id<P>
7972       !LHSType->isObjCQualifiedIdType())
7973     return Sema::CompatiblePointerDiscardsQualifiers;
7974 
7975   if (S.Context.typesAreCompatible(LHSType, RHSType))
7976     return Sema::Compatible;
7977   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7978     return Sema::IncompatibleObjCQualifiedId;
7979   return Sema::IncompatiblePointer;
7980 }
7981 
7982 Sema::AssignConvertType
7983 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7984                                  QualType LHSType, QualType RHSType) {
7985   // Fake up an opaque expression.  We don't actually care about what
7986   // cast operations are required, so if CheckAssignmentConstraints
7987   // adds casts to this they'll be wasted, but fortunately that doesn't
7988   // usually happen on valid code.
7989   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7990   ExprResult RHSPtr = &RHSExpr;
7991   CastKind K;
7992 
7993   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7994 }
7995 
7996 /// This helper function returns true if QT is a vector type that has element
7997 /// type ElementType.
7998 static bool isVector(QualType QT, QualType ElementType) {
7999   if (const VectorType *VT = QT->getAs<VectorType>())
8000     return VT->getElementType() == ElementType;
8001   return false;
8002 }
8003 
8004 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8005 /// has code to accommodate several GCC extensions when type checking
8006 /// pointers. Here are some objectionable examples that GCC considers warnings:
8007 ///
8008 ///  int a, *pint;
8009 ///  short *pshort;
8010 ///  struct foo *pfoo;
8011 ///
8012 ///  pint = pshort; // warning: assignment from incompatible pointer type
8013 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8014 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8015 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8016 ///
8017 /// As a result, the code for dealing with pointers is more complex than the
8018 /// C99 spec dictates.
8019 ///
8020 /// Sets 'Kind' for any result kind except Incompatible.
8021 Sema::AssignConvertType
8022 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8023                                  CastKind &Kind, bool ConvertRHS) {
8024   QualType RHSType = RHS.get()->getType();
8025   QualType OrigLHSType = LHSType;
8026 
8027   // Get canonical types.  We're not formatting these types, just comparing
8028   // them.
8029   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8030   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8031 
8032   // Common case: no conversion required.
8033   if (LHSType == RHSType) {
8034     Kind = CK_NoOp;
8035     return Compatible;
8036   }
8037 
8038   // If we have an atomic type, try a non-atomic assignment, then just add an
8039   // atomic qualification step.
8040   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8041     Sema::AssignConvertType result =
8042       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8043     if (result != Compatible)
8044       return result;
8045     if (Kind != CK_NoOp && ConvertRHS)
8046       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8047     Kind = CK_NonAtomicToAtomic;
8048     return Compatible;
8049   }
8050 
8051   // If the left-hand side is a reference type, then we are in a
8052   // (rare!) case where we've allowed the use of references in C,
8053   // e.g., as a parameter type in a built-in function. In this case,
8054   // just make sure that the type referenced is compatible with the
8055   // right-hand side type. The caller is responsible for adjusting
8056   // LHSType so that the resulting expression does not have reference
8057   // type.
8058   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8059     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8060       Kind = CK_LValueBitCast;
8061       return Compatible;
8062     }
8063     return Incompatible;
8064   }
8065 
8066   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8067   // to the same ExtVector type.
8068   if (LHSType->isExtVectorType()) {
8069     if (RHSType->isExtVectorType())
8070       return Incompatible;
8071     if (RHSType->isArithmeticType()) {
8072       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8073       if (ConvertRHS)
8074         RHS = prepareVectorSplat(LHSType, RHS.get());
8075       Kind = CK_VectorSplat;
8076       return Compatible;
8077     }
8078   }
8079 
8080   // Conversions to or from vector type.
8081   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8082     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8083       // Allow assignments of an AltiVec vector type to an equivalent GCC
8084       // vector type and vice versa
8085       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8086         Kind = CK_BitCast;
8087         return Compatible;
8088       }
8089 
8090       // If we are allowing lax vector conversions, and LHS and RHS are both
8091       // vectors, the total size only needs to be the same. This is a bitcast;
8092       // no bits are changed but the result type is different.
8093       if (isLaxVectorConversion(RHSType, LHSType)) {
8094         Kind = CK_BitCast;
8095         return IncompatibleVectors;
8096       }
8097     }
8098 
8099     // When the RHS comes from another lax conversion (e.g. binops between
8100     // scalars and vectors) the result is canonicalized as a vector. When the
8101     // LHS is also a vector, the lax is allowed by the condition above. Handle
8102     // the case where LHS is a scalar.
8103     if (LHSType->isScalarType()) {
8104       const VectorType *VecType = RHSType->getAs<VectorType>();
8105       if (VecType && VecType->getNumElements() == 1 &&
8106           isLaxVectorConversion(RHSType, LHSType)) {
8107         ExprResult *VecExpr = &RHS;
8108         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8109         Kind = CK_BitCast;
8110         return Compatible;
8111       }
8112     }
8113 
8114     return Incompatible;
8115   }
8116 
8117   // Diagnose attempts to convert between __float128 and long double where
8118   // such conversions currently can't be handled.
8119   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8120     return Incompatible;
8121 
8122   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8123   // discards the imaginary part.
8124   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8125       !LHSType->getAs<ComplexType>())
8126     return Incompatible;
8127 
8128   // Arithmetic conversions.
8129   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8130       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8131     if (ConvertRHS)
8132       Kind = PrepareScalarCast(RHS, LHSType);
8133     return Compatible;
8134   }
8135 
8136   // Conversions to normal pointers.
8137   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8138     // U* -> T*
8139     if (isa<PointerType>(RHSType)) {
8140       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8141       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8142       if (AddrSpaceL != AddrSpaceR)
8143         Kind = CK_AddressSpaceConversion;
8144       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8145         Kind = CK_NoOp;
8146       else
8147         Kind = CK_BitCast;
8148       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8149     }
8150 
8151     // int -> T*
8152     if (RHSType->isIntegerType()) {
8153       Kind = CK_IntegralToPointer; // FIXME: null?
8154       return IntToPointer;
8155     }
8156 
8157     // C pointers are not compatible with ObjC object pointers,
8158     // with two exceptions:
8159     if (isa<ObjCObjectPointerType>(RHSType)) {
8160       //  - conversions to void*
8161       if (LHSPointer->getPointeeType()->isVoidType()) {
8162         Kind = CK_BitCast;
8163         return Compatible;
8164       }
8165 
8166       //  - conversions from 'Class' to the redefinition type
8167       if (RHSType->isObjCClassType() &&
8168           Context.hasSameType(LHSType,
8169                               Context.getObjCClassRedefinitionType())) {
8170         Kind = CK_BitCast;
8171         return Compatible;
8172       }
8173 
8174       Kind = CK_BitCast;
8175       return IncompatiblePointer;
8176     }
8177 
8178     // U^ -> void*
8179     if (RHSType->getAs<BlockPointerType>()) {
8180       if (LHSPointer->getPointeeType()->isVoidType()) {
8181         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8182         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8183                                 ->getPointeeType()
8184                                 .getAddressSpace();
8185         Kind =
8186             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8187         return Compatible;
8188       }
8189     }
8190 
8191     return Incompatible;
8192   }
8193 
8194   // Conversions to block pointers.
8195   if (isa<BlockPointerType>(LHSType)) {
8196     // U^ -> T^
8197     if (RHSType->isBlockPointerType()) {
8198       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8199                               ->getPointeeType()
8200                               .getAddressSpace();
8201       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8202                               ->getPointeeType()
8203                               .getAddressSpace();
8204       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8205       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8206     }
8207 
8208     // int or null -> T^
8209     if (RHSType->isIntegerType()) {
8210       Kind = CK_IntegralToPointer; // FIXME: null
8211       return IntToBlockPointer;
8212     }
8213 
8214     // id -> T^
8215     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8216       Kind = CK_AnyPointerToBlockPointerCast;
8217       return Compatible;
8218     }
8219 
8220     // void* -> T^
8221     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8222       if (RHSPT->getPointeeType()->isVoidType()) {
8223         Kind = CK_AnyPointerToBlockPointerCast;
8224         return Compatible;
8225       }
8226 
8227     return Incompatible;
8228   }
8229 
8230   // Conversions to Objective-C pointers.
8231   if (isa<ObjCObjectPointerType>(LHSType)) {
8232     // A* -> B*
8233     if (RHSType->isObjCObjectPointerType()) {
8234       Kind = CK_BitCast;
8235       Sema::AssignConvertType result =
8236         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8237       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8238           result == Compatible &&
8239           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8240         result = IncompatibleObjCWeakRef;
8241       return result;
8242     }
8243 
8244     // int or null -> A*
8245     if (RHSType->isIntegerType()) {
8246       Kind = CK_IntegralToPointer; // FIXME: null
8247       return IntToPointer;
8248     }
8249 
8250     // In general, C pointers are not compatible with ObjC object pointers,
8251     // with two exceptions:
8252     if (isa<PointerType>(RHSType)) {
8253       Kind = CK_CPointerToObjCPointerCast;
8254 
8255       //  - conversions from 'void*'
8256       if (RHSType->isVoidPointerType()) {
8257         return Compatible;
8258       }
8259 
8260       //  - conversions to 'Class' from its redefinition type
8261       if (LHSType->isObjCClassType() &&
8262           Context.hasSameType(RHSType,
8263                               Context.getObjCClassRedefinitionType())) {
8264         return Compatible;
8265       }
8266 
8267       return IncompatiblePointer;
8268     }
8269 
8270     // Only under strict condition T^ is compatible with an Objective-C pointer.
8271     if (RHSType->isBlockPointerType() &&
8272         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8273       if (ConvertRHS)
8274         maybeExtendBlockObject(RHS);
8275       Kind = CK_BlockPointerToObjCPointerCast;
8276       return Compatible;
8277     }
8278 
8279     return Incompatible;
8280   }
8281 
8282   // Conversions from pointers that are not covered by the above.
8283   if (isa<PointerType>(RHSType)) {
8284     // T* -> _Bool
8285     if (LHSType == Context.BoolTy) {
8286       Kind = CK_PointerToBoolean;
8287       return Compatible;
8288     }
8289 
8290     // T* -> int
8291     if (LHSType->isIntegerType()) {
8292       Kind = CK_PointerToIntegral;
8293       return PointerToInt;
8294     }
8295 
8296     return Incompatible;
8297   }
8298 
8299   // Conversions from Objective-C pointers that are not covered by the above.
8300   if (isa<ObjCObjectPointerType>(RHSType)) {
8301     // T* -> _Bool
8302     if (LHSType == Context.BoolTy) {
8303       Kind = CK_PointerToBoolean;
8304       return Compatible;
8305     }
8306 
8307     // T* -> int
8308     if (LHSType->isIntegerType()) {
8309       Kind = CK_PointerToIntegral;
8310       return PointerToInt;
8311     }
8312 
8313     return Incompatible;
8314   }
8315 
8316   // struct A -> struct B
8317   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8318     if (Context.typesAreCompatible(LHSType, RHSType)) {
8319       Kind = CK_NoOp;
8320       return Compatible;
8321     }
8322   }
8323 
8324   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8325     Kind = CK_IntToOCLSampler;
8326     return Compatible;
8327   }
8328 
8329   return Incompatible;
8330 }
8331 
8332 /// Constructs a transparent union from an expression that is
8333 /// used to initialize the transparent union.
8334 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8335                                       ExprResult &EResult, QualType UnionType,
8336                                       FieldDecl *Field) {
8337   // Build an initializer list that designates the appropriate member
8338   // of the transparent union.
8339   Expr *E = EResult.get();
8340   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8341                                                    E, SourceLocation());
8342   Initializer->setType(UnionType);
8343   Initializer->setInitializedFieldInUnion(Field);
8344 
8345   // Build a compound literal constructing a value of the transparent
8346   // union type from this initializer list.
8347   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8348   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8349                                         VK_RValue, Initializer, false);
8350 }
8351 
8352 Sema::AssignConvertType
8353 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8354                                                ExprResult &RHS) {
8355   QualType RHSType = RHS.get()->getType();
8356 
8357   // If the ArgType is a Union type, we want to handle a potential
8358   // transparent_union GCC extension.
8359   const RecordType *UT = ArgType->getAsUnionType();
8360   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8361     return Incompatible;
8362 
8363   // The field to initialize within the transparent union.
8364   RecordDecl *UD = UT->getDecl();
8365   FieldDecl *InitField = nullptr;
8366   // It's compatible if the expression matches any of the fields.
8367   for (auto *it : UD->fields()) {
8368     if (it->getType()->isPointerType()) {
8369       // If the transparent union contains a pointer type, we allow:
8370       // 1) void pointer
8371       // 2) null pointer constant
8372       if (RHSType->isPointerType())
8373         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8374           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8375           InitField = it;
8376           break;
8377         }
8378 
8379       if (RHS.get()->isNullPointerConstant(Context,
8380                                            Expr::NPC_ValueDependentIsNull)) {
8381         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8382                                 CK_NullToPointer);
8383         InitField = it;
8384         break;
8385       }
8386     }
8387 
8388     CastKind Kind;
8389     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8390           == Compatible) {
8391       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8392       InitField = it;
8393       break;
8394     }
8395   }
8396 
8397   if (!InitField)
8398     return Incompatible;
8399 
8400   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8401   return Compatible;
8402 }
8403 
8404 Sema::AssignConvertType
8405 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8406                                        bool Diagnose,
8407                                        bool DiagnoseCFAudited,
8408                                        bool ConvertRHS) {
8409   // We need to be able to tell the caller whether we diagnosed a problem, if
8410   // they ask us to issue diagnostics.
8411   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8412 
8413   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8414   // we can't avoid *all* modifications at the moment, so we need some somewhere
8415   // to put the updated value.
8416   ExprResult LocalRHS = CallerRHS;
8417   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8418 
8419   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8420     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8421       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8422           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8423         Diag(RHS.get()->getExprLoc(),
8424              diag::warn_noderef_to_dereferenceable_pointer)
8425             << RHS.get()->getSourceRange();
8426       }
8427     }
8428   }
8429 
8430   if (getLangOpts().CPlusPlus) {
8431     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8432       // C++ 5.17p3: If the left operand is not of class type, the
8433       // expression is implicitly converted (C++ 4) to the
8434       // cv-unqualified type of the left operand.
8435       QualType RHSType = RHS.get()->getType();
8436       if (Diagnose) {
8437         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8438                                         AA_Assigning);
8439       } else {
8440         ImplicitConversionSequence ICS =
8441             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8442                                   /*SuppressUserConversions=*/false,
8443                                   /*AllowExplicit=*/false,
8444                                   /*InOverloadResolution=*/false,
8445                                   /*CStyle=*/false,
8446                                   /*AllowObjCWritebackConversion=*/false);
8447         if (ICS.isFailure())
8448           return Incompatible;
8449         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8450                                         ICS, AA_Assigning);
8451       }
8452       if (RHS.isInvalid())
8453         return Incompatible;
8454       Sema::AssignConvertType result = Compatible;
8455       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8456           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8457         result = IncompatibleObjCWeakRef;
8458       return result;
8459     }
8460 
8461     // FIXME: Currently, we fall through and treat C++ classes like C
8462     // structures.
8463     // FIXME: We also fall through for atomics; not sure what should
8464     // happen there, though.
8465   } else if (RHS.get()->getType() == Context.OverloadTy) {
8466     // As a set of extensions to C, we support overloading on functions. These
8467     // functions need to be resolved here.
8468     DeclAccessPair DAP;
8469     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8470             RHS.get(), LHSType, /*Complain=*/false, DAP))
8471       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8472     else
8473       return Incompatible;
8474   }
8475 
8476   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8477   // a null pointer constant.
8478   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8479        LHSType->isBlockPointerType()) &&
8480       RHS.get()->isNullPointerConstant(Context,
8481                                        Expr::NPC_ValueDependentIsNull)) {
8482     if (Diagnose || ConvertRHS) {
8483       CastKind Kind;
8484       CXXCastPath Path;
8485       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8486                              /*IgnoreBaseAccess=*/false, Diagnose);
8487       if (ConvertRHS)
8488         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8489     }
8490     return Compatible;
8491   }
8492 
8493   // OpenCL queue_t type assignment.
8494   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8495                                  Context, Expr::NPC_ValueDependentIsNull)) {
8496     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8497     return Compatible;
8498   }
8499 
8500   // This check seems unnatural, however it is necessary to ensure the proper
8501   // conversion of functions/arrays. If the conversion were done for all
8502   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8503   // expressions that suppress this implicit conversion (&, sizeof).
8504   //
8505   // Suppress this for references: C++ 8.5.3p5.
8506   if (!LHSType->isReferenceType()) {
8507     // FIXME: We potentially allocate here even if ConvertRHS is false.
8508     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8509     if (RHS.isInvalid())
8510       return Incompatible;
8511   }
8512   CastKind Kind;
8513   Sema::AssignConvertType result =
8514     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8515 
8516   // C99 6.5.16.1p2: The value of the right operand is converted to the
8517   // type of the assignment expression.
8518   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8519   // so that we can use references in built-in functions even in C.
8520   // The getNonReferenceType() call makes sure that the resulting expression
8521   // does not have reference type.
8522   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8523     QualType Ty = LHSType.getNonLValueExprType(Context);
8524     Expr *E = RHS.get();
8525 
8526     // Check for various Objective-C errors. If we are not reporting
8527     // diagnostics and just checking for errors, e.g., during overload
8528     // resolution, return Incompatible to indicate the failure.
8529     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8530         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8531                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8532       if (!Diagnose)
8533         return Incompatible;
8534     }
8535     if (getLangOpts().ObjC &&
8536         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8537                                            E->getType(), E, Diagnose) ||
8538          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8539       if (!Diagnose)
8540         return Incompatible;
8541       // Replace the expression with a corrected version and continue so we
8542       // can find further errors.
8543       RHS = E;
8544       return Compatible;
8545     }
8546 
8547     if (ConvertRHS)
8548       RHS = ImpCastExprToType(E, Ty, Kind);
8549   }
8550 
8551   return result;
8552 }
8553 
8554 namespace {
8555 /// The original operand to an operator, prior to the application of the usual
8556 /// arithmetic conversions and converting the arguments of a builtin operator
8557 /// candidate.
8558 struct OriginalOperand {
8559   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8560     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8561       Op = MTE->GetTemporaryExpr();
8562     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8563       Op = BTE->getSubExpr();
8564     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8565       Orig = ICE->getSubExprAsWritten();
8566       Conversion = ICE->getConversionFunction();
8567     }
8568   }
8569 
8570   QualType getType() const { return Orig->getType(); }
8571 
8572   Expr *Orig;
8573   NamedDecl *Conversion;
8574 };
8575 }
8576 
8577 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8578                                ExprResult &RHS) {
8579   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8580 
8581   Diag(Loc, diag::err_typecheck_invalid_operands)
8582     << OrigLHS.getType() << OrigRHS.getType()
8583     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8584 
8585   // If a user-defined conversion was applied to either of the operands prior
8586   // to applying the built-in operator rules, tell the user about it.
8587   if (OrigLHS.Conversion) {
8588     Diag(OrigLHS.Conversion->getLocation(),
8589          diag::note_typecheck_invalid_operands_converted)
8590       << 0 << LHS.get()->getType();
8591   }
8592   if (OrigRHS.Conversion) {
8593     Diag(OrigRHS.Conversion->getLocation(),
8594          diag::note_typecheck_invalid_operands_converted)
8595       << 1 << RHS.get()->getType();
8596   }
8597 
8598   return QualType();
8599 }
8600 
8601 // Diagnose cases where a scalar was implicitly converted to a vector and
8602 // diagnose the underlying types. Otherwise, diagnose the error
8603 // as invalid vector logical operands for non-C++ cases.
8604 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8605                                             ExprResult &RHS) {
8606   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8607   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8608 
8609   bool LHSNatVec = LHSType->isVectorType();
8610   bool RHSNatVec = RHSType->isVectorType();
8611 
8612   if (!(LHSNatVec && RHSNatVec)) {
8613     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8614     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8615     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8616         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8617         << Vector->getSourceRange();
8618     return QualType();
8619   }
8620 
8621   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8622       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8623       << RHS.get()->getSourceRange();
8624 
8625   return QualType();
8626 }
8627 
8628 /// Try to convert a value of non-vector type to a vector type by converting
8629 /// the type to the element type of the vector and then performing a splat.
8630 /// If the language is OpenCL, we only use conversions that promote scalar
8631 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8632 /// for float->int.
8633 ///
8634 /// OpenCL V2.0 6.2.6.p2:
8635 /// An error shall occur if any scalar operand type has greater rank
8636 /// than the type of the vector element.
8637 ///
8638 /// \param scalar - if non-null, actually perform the conversions
8639 /// \return true if the operation fails (but without diagnosing the failure)
8640 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8641                                      QualType scalarTy,
8642                                      QualType vectorEltTy,
8643                                      QualType vectorTy,
8644                                      unsigned &DiagID) {
8645   // The conversion to apply to the scalar before splatting it,
8646   // if necessary.
8647   CastKind scalarCast = CK_NoOp;
8648 
8649   if (vectorEltTy->isIntegralType(S.Context)) {
8650     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8651         (scalarTy->isIntegerType() &&
8652          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8653       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8654       return true;
8655     }
8656     if (!scalarTy->isIntegralType(S.Context))
8657       return true;
8658     scalarCast = CK_IntegralCast;
8659   } else if (vectorEltTy->isRealFloatingType()) {
8660     if (scalarTy->isRealFloatingType()) {
8661       if (S.getLangOpts().OpenCL &&
8662           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8663         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8664         return true;
8665       }
8666       scalarCast = CK_FloatingCast;
8667     }
8668     else if (scalarTy->isIntegralType(S.Context))
8669       scalarCast = CK_IntegralToFloating;
8670     else
8671       return true;
8672   } else {
8673     return true;
8674   }
8675 
8676   // Adjust scalar if desired.
8677   if (scalar) {
8678     if (scalarCast != CK_NoOp)
8679       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8680     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8681   }
8682   return false;
8683 }
8684 
8685 /// Convert vector E to a vector with the same number of elements but different
8686 /// element type.
8687 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8688   const auto *VecTy = E->getType()->getAs<VectorType>();
8689   assert(VecTy && "Expression E must be a vector");
8690   QualType NewVecTy = S.Context.getVectorType(ElementType,
8691                                               VecTy->getNumElements(),
8692                                               VecTy->getVectorKind());
8693 
8694   // Look through the implicit cast. Return the subexpression if its type is
8695   // NewVecTy.
8696   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8697     if (ICE->getSubExpr()->getType() == NewVecTy)
8698       return ICE->getSubExpr();
8699 
8700   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8701   return S.ImpCastExprToType(E, NewVecTy, Cast);
8702 }
8703 
8704 /// Test if a (constant) integer Int can be casted to another integer type
8705 /// IntTy without losing precision.
8706 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8707                                       QualType OtherIntTy) {
8708   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8709 
8710   // Reject cases where the value of the Int is unknown as that would
8711   // possibly cause truncation, but accept cases where the scalar can be
8712   // demoted without loss of precision.
8713   Expr::EvalResult EVResult;
8714   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8715   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8716   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8717   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8718 
8719   if (CstInt) {
8720     // If the scalar is constant and is of a higher order and has more active
8721     // bits that the vector element type, reject it.
8722     llvm::APSInt Result = EVResult.Val.getInt();
8723     unsigned NumBits = IntSigned
8724                            ? (Result.isNegative() ? Result.getMinSignedBits()
8725                                                   : Result.getActiveBits())
8726                            : Result.getActiveBits();
8727     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8728       return true;
8729 
8730     // If the signedness of the scalar type and the vector element type
8731     // differs and the number of bits is greater than that of the vector
8732     // element reject it.
8733     return (IntSigned != OtherIntSigned &&
8734             NumBits > S.Context.getIntWidth(OtherIntTy));
8735   }
8736 
8737   // Reject cases where the value of the scalar is not constant and it's
8738   // order is greater than that of the vector element type.
8739   return (Order < 0);
8740 }
8741 
8742 /// Test if a (constant) integer Int can be casted to floating point type
8743 /// FloatTy without losing precision.
8744 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8745                                      QualType FloatTy) {
8746   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8747 
8748   // Determine if the integer constant can be expressed as a floating point
8749   // number of the appropriate type.
8750   Expr::EvalResult EVResult;
8751   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8752 
8753   uint64_t Bits = 0;
8754   if (CstInt) {
8755     // Reject constants that would be truncated if they were converted to
8756     // the floating point type. Test by simple to/from conversion.
8757     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8758     //        could be avoided if there was a convertFromAPInt method
8759     //        which could signal back if implicit truncation occurred.
8760     llvm::APSInt Result = EVResult.Val.getInt();
8761     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8762     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8763                            llvm::APFloat::rmTowardZero);
8764     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8765                              !IntTy->hasSignedIntegerRepresentation());
8766     bool Ignored = false;
8767     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8768                            &Ignored);
8769     if (Result != ConvertBack)
8770       return true;
8771   } else {
8772     // Reject types that cannot be fully encoded into the mantissa of
8773     // the float.
8774     Bits = S.Context.getTypeSize(IntTy);
8775     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8776         S.Context.getFloatTypeSemantics(FloatTy));
8777     if (Bits > FloatPrec)
8778       return true;
8779   }
8780 
8781   return false;
8782 }
8783 
8784 /// Attempt to convert and splat Scalar into a vector whose types matches
8785 /// Vector following GCC conversion rules. The rule is that implicit
8786 /// conversion can occur when Scalar can be casted to match Vector's element
8787 /// type without causing truncation of Scalar.
8788 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8789                                         ExprResult *Vector) {
8790   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8791   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8792   const VectorType *VT = VectorTy->getAs<VectorType>();
8793 
8794   assert(!isa<ExtVectorType>(VT) &&
8795          "ExtVectorTypes should not be handled here!");
8796 
8797   QualType VectorEltTy = VT->getElementType();
8798 
8799   // Reject cases where the vector element type or the scalar element type are
8800   // not integral or floating point types.
8801   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8802     return true;
8803 
8804   // The conversion to apply to the scalar before splatting it,
8805   // if necessary.
8806   CastKind ScalarCast = CK_NoOp;
8807 
8808   // Accept cases where the vector elements are integers and the scalar is
8809   // an integer.
8810   // FIXME: Notionally if the scalar was a floating point value with a precise
8811   //        integral representation, we could cast it to an appropriate integer
8812   //        type and then perform the rest of the checks here. GCC will perform
8813   //        this conversion in some cases as determined by the input language.
8814   //        We should accept it on a language independent basis.
8815   if (VectorEltTy->isIntegralType(S.Context) &&
8816       ScalarTy->isIntegralType(S.Context) &&
8817       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8818 
8819     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8820       return true;
8821 
8822     ScalarCast = CK_IntegralCast;
8823   } else if (VectorEltTy->isRealFloatingType()) {
8824     if (ScalarTy->isRealFloatingType()) {
8825 
8826       // Reject cases where the scalar type is not a constant and has a higher
8827       // Order than the vector element type.
8828       llvm::APFloat Result(0.0);
8829       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8830       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8831       if (!CstScalar && Order < 0)
8832         return true;
8833 
8834       // If the scalar cannot be safely casted to the vector element type,
8835       // reject it.
8836       if (CstScalar) {
8837         bool Truncated = false;
8838         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8839                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8840         if (Truncated)
8841           return true;
8842       }
8843 
8844       ScalarCast = CK_FloatingCast;
8845     } else if (ScalarTy->isIntegralType(S.Context)) {
8846       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8847         return true;
8848 
8849       ScalarCast = CK_IntegralToFloating;
8850     } else
8851       return true;
8852   }
8853 
8854   // Adjust scalar if desired.
8855   if (Scalar) {
8856     if (ScalarCast != CK_NoOp)
8857       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8858     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8859   }
8860   return false;
8861 }
8862 
8863 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8864                                    SourceLocation Loc, bool IsCompAssign,
8865                                    bool AllowBothBool,
8866                                    bool AllowBoolConversions) {
8867   if (!IsCompAssign) {
8868     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8869     if (LHS.isInvalid())
8870       return QualType();
8871   }
8872   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8873   if (RHS.isInvalid())
8874     return QualType();
8875 
8876   // For conversion purposes, we ignore any qualifiers.
8877   // For example, "const float" and "float" are equivalent.
8878   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8879   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8880 
8881   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8882   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8883   assert(LHSVecType || RHSVecType);
8884 
8885   // AltiVec-style "vector bool op vector bool" combinations are allowed
8886   // for some operators but not others.
8887   if (!AllowBothBool &&
8888       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8889       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8890     return InvalidOperands(Loc, LHS, RHS);
8891 
8892   // If the vector types are identical, return.
8893   if (Context.hasSameType(LHSType, RHSType))
8894     return LHSType;
8895 
8896   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8897   if (LHSVecType && RHSVecType &&
8898       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8899     if (isa<ExtVectorType>(LHSVecType)) {
8900       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8901       return LHSType;
8902     }
8903 
8904     if (!IsCompAssign)
8905       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8906     return RHSType;
8907   }
8908 
8909   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8910   // can be mixed, with the result being the non-bool type.  The non-bool
8911   // operand must have integer element type.
8912   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8913       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8914       (Context.getTypeSize(LHSVecType->getElementType()) ==
8915        Context.getTypeSize(RHSVecType->getElementType()))) {
8916     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8917         LHSVecType->getElementType()->isIntegerType() &&
8918         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8919       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8920       return LHSType;
8921     }
8922     if (!IsCompAssign &&
8923         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8924         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8925         RHSVecType->getElementType()->isIntegerType()) {
8926       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8927       return RHSType;
8928     }
8929   }
8930 
8931   // If there's a vector type and a scalar, try to convert the scalar to
8932   // the vector element type and splat.
8933   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8934   if (!RHSVecType) {
8935     if (isa<ExtVectorType>(LHSVecType)) {
8936       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8937                                     LHSVecType->getElementType(), LHSType,
8938                                     DiagID))
8939         return LHSType;
8940     } else {
8941       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8942         return LHSType;
8943     }
8944   }
8945   if (!LHSVecType) {
8946     if (isa<ExtVectorType>(RHSVecType)) {
8947       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8948                                     LHSType, RHSVecType->getElementType(),
8949                                     RHSType, DiagID))
8950         return RHSType;
8951     } else {
8952       if (LHS.get()->getValueKind() == VK_LValue ||
8953           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8954         return RHSType;
8955     }
8956   }
8957 
8958   // FIXME: The code below also handles conversion between vectors and
8959   // non-scalars, we should break this down into fine grained specific checks
8960   // and emit proper diagnostics.
8961   QualType VecType = LHSVecType ? LHSType : RHSType;
8962   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8963   QualType OtherType = LHSVecType ? RHSType : LHSType;
8964   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8965   if (isLaxVectorConversion(OtherType, VecType)) {
8966     // If we're allowing lax vector conversions, only the total (data) size
8967     // needs to be the same. For non compound assignment, if one of the types is
8968     // scalar, the result is always the vector type.
8969     if (!IsCompAssign) {
8970       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8971       return VecType;
8972     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8973     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8974     // type. Note that this is already done by non-compound assignments in
8975     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8976     // <1 x T> -> T. The result is also a vector type.
8977     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8978                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8979       ExprResult *RHSExpr = &RHS;
8980       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8981       return VecType;
8982     }
8983   }
8984 
8985   // Okay, the expression is invalid.
8986 
8987   // If there's a non-vector, non-real operand, diagnose that.
8988   if ((!RHSVecType && !RHSType->isRealType()) ||
8989       (!LHSVecType && !LHSType->isRealType())) {
8990     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8991       << LHSType << RHSType
8992       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8993     return QualType();
8994   }
8995 
8996   // OpenCL V1.1 6.2.6.p1:
8997   // If the operands are of more than one vector type, then an error shall
8998   // occur. Implicit conversions between vector types are not permitted, per
8999   // section 6.2.1.
9000   if (getLangOpts().OpenCL &&
9001       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9002       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9003     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9004                                                            << RHSType;
9005     return QualType();
9006   }
9007 
9008 
9009   // If there is a vector type that is not a ExtVector and a scalar, we reach
9010   // this point if scalar could not be converted to the vector's element type
9011   // without truncation.
9012   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9013       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9014     QualType Scalar = LHSVecType ? RHSType : LHSType;
9015     QualType Vector = LHSVecType ? LHSType : RHSType;
9016     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9017     Diag(Loc,
9018          diag::err_typecheck_vector_not_convertable_implict_truncation)
9019         << ScalarOrVector << Scalar << Vector;
9020 
9021     return QualType();
9022   }
9023 
9024   // Otherwise, use the generic diagnostic.
9025   Diag(Loc, DiagID)
9026     << LHSType << RHSType
9027     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9028   return QualType();
9029 }
9030 
9031 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9032 // expression.  These are mainly cases where the null pointer is used as an
9033 // integer instead of a pointer.
9034 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9035                                 SourceLocation Loc, bool IsCompare) {
9036   // The canonical way to check for a GNU null is with isNullPointerConstant,
9037   // but we use a bit of a hack here for speed; this is a relatively
9038   // hot path, and isNullPointerConstant is slow.
9039   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9040   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9041 
9042   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9043 
9044   // Avoid analyzing cases where the result will either be invalid (and
9045   // diagnosed as such) or entirely valid and not something to warn about.
9046   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9047       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9048     return;
9049 
9050   // Comparison operations would not make sense with a null pointer no matter
9051   // what the other expression is.
9052   if (!IsCompare) {
9053     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9054         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9055         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9056     return;
9057   }
9058 
9059   // The rest of the operations only make sense with a null pointer
9060   // if the other expression is a pointer.
9061   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9062       NonNullType->canDecayToPointerType())
9063     return;
9064 
9065   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9066       << LHSNull /* LHS is NULL */ << NonNullType
9067       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9068 }
9069 
9070 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
9071                                           SourceLocation Loc) {
9072   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9073   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9074   if (!LUE || !RUE)
9075     return;
9076   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9077       RUE->getKind() != UETT_SizeOf)
9078     return;
9079 
9080   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9081   QualType LHSTy = LHSArg->getType();
9082   QualType RHSTy;
9083 
9084   if (RUE->isArgumentType())
9085     RHSTy = RUE->getArgumentType();
9086   else
9087     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9088 
9089   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
9090     return;
9091   if (LHSTy->getPointeeType().getCanonicalType() != RHSTy.getCanonicalType())
9092     return;
9093 
9094   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9095   if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9096     if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9097       S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9098           << LHSArgDecl;
9099   }
9100 }
9101 
9102 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9103                                                ExprResult &RHS,
9104                                                SourceLocation Loc, bool IsDiv) {
9105   // Check for division/remainder by zero.
9106   Expr::EvalResult RHSValue;
9107   if (!RHS.get()->isValueDependent() &&
9108       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9109       RHSValue.Val.getInt() == 0)
9110     S.DiagRuntimeBehavior(Loc, RHS.get(),
9111                           S.PDiag(diag::warn_remainder_division_by_zero)
9112                             << IsDiv << RHS.get()->getSourceRange());
9113 }
9114 
9115 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9116                                            SourceLocation Loc,
9117                                            bool IsCompAssign, bool IsDiv) {
9118   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9119 
9120   if (LHS.get()->getType()->isVectorType() ||
9121       RHS.get()->getType()->isVectorType())
9122     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9123                                /*AllowBothBool*/getLangOpts().AltiVec,
9124                                /*AllowBoolConversions*/false);
9125 
9126   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9127   if (LHS.isInvalid() || RHS.isInvalid())
9128     return QualType();
9129 
9130 
9131   if (compType.isNull() || !compType->isArithmeticType())
9132     return InvalidOperands(Loc, LHS, RHS);
9133   if (IsDiv) {
9134     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9135     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9136   }
9137   return compType;
9138 }
9139 
9140 QualType Sema::CheckRemainderOperands(
9141   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9142   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9143 
9144   if (LHS.get()->getType()->isVectorType() ||
9145       RHS.get()->getType()->isVectorType()) {
9146     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9147         RHS.get()->getType()->hasIntegerRepresentation())
9148       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9149                                  /*AllowBothBool*/getLangOpts().AltiVec,
9150                                  /*AllowBoolConversions*/false);
9151     return InvalidOperands(Loc, LHS, RHS);
9152   }
9153 
9154   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9155   if (LHS.isInvalid() || RHS.isInvalid())
9156     return QualType();
9157 
9158   if (compType.isNull() || !compType->isIntegerType())
9159     return InvalidOperands(Loc, LHS, RHS);
9160   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9161   return compType;
9162 }
9163 
9164 /// Diagnose invalid arithmetic on two void pointers.
9165 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9166                                                 Expr *LHSExpr, Expr *RHSExpr) {
9167   S.Diag(Loc, S.getLangOpts().CPlusPlus
9168                 ? diag::err_typecheck_pointer_arith_void_type
9169                 : diag::ext_gnu_void_ptr)
9170     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9171                             << RHSExpr->getSourceRange();
9172 }
9173 
9174 /// Diagnose invalid arithmetic on a void pointer.
9175 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9176                                             Expr *Pointer) {
9177   S.Diag(Loc, S.getLangOpts().CPlusPlus
9178                 ? diag::err_typecheck_pointer_arith_void_type
9179                 : diag::ext_gnu_void_ptr)
9180     << 0 /* one pointer */ << Pointer->getSourceRange();
9181 }
9182 
9183 /// Diagnose invalid arithmetic on a null pointer.
9184 ///
9185 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9186 /// idiom, which we recognize as a GNU extension.
9187 ///
9188 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9189                                             Expr *Pointer, bool IsGNUIdiom) {
9190   if (IsGNUIdiom)
9191     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9192       << Pointer->getSourceRange();
9193   else
9194     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9195       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9196 }
9197 
9198 /// Diagnose invalid arithmetic on two function pointers.
9199 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9200                                                     Expr *LHS, Expr *RHS) {
9201   assert(LHS->getType()->isAnyPointerType());
9202   assert(RHS->getType()->isAnyPointerType());
9203   S.Diag(Loc, S.getLangOpts().CPlusPlus
9204                 ? diag::err_typecheck_pointer_arith_function_type
9205                 : diag::ext_gnu_ptr_func_arith)
9206     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9207     // We only show the second type if it differs from the first.
9208     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9209                                                    RHS->getType())
9210     << RHS->getType()->getPointeeType()
9211     << LHS->getSourceRange() << RHS->getSourceRange();
9212 }
9213 
9214 /// Diagnose invalid arithmetic on a function pointer.
9215 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9216                                                 Expr *Pointer) {
9217   assert(Pointer->getType()->isAnyPointerType());
9218   S.Diag(Loc, S.getLangOpts().CPlusPlus
9219                 ? diag::err_typecheck_pointer_arith_function_type
9220                 : diag::ext_gnu_ptr_func_arith)
9221     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9222     << 0 /* one pointer, so only one type */
9223     << Pointer->getSourceRange();
9224 }
9225 
9226 /// Emit error if Operand is incomplete pointer type
9227 ///
9228 /// \returns True if pointer has incomplete type
9229 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9230                                                  Expr *Operand) {
9231   QualType ResType = Operand->getType();
9232   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9233     ResType = ResAtomicType->getValueType();
9234 
9235   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9236   QualType PointeeTy = ResType->getPointeeType();
9237   return S.RequireCompleteType(Loc, PointeeTy,
9238                                diag::err_typecheck_arithmetic_incomplete_type,
9239                                PointeeTy, Operand->getSourceRange());
9240 }
9241 
9242 /// Check the validity of an arithmetic pointer operand.
9243 ///
9244 /// If the operand has pointer type, this code will check for pointer types
9245 /// which are invalid in arithmetic operations. These will be diagnosed
9246 /// appropriately, including whether or not the use is supported as an
9247 /// extension.
9248 ///
9249 /// \returns True when the operand is valid to use (even if as an extension).
9250 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9251                                             Expr *Operand) {
9252   QualType ResType = Operand->getType();
9253   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9254     ResType = ResAtomicType->getValueType();
9255 
9256   if (!ResType->isAnyPointerType()) return true;
9257 
9258   QualType PointeeTy = ResType->getPointeeType();
9259   if (PointeeTy->isVoidType()) {
9260     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9261     return !S.getLangOpts().CPlusPlus;
9262   }
9263   if (PointeeTy->isFunctionType()) {
9264     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9265     return !S.getLangOpts().CPlusPlus;
9266   }
9267 
9268   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9269 
9270   return true;
9271 }
9272 
9273 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9274 /// operands.
9275 ///
9276 /// This routine will diagnose any invalid arithmetic on pointer operands much
9277 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9278 /// for emitting a single diagnostic even for operations where both LHS and RHS
9279 /// are (potentially problematic) pointers.
9280 ///
9281 /// \returns True when the operand is valid to use (even if as an extension).
9282 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9283                                                 Expr *LHSExpr, Expr *RHSExpr) {
9284   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9285   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9286   if (!isLHSPointer && !isRHSPointer) return true;
9287 
9288   QualType LHSPointeeTy, RHSPointeeTy;
9289   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9290   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9291 
9292   // if both are pointers check if operation is valid wrt address spaces
9293   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9294     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9295     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9296     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9297       S.Diag(Loc,
9298              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9299           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9300           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9301       return false;
9302     }
9303   }
9304 
9305   // Check for arithmetic on pointers to incomplete types.
9306   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9307   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9308   if (isLHSVoidPtr || isRHSVoidPtr) {
9309     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9310     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9311     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9312 
9313     return !S.getLangOpts().CPlusPlus;
9314   }
9315 
9316   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9317   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9318   if (isLHSFuncPtr || isRHSFuncPtr) {
9319     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9320     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9321                                                                 RHSExpr);
9322     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9323 
9324     return !S.getLangOpts().CPlusPlus;
9325   }
9326 
9327   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9328     return false;
9329   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9330     return false;
9331 
9332   return true;
9333 }
9334 
9335 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9336 /// literal.
9337 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9338                                   Expr *LHSExpr, Expr *RHSExpr) {
9339   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9340   Expr* IndexExpr = RHSExpr;
9341   if (!StrExpr) {
9342     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9343     IndexExpr = LHSExpr;
9344   }
9345 
9346   bool IsStringPlusInt = StrExpr &&
9347       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9348   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9349     return;
9350 
9351   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9352   Self.Diag(OpLoc, diag::warn_string_plus_int)
9353       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9354 
9355   // Only print a fixit for "str" + int, not for int + "str".
9356   if (IndexExpr == RHSExpr) {
9357     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9358     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9359         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9360         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9361         << FixItHint::CreateInsertion(EndLoc, "]");
9362   } else
9363     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9364 }
9365 
9366 /// Emit a warning when adding a char literal to a string.
9367 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9368                                    Expr *LHSExpr, Expr *RHSExpr) {
9369   const Expr *StringRefExpr = LHSExpr;
9370   const CharacterLiteral *CharExpr =
9371       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9372 
9373   if (!CharExpr) {
9374     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9375     StringRefExpr = RHSExpr;
9376   }
9377 
9378   if (!CharExpr || !StringRefExpr)
9379     return;
9380 
9381   const QualType StringType = StringRefExpr->getType();
9382 
9383   // Return if not a PointerType.
9384   if (!StringType->isAnyPointerType())
9385     return;
9386 
9387   // Return if not a CharacterType.
9388   if (!StringType->getPointeeType()->isAnyCharacterType())
9389     return;
9390 
9391   ASTContext &Ctx = Self.getASTContext();
9392   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9393 
9394   const QualType CharType = CharExpr->getType();
9395   if (!CharType->isAnyCharacterType() &&
9396       CharType->isIntegerType() &&
9397       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9398     Self.Diag(OpLoc, diag::warn_string_plus_char)
9399         << DiagRange << Ctx.CharTy;
9400   } else {
9401     Self.Diag(OpLoc, diag::warn_string_plus_char)
9402         << DiagRange << CharExpr->getType();
9403   }
9404 
9405   // Only print a fixit for str + char, not for char + str.
9406   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9407     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9408     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9409         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9410         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9411         << FixItHint::CreateInsertion(EndLoc, "]");
9412   } else {
9413     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9414   }
9415 }
9416 
9417 /// Emit error when two pointers are incompatible.
9418 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9419                                            Expr *LHSExpr, Expr *RHSExpr) {
9420   assert(LHSExpr->getType()->isAnyPointerType());
9421   assert(RHSExpr->getType()->isAnyPointerType());
9422   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9423     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9424     << RHSExpr->getSourceRange();
9425 }
9426 
9427 // C99 6.5.6
9428 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9429                                      SourceLocation Loc, BinaryOperatorKind Opc,
9430                                      QualType* CompLHSTy) {
9431   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9432 
9433   if (LHS.get()->getType()->isVectorType() ||
9434       RHS.get()->getType()->isVectorType()) {
9435     QualType compType = CheckVectorOperands(
9436         LHS, RHS, Loc, CompLHSTy,
9437         /*AllowBothBool*/getLangOpts().AltiVec,
9438         /*AllowBoolConversions*/getLangOpts().ZVector);
9439     if (CompLHSTy) *CompLHSTy = compType;
9440     return compType;
9441   }
9442 
9443   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9444   if (LHS.isInvalid() || RHS.isInvalid())
9445     return QualType();
9446 
9447   // Diagnose "string literal" '+' int and string '+' "char literal".
9448   if (Opc == BO_Add) {
9449     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9450     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9451   }
9452 
9453   // handle the common case first (both operands are arithmetic).
9454   if (!compType.isNull() && compType->isArithmeticType()) {
9455     if (CompLHSTy) *CompLHSTy = compType;
9456     return compType;
9457   }
9458 
9459   // Type-checking.  Ultimately the pointer's going to be in PExp;
9460   // note that we bias towards the LHS being the pointer.
9461   Expr *PExp = LHS.get(), *IExp = RHS.get();
9462 
9463   bool isObjCPointer;
9464   if (PExp->getType()->isPointerType()) {
9465     isObjCPointer = false;
9466   } else if (PExp->getType()->isObjCObjectPointerType()) {
9467     isObjCPointer = true;
9468   } else {
9469     std::swap(PExp, IExp);
9470     if (PExp->getType()->isPointerType()) {
9471       isObjCPointer = false;
9472     } else if (PExp->getType()->isObjCObjectPointerType()) {
9473       isObjCPointer = true;
9474     } else {
9475       return InvalidOperands(Loc, LHS, RHS);
9476     }
9477   }
9478   assert(PExp->getType()->isAnyPointerType());
9479 
9480   if (!IExp->getType()->isIntegerType())
9481     return InvalidOperands(Loc, LHS, RHS);
9482 
9483   // Adding to a null pointer results in undefined behavior.
9484   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9485           Context, Expr::NPC_ValueDependentIsNotNull)) {
9486     // In C++ adding zero to a null pointer is defined.
9487     Expr::EvalResult KnownVal;
9488     if (!getLangOpts().CPlusPlus ||
9489         (!IExp->isValueDependent() &&
9490          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9491           KnownVal.Val.getInt() != 0))) {
9492       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9493       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9494           Context, BO_Add, PExp, IExp);
9495       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9496     }
9497   }
9498 
9499   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9500     return QualType();
9501 
9502   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9503     return QualType();
9504 
9505   // Check array bounds for pointer arithemtic
9506   CheckArrayAccess(PExp, IExp);
9507 
9508   if (CompLHSTy) {
9509     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9510     if (LHSTy.isNull()) {
9511       LHSTy = LHS.get()->getType();
9512       if (LHSTy->isPromotableIntegerType())
9513         LHSTy = Context.getPromotedIntegerType(LHSTy);
9514     }
9515     *CompLHSTy = LHSTy;
9516   }
9517 
9518   return PExp->getType();
9519 }
9520 
9521 // C99 6.5.6
9522 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9523                                         SourceLocation Loc,
9524                                         QualType* CompLHSTy) {
9525   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9526 
9527   if (LHS.get()->getType()->isVectorType() ||
9528       RHS.get()->getType()->isVectorType()) {
9529     QualType compType = CheckVectorOperands(
9530         LHS, RHS, Loc, CompLHSTy,
9531         /*AllowBothBool*/getLangOpts().AltiVec,
9532         /*AllowBoolConversions*/getLangOpts().ZVector);
9533     if (CompLHSTy) *CompLHSTy = compType;
9534     return compType;
9535   }
9536 
9537   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9538   if (LHS.isInvalid() || RHS.isInvalid())
9539     return QualType();
9540 
9541   // Enforce type constraints: C99 6.5.6p3.
9542 
9543   // Handle the common case first (both operands are arithmetic).
9544   if (!compType.isNull() && compType->isArithmeticType()) {
9545     if (CompLHSTy) *CompLHSTy = compType;
9546     return compType;
9547   }
9548 
9549   // Either ptr - int   or   ptr - ptr.
9550   if (LHS.get()->getType()->isAnyPointerType()) {
9551     QualType lpointee = LHS.get()->getType()->getPointeeType();
9552 
9553     // Diagnose bad cases where we step over interface counts.
9554     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9555         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9556       return QualType();
9557 
9558     // The result type of a pointer-int computation is the pointer type.
9559     if (RHS.get()->getType()->isIntegerType()) {
9560       // Subtracting from a null pointer should produce a warning.
9561       // The last argument to the diagnose call says this doesn't match the
9562       // GNU int-to-pointer idiom.
9563       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9564                                            Expr::NPC_ValueDependentIsNotNull)) {
9565         // In C++ adding zero to a null pointer is defined.
9566         Expr::EvalResult KnownVal;
9567         if (!getLangOpts().CPlusPlus ||
9568             (!RHS.get()->isValueDependent() &&
9569              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9570               KnownVal.Val.getInt() != 0))) {
9571           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9572         }
9573       }
9574 
9575       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9576         return QualType();
9577 
9578       // Check array bounds for pointer arithemtic
9579       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9580                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9581 
9582       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9583       return LHS.get()->getType();
9584     }
9585 
9586     // Handle pointer-pointer subtractions.
9587     if (const PointerType *RHSPTy
9588           = RHS.get()->getType()->getAs<PointerType>()) {
9589       QualType rpointee = RHSPTy->getPointeeType();
9590 
9591       if (getLangOpts().CPlusPlus) {
9592         // Pointee types must be the same: C++ [expr.add]
9593         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9594           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9595         }
9596       } else {
9597         // Pointee types must be compatible C99 6.5.6p3
9598         if (!Context.typesAreCompatible(
9599                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9600                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9601           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9602           return QualType();
9603         }
9604       }
9605 
9606       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9607                                                LHS.get(), RHS.get()))
9608         return QualType();
9609 
9610       // FIXME: Add warnings for nullptr - ptr.
9611 
9612       // The pointee type may have zero size.  As an extension, a structure or
9613       // union may have zero size or an array may have zero length.  In this
9614       // case subtraction does not make sense.
9615       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9616         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9617         if (ElementSize.isZero()) {
9618           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9619             << rpointee.getUnqualifiedType()
9620             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9621         }
9622       }
9623 
9624       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9625       return Context.getPointerDiffType();
9626     }
9627   }
9628 
9629   return InvalidOperands(Loc, LHS, RHS);
9630 }
9631 
9632 static bool isScopedEnumerationType(QualType T) {
9633   if (const EnumType *ET = T->getAs<EnumType>())
9634     return ET->getDecl()->isScoped();
9635   return false;
9636 }
9637 
9638 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9639                                    SourceLocation Loc, BinaryOperatorKind Opc,
9640                                    QualType LHSType) {
9641   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9642   // so skip remaining warnings as we don't want to modify values within Sema.
9643   if (S.getLangOpts().OpenCL)
9644     return;
9645 
9646   // Check right/shifter operand
9647   Expr::EvalResult RHSResult;
9648   if (RHS.get()->isValueDependent() ||
9649       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9650     return;
9651   llvm::APSInt Right = RHSResult.Val.getInt();
9652 
9653   if (Right.isNegative()) {
9654     S.DiagRuntimeBehavior(Loc, RHS.get(),
9655                           S.PDiag(diag::warn_shift_negative)
9656                             << RHS.get()->getSourceRange());
9657     return;
9658   }
9659   llvm::APInt LeftBits(Right.getBitWidth(),
9660                        S.Context.getTypeSize(LHS.get()->getType()));
9661   if (Right.uge(LeftBits)) {
9662     S.DiagRuntimeBehavior(Loc, RHS.get(),
9663                           S.PDiag(diag::warn_shift_gt_typewidth)
9664                             << RHS.get()->getSourceRange());
9665     return;
9666   }
9667   if (Opc != BO_Shl)
9668     return;
9669 
9670   // When left shifting an ICE which is signed, we can check for overflow which
9671   // according to C++ standards prior to C++2a has undefined behavior
9672   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9673   // more than the maximum value representable in the result type, so never
9674   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9675   // expression is still probably a bug.)
9676   Expr::EvalResult LHSResult;
9677   if (LHS.get()->isValueDependent() ||
9678       LHSType->hasUnsignedIntegerRepresentation() ||
9679       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9680     return;
9681   llvm::APSInt Left = LHSResult.Val.getInt();
9682 
9683   // If LHS does not have a signed type and non-negative value
9684   // then, the behavior is undefined before C++2a. Warn about it.
9685   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9686       !S.getLangOpts().CPlusPlus2a) {
9687     S.DiagRuntimeBehavior(Loc, LHS.get(),
9688                           S.PDiag(diag::warn_shift_lhs_negative)
9689                             << LHS.get()->getSourceRange());
9690     return;
9691   }
9692 
9693   llvm::APInt ResultBits =
9694       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9695   if (LeftBits.uge(ResultBits))
9696     return;
9697   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9698   Result = Result.shl(Right);
9699 
9700   // Print the bit representation of the signed integer as an unsigned
9701   // hexadecimal number.
9702   SmallString<40> HexResult;
9703   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9704 
9705   // If we are only missing a sign bit, this is less likely to result in actual
9706   // bugs -- if the result is cast back to an unsigned type, it will have the
9707   // expected value. Thus we place this behind a different warning that can be
9708   // turned off separately if needed.
9709   if (LeftBits == ResultBits - 1) {
9710     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9711         << HexResult << LHSType
9712         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9713     return;
9714   }
9715 
9716   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9717     << HexResult.str() << Result.getMinSignedBits() << LHSType
9718     << Left.getBitWidth() << LHS.get()->getSourceRange()
9719     << RHS.get()->getSourceRange();
9720 }
9721 
9722 /// Return the resulting type when a vector is shifted
9723 ///        by a scalar or vector shift amount.
9724 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9725                                  SourceLocation Loc, bool IsCompAssign) {
9726   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9727   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9728       !LHS.get()->getType()->isVectorType()) {
9729     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9730       << RHS.get()->getType() << LHS.get()->getType()
9731       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9732     return QualType();
9733   }
9734 
9735   if (!IsCompAssign) {
9736     LHS = S.UsualUnaryConversions(LHS.get());
9737     if (LHS.isInvalid()) return QualType();
9738   }
9739 
9740   RHS = S.UsualUnaryConversions(RHS.get());
9741   if (RHS.isInvalid()) return QualType();
9742 
9743   QualType LHSType = LHS.get()->getType();
9744   // Note that LHS might be a scalar because the routine calls not only in
9745   // OpenCL case.
9746   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9747   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9748 
9749   // Note that RHS might not be a vector.
9750   QualType RHSType = RHS.get()->getType();
9751   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9752   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9753 
9754   // The operands need to be integers.
9755   if (!LHSEleType->isIntegerType()) {
9756     S.Diag(Loc, diag::err_typecheck_expect_int)
9757       << LHS.get()->getType() << LHS.get()->getSourceRange();
9758     return QualType();
9759   }
9760 
9761   if (!RHSEleType->isIntegerType()) {
9762     S.Diag(Loc, diag::err_typecheck_expect_int)
9763       << RHS.get()->getType() << RHS.get()->getSourceRange();
9764     return QualType();
9765   }
9766 
9767   if (!LHSVecTy) {
9768     assert(RHSVecTy);
9769     if (IsCompAssign)
9770       return RHSType;
9771     if (LHSEleType != RHSEleType) {
9772       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9773       LHSEleType = RHSEleType;
9774     }
9775     QualType VecTy =
9776         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9777     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9778     LHSType = VecTy;
9779   } else if (RHSVecTy) {
9780     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9781     // are applied component-wise. So if RHS is a vector, then ensure
9782     // that the number of elements is the same as LHS...
9783     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9784       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9785         << LHS.get()->getType() << RHS.get()->getType()
9786         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9787       return QualType();
9788     }
9789     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9790       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9791       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9792       if (LHSBT != RHSBT &&
9793           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9794         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9795             << LHS.get()->getType() << RHS.get()->getType()
9796             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9797       }
9798     }
9799   } else {
9800     // ...else expand RHS to match the number of elements in LHS.
9801     QualType VecTy =
9802       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9803     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9804   }
9805 
9806   return LHSType;
9807 }
9808 
9809 // C99 6.5.7
9810 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9811                                   SourceLocation Loc, BinaryOperatorKind Opc,
9812                                   bool IsCompAssign) {
9813   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9814 
9815   // Vector shifts promote their scalar inputs to vector type.
9816   if (LHS.get()->getType()->isVectorType() ||
9817       RHS.get()->getType()->isVectorType()) {
9818     if (LangOpts.ZVector) {
9819       // The shift operators for the z vector extensions work basically
9820       // like general shifts, except that neither the LHS nor the RHS is
9821       // allowed to be a "vector bool".
9822       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9823         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9824           return InvalidOperands(Loc, LHS, RHS);
9825       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9826         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9827           return InvalidOperands(Loc, LHS, RHS);
9828     }
9829     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9830   }
9831 
9832   // Shifts don't perform usual arithmetic conversions, they just do integer
9833   // promotions on each operand. C99 6.5.7p3
9834 
9835   // For the LHS, do usual unary conversions, but then reset them away
9836   // if this is a compound assignment.
9837   ExprResult OldLHS = LHS;
9838   LHS = UsualUnaryConversions(LHS.get());
9839   if (LHS.isInvalid())
9840     return QualType();
9841   QualType LHSType = LHS.get()->getType();
9842   if (IsCompAssign) LHS = OldLHS;
9843 
9844   // The RHS is simpler.
9845   RHS = UsualUnaryConversions(RHS.get());
9846   if (RHS.isInvalid())
9847     return QualType();
9848   QualType RHSType = RHS.get()->getType();
9849 
9850   // C99 6.5.7p2: Each of the operands shall have integer type.
9851   if (!LHSType->hasIntegerRepresentation() ||
9852       !RHSType->hasIntegerRepresentation())
9853     return InvalidOperands(Loc, LHS, RHS);
9854 
9855   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9856   // hasIntegerRepresentation() above instead of this.
9857   if (isScopedEnumerationType(LHSType) ||
9858       isScopedEnumerationType(RHSType)) {
9859     return InvalidOperands(Loc, LHS, RHS);
9860   }
9861   // Sanity-check shift operands
9862   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9863 
9864   // "The type of the result is that of the promoted left operand."
9865   return LHSType;
9866 }
9867 
9868 /// If two different enums are compared, raise a warning.
9869 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9870                                 Expr *RHS) {
9871   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9872   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9873 
9874   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9875   if (!LHSEnumType)
9876     return;
9877   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9878   if (!RHSEnumType)
9879     return;
9880 
9881   // Ignore anonymous enums.
9882   if (!LHSEnumType->getDecl()->getIdentifier() &&
9883       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9884     return;
9885   if (!RHSEnumType->getDecl()->getIdentifier() &&
9886       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9887     return;
9888 
9889   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9890     return;
9891 
9892   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9893       << LHSStrippedType << RHSStrippedType
9894       << LHS->getSourceRange() << RHS->getSourceRange();
9895 }
9896 
9897 /// Diagnose bad pointer comparisons.
9898 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9899                                               ExprResult &LHS, ExprResult &RHS,
9900                                               bool IsError) {
9901   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9902                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9903     << LHS.get()->getType() << RHS.get()->getType()
9904     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9905 }
9906 
9907 /// Returns false if the pointers are converted to a composite type,
9908 /// true otherwise.
9909 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9910                                            ExprResult &LHS, ExprResult &RHS) {
9911   // C++ [expr.rel]p2:
9912   //   [...] Pointer conversions (4.10) and qualification
9913   //   conversions (4.4) are performed on pointer operands (or on
9914   //   a pointer operand and a null pointer constant) to bring
9915   //   them to their composite pointer type. [...]
9916   //
9917   // C++ [expr.eq]p1 uses the same notion for (in)equality
9918   // comparisons of pointers.
9919 
9920   QualType LHSType = LHS.get()->getType();
9921   QualType RHSType = RHS.get()->getType();
9922   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9923          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9924 
9925   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9926   if (T.isNull()) {
9927     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9928         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9929       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9930     else
9931       S.InvalidOperands(Loc, LHS, RHS);
9932     return true;
9933   }
9934 
9935   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9936   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9937   return false;
9938 }
9939 
9940 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9941                                                     ExprResult &LHS,
9942                                                     ExprResult &RHS,
9943                                                     bool IsError) {
9944   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9945                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9946     << LHS.get()->getType() << RHS.get()->getType()
9947     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9948 }
9949 
9950 static bool isObjCObjectLiteral(ExprResult &E) {
9951   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9952   case Stmt::ObjCArrayLiteralClass:
9953   case Stmt::ObjCDictionaryLiteralClass:
9954   case Stmt::ObjCStringLiteralClass:
9955   case Stmt::ObjCBoxedExprClass:
9956     return true;
9957   default:
9958     // Note that ObjCBoolLiteral is NOT an object literal!
9959     return false;
9960   }
9961 }
9962 
9963 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9964   const ObjCObjectPointerType *Type =
9965     LHS->getType()->getAs<ObjCObjectPointerType>();
9966 
9967   // If this is not actually an Objective-C object, bail out.
9968   if (!Type)
9969     return false;
9970 
9971   // Get the LHS object's interface type.
9972   QualType InterfaceType = Type->getPointeeType();
9973 
9974   // If the RHS isn't an Objective-C object, bail out.
9975   if (!RHS->getType()->isObjCObjectPointerType())
9976     return false;
9977 
9978   // Try to find the -isEqual: method.
9979   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9980   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9981                                                       InterfaceType,
9982                                                       /*IsInstance=*/true);
9983   if (!Method) {
9984     if (Type->isObjCIdType()) {
9985       // For 'id', just check the global pool.
9986       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9987                                                   /*receiverId=*/true);
9988     } else {
9989       // Check protocols.
9990       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9991                                              /*IsInstance=*/true);
9992     }
9993   }
9994 
9995   if (!Method)
9996     return false;
9997 
9998   QualType T = Method->parameters()[0]->getType();
9999   if (!T->isObjCObjectPointerType())
10000     return false;
10001 
10002   QualType R = Method->getReturnType();
10003   if (!R->isScalarType())
10004     return false;
10005 
10006   return true;
10007 }
10008 
10009 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10010   FromE = FromE->IgnoreParenImpCasts();
10011   switch (FromE->getStmtClass()) {
10012     default:
10013       break;
10014     case Stmt::ObjCStringLiteralClass:
10015       // "string literal"
10016       return LK_String;
10017     case Stmt::ObjCArrayLiteralClass:
10018       // "array literal"
10019       return LK_Array;
10020     case Stmt::ObjCDictionaryLiteralClass:
10021       // "dictionary literal"
10022       return LK_Dictionary;
10023     case Stmt::BlockExprClass:
10024       return LK_Block;
10025     case Stmt::ObjCBoxedExprClass: {
10026       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10027       switch (Inner->getStmtClass()) {
10028         case Stmt::IntegerLiteralClass:
10029         case Stmt::FloatingLiteralClass:
10030         case Stmt::CharacterLiteralClass:
10031         case Stmt::ObjCBoolLiteralExprClass:
10032         case Stmt::CXXBoolLiteralExprClass:
10033           // "numeric literal"
10034           return LK_Numeric;
10035         case Stmt::ImplicitCastExprClass: {
10036           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10037           // Boolean literals can be represented by implicit casts.
10038           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10039             return LK_Numeric;
10040           break;
10041         }
10042         default:
10043           break;
10044       }
10045       return LK_Boxed;
10046     }
10047   }
10048   return LK_None;
10049 }
10050 
10051 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10052                                           ExprResult &LHS, ExprResult &RHS,
10053                                           BinaryOperator::Opcode Opc){
10054   Expr *Literal;
10055   Expr *Other;
10056   if (isObjCObjectLiteral(LHS)) {
10057     Literal = LHS.get();
10058     Other = RHS.get();
10059   } else {
10060     Literal = RHS.get();
10061     Other = LHS.get();
10062   }
10063 
10064   // Don't warn on comparisons against nil.
10065   Other = Other->IgnoreParenCasts();
10066   if (Other->isNullPointerConstant(S.getASTContext(),
10067                                    Expr::NPC_ValueDependentIsNotNull))
10068     return;
10069 
10070   // This should be kept in sync with warn_objc_literal_comparison.
10071   // LK_String should always be after the other literals, since it has its own
10072   // warning flag.
10073   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10074   assert(LiteralKind != Sema::LK_Block);
10075   if (LiteralKind == Sema::LK_None) {
10076     llvm_unreachable("Unknown Objective-C object literal kind");
10077   }
10078 
10079   if (LiteralKind == Sema::LK_String)
10080     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10081       << Literal->getSourceRange();
10082   else
10083     S.Diag(Loc, diag::warn_objc_literal_comparison)
10084       << LiteralKind << Literal->getSourceRange();
10085 
10086   if (BinaryOperator::isEqualityOp(Opc) &&
10087       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10088     SourceLocation Start = LHS.get()->getBeginLoc();
10089     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10090     CharSourceRange OpRange =
10091       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10092 
10093     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10094       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10095       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10096       << FixItHint::CreateInsertion(End, "]");
10097   }
10098 }
10099 
10100 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10101 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10102                                            ExprResult &RHS, SourceLocation Loc,
10103                                            BinaryOperatorKind Opc) {
10104   // Check that left hand side is !something.
10105   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10106   if (!UO || UO->getOpcode() != UO_LNot) return;
10107 
10108   // Only check if the right hand side is non-bool arithmetic type.
10109   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10110 
10111   // Make sure that the something in !something is not bool.
10112   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10113   if (SubExpr->isKnownToHaveBooleanValue()) return;
10114 
10115   // Emit warning.
10116   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10117   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10118       << Loc << IsBitwiseOp;
10119 
10120   // First note suggest !(x < y)
10121   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10122   SourceLocation FirstClose = RHS.get()->getEndLoc();
10123   FirstClose = S.getLocForEndOfToken(FirstClose);
10124   if (FirstClose.isInvalid())
10125     FirstOpen = SourceLocation();
10126   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10127       << IsBitwiseOp
10128       << FixItHint::CreateInsertion(FirstOpen, "(")
10129       << FixItHint::CreateInsertion(FirstClose, ")");
10130 
10131   // Second note suggests (!x) < y
10132   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10133   SourceLocation SecondClose = LHS.get()->getEndLoc();
10134   SecondClose = S.getLocForEndOfToken(SecondClose);
10135   if (SecondClose.isInvalid())
10136     SecondOpen = SourceLocation();
10137   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10138       << FixItHint::CreateInsertion(SecondOpen, "(")
10139       << FixItHint::CreateInsertion(SecondClose, ")");
10140 }
10141 
10142 // Get the decl for a simple expression: a reference to a variable,
10143 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10144 static ValueDecl *getCompareDecl(Expr *E) {
10145   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10146     return DR->getDecl();
10147   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10148     if (Ivar->isFreeIvar())
10149       return Ivar->getDecl();
10150   }
10151   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10152     if (Mem->isImplicitAccess())
10153       return Mem->getMemberDecl();
10154   }
10155   return nullptr;
10156 }
10157 
10158 /// Diagnose some forms of syntactically-obvious tautological comparison.
10159 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10160                                            Expr *LHS, Expr *RHS,
10161                                            BinaryOperatorKind Opc) {
10162   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10163   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10164 
10165   QualType LHSType = LHS->getType();
10166   QualType RHSType = RHS->getType();
10167   if (LHSType->hasFloatingRepresentation() ||
10168       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10169       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10170       S.inTemplateInstantiation())
10171     return;
10172 
10173   // Comparisons between two array types are ill-formed for operator<=>, so
10174   // we shouldn't emit any additional warnings about it.
10175   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10176     return;
10177 
10178   // For non-floating point types, check for self-comparisons of the form
10179   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10180   // often indicate logic errors in the program.
10181   //
10182   // NOTE: Don't warn about comparison expressions resulting from macro
10183   // expansion. Also don't warn about comparisons which are only self
10184   // comparisons within a template instantiation. The warnings should catch
10185   // obvious cases in the definition of the template anyways. The idea is to
10186   // warn when the typed comparison operator will always evaluate to the same
10187   // result.
10188   ValueDecl *DL = getCompareDecl(LHSStripped);
10189   ValueDecl *DR = getCompareDecl(RHSStripped);
10190 
10191   // Used for indexing into %select in warn_comparison_always
10192   enum {
10193     AlwaysConstant,
10194     AlwaysTrue,
10195     AlwaysFalse,
10196     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10197   };
10198   if (DL && DR && declaresSameEntity(DL, DR)) {
10199     unsigned Result;
10200     switch (Opc) {
10201     case BO_EQ: case BO_LE: case BO_GE:
10202       Result = AlwaysTrue;
10203       break;
10204     case BO_NE: case BO_LT: case BO_GT:
10205       Result = AlwaysFalse;
10206       break;
10207     case BO_Cmp:
10208       Result = AlwaysEqual;
10209       break;
10210     default:
10211       Result = AlwaysConstant;
10212       break;
10213     }
10214     S.DiagRuntimeBehavior(Loc, nullptr,
10215                           S.PDiag(diag::warn_comparison_always)
10216                               << 0 /*self-comparison*/
10217                               << Result);
10218   } else if (DL && DR &&
10219              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10220              !DL->isWeak() && !DR->isWeak()) {
10221     // What is it always going to evaluate to?
10222     unsigned Result;
10223     switch(Opc) {
10224     case BO_EQ: // e.g. array1 == array2
10225       Result = AlwaysFalse;
10226       break;
10227     case BO_NE: // e.g. array1 != array2
10228       Result = AlwaysTrue;
10229       break;
10230     default: // e.g. array1 <= array2
10231       // The best we can say is 'a constant'
10232       Result = AlwaysConstant;
10233       break;
10234     }
10235     S.DiagRuntimeBehavior(Loc, nullptr,
10236                           S.PDiag(diag::warn_comparison_always)
10237                               << 1 /*array comparison*/
10238                               << Result);
10239   }
10240 
10241   if (isa<CastExpr>(LHSStripped))
10242     LHSStripped = LHSStripped->IgnoreParenCasts();
10243   if (isa<CastExpr>(RHSStripped))
10244     RHSStripped = RHSStripped->IgnoreParenCasts();
10245 
10246   // Warn about comparisons against a string constant (unless the other
10247   // operand is null); the user probably wants strcmp.
10248   Expr *LiteralString = nullptr;
10249   Expr *LiteralStringStripped = nullptr;
10250   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10251       !RHSStripped->isNullPointerConstant(S.Context,
10252                                           Expr::NPC_ValueDependentIsNull)) {
10253     LiteralString = LHS;
10254     LiteralStringStripped = LHSStripped;
10255   } else if ((isa<StringLiteral>(RHSStripped) ||
10256               isa<ObjCEncodeExpr>(RHSStripped)) &&
10257              !LHSStripped->isNullPointerConstant(S.Context,
10258                                           Expr::NPC_ValueDependentIsNull)) {
10259     LiteralString = RHS;
10260     LiteralStringStripped = RHSStripped;
10261   }
10262 
10263   if (LiteralString) {
10264     S.DiagRuntimeBehavior(Loc, nullptr,
10265                           S.PDiag(diag::warn_stringcompare)
10266                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10267                               << LiteralString->getSourceRange());
10268   }
10269 }
10270 
10271 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10272   switch (CK) {
10273   default: {
10274 #ifndef NDEBUG
10275     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10276                  << "\n";
10277 #endif
10278     llvm_unreachable("unhandled cast kind");
10279   }
10280   case CK_UserDefinedConversion:
10281     return ICK_Identity;
10282   case CK_LValueToRValue:
10283     return ICK_Lvalue_To_Rvalue;
10284   case CK_ArrayToPointerDecay:
10285     return ICK_Array_To_Pointer;
10286   case CK_FunctionToPointerDecay:
10287     return ICK_Function_To_Pointer;
10288   case CK_IntegralCast:
10289     return ICK_Integral_Conversion;
10290   case CK_FloatingCast:
10291     return ICK_Floating_Conversion;
10292   case CK_IntegralToFloating:
10293   case CK_FloatingToIntegral:
10294     return ICK_Floating_Integral;
10295   case CK_IntegralComplexCast:
10296   case CK_FloatingComplexCast:
10297   case CK_FloatingComplexToIntegralComplex:
10298   case CK_IntegralComplexToFloatingComplex:
10299     return ICK_Complex_Conversion;
10300   case CK_FloatingComplexToReal:
10301   case CK_FloatingRealToComplex:
10302   case CK_IntegralComplexToReal:
10303   case CK_IntegralRealToComplex:
10304     return ICK_Complex_Real;
10305   }
10306 }
10307 
10308 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10309                                              QualType FromType,
10310                                              SourceLocation Loc) {
10311   // Check for a narrowing implicit conversion.
10312   StandardConversionSequence SCS;
10313   SCS.setAsIdentityConversion();
10314   SCS.setToType(0, FromType);
10315   SCS.setToType(1, ToType);
10316   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10317     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10318 
10319   APValue PreNarrowingValue;
10320   QualType PreNarrowingType;
10321   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10322                                PreNarrowingType,
10323                                /*IgnoreFloatToIntegralConversion*/ true)) {
10324   case NK_Dependent_Narrowing:
10325     // Implicit conversion to a narrower type, but the expression is
10326     // value-dependent so we can't tell whether it's actually narrowing.
10327   case NK_Not_Narrowing:
10328     return false;
10329 
10330   case NK_Constant_Narrowing:
10331     // Implicit conversion to a narrower type, and the value is not a constant
10332     // expression.
10333     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10334         << /*Constant*/ 1
10335         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10336     return true;
10337 
10338   case NK_Variable_Narrowing:
10339     // Implicit conversion to a narrower type, and the value is not a constant
10340     // expression.
10341   case NK_Type_Narrowing:
10342     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10343         << /*Constant*/ 0 << FromType << ToType;
10344     // TODO: It's not a constant expression, but what if the user intended it
10345     // to be? Can we produce notes to help them figure out why it isn't?
10346     return true;
10347   }
10348   llvm_unreachable("unhandled case in switch");
10349 }
10350 
10351 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10352                                                          ExprResult &LHS,
10353                                                          ExprResult &RHS,
10354                                                          SourceLocation Loc) {
10355   using CCT = ComparisonCategoryType;
10356 
10357   QualType LHSType = LHS.get()->getType();
10358   QualType RHSType = RHS.get()->getType();
10359   // Dig out the original argument type and expression before implicit casts
10360   // were applied. These are the types/expressions we need to check the
10361   // [expr.spaceship] requirements against.
10362   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10363   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10364   QualType LHSStrippedType = LHSStripped.get()->getType();
10365   QualType RHSStrippedType = RHSStripped.get()->getType();
10366 
10367   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10368   // other is not, the program is ill-formed.
10369   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10370     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10371     return QualType();
10372   }
10373 
10374   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10375                     RHSStrippedType->isEnumeralType();
10376   if (NumEnumArgs == 1) {
10377     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10378     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10379     if (OtherTy->hasFloatingRepresentation()) {
10380       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10381       return QualType();
10382     }
10383   }
10384   if (NumEnumArgs == 2) {
10385     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10386     // type E, the operator yields the result of converting the operands
10387     // to the underlying type of E and applying <=> to the converted operands.
10388     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10389       S.InvalidOperands(Loc, LHS, RHS);
10390       return QualType();
10391     }
10392     QualType IntType =
10393         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10394     assert(IntType->isArithmeticType());
10395 
10396     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10397     // promote the boolean type, and all other promotable integer types, to
10398     // avoid this.
10399     if (IntType->isPromotableIntegerType())
10400       IntType = S.Context.getPromotedIntegerType(IntType);
10401 
10402     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10403     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10404     LHSType = RHSType = IntType;
10405   }
10406 
10407   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10408   // usual arithmetic conversions are applied to the operands.
10409   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10410   if (LHS.isInvalid() || RHS.isInvalid())
10411     return QualType();
10412   if (Type.isNull())
10413     return S.InvalidOperands(Loc, LHS, RHS);
10414   assert(Type->isArithmeticType() || Type->isEnumeralType());
10415 
10416   bool HasNarrowing = checkThreeWayNarrowingConversion(
10417       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10418   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10419                                                    RHS.get()->getBeginLoc());
10420   if (HasNarrowing)
10421     return QualType();
10422 
10423   assert(!Type.isNull() && "composite type for <=> has not been set");
10424 
10425   auto TypeKind = [&]() {
10426     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10427       if (CT->getElementType()->hasFloatingRepresentation())
10428         return CCT::WeakEquality;
10429       return CCT::StrongEquality;
10430     }
10431     if (Type->isIntegralOrEnumerationType())
10432       return CCT::StrongOrdering;
10433     if (Type->hasFloatingRepresentation())
10434       return CCT::PartialOrdering;
10435     llvm_unreachable("other types are unimplemented");
10436   }();
10437 
10438   return S.CheckComparisonCategoryType(TypeKind, Loc);
10439 }
10440 
10441 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10442                                                  ExprResult &RHS,
10443                                                  SourceLocation Loc,
10444                                                  BinaryOperatorKind Opc) {
10445   if (Opc == BO_Cmp)
10446     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10447 
10448   // C99 6.5.8p3 / C99 6.5.9p4
10449   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10450   if (LHS.isInvalid() || RHS.isInvalid())
10451     return QualType();
10452   if (Type.isNull())
10453     return S.InvalidOperands(Loc, LHS, RHS);
10454   assert(Type->isArithmeticType() || Type->isEnumeralType());
10455 
10456   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10457 
10458   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10459     return S.InvalidOperands(Loc, LHS, RHS);
10460 
10461   // Check for comparisons of floating point operands using != and ==.
10462   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10463     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10464 
10465   // The result of comparisons is 'bool' in C++, 'int' in C.
10466   return S.Context.getLogicalOperationType();
10467 }
10468 
10469 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10470   if (!NullE.get()->getType()->isAnyPointerType())
10471     return;
10472   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10473   if (!E.get()->getType()->isAnyPointerType() &&
10474       E.get()->isNullPointerConstant(Context,
10475                                      Expr::NPC_ValueDependentIsNotNull) ==
10476         Expr::NPCK_ZeroExpression) {
10477     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10478       if (CL->getValue() == 0)
10479         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10480             << NullValue
10481             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10482                                             NullValue ? "NULL" : "(void *)0");
10483     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10484         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10485         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10486         if (T == Context.CharTy)
10487           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10488               << NullValue
10489               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10490                                               NullValue ? "NULL" : "(void *)0");
10491       }
10492   }
10493 }
10494 
10495 // C99 6.5.8, C++ [expr.rel]
10496 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10497                                     SourceLocation Loc,
10498                                     BinaryOperatorKind Opc) {
10499   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10500   bool IsThreeWay = Opc == BO_Cmp;
10501   auto IsAnyPointerType = [](ExprResult E) {
10502     QualType Ty = E.get()->getType();
10503     return Ty->isPointerType() || Ty->isMemberPointerType();
10504   };
10505 
10506   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10507   // type, array-to-pointer, ..., conversions are performed on both operands to
10508   // bring them to their composite type.
10509   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10510   // any type-related checks.
10511   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10512     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10513     if (LHS.isInvalid())
10514       return QualType();
10515     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10516     if (RHS.isInvalid())
10517       return QualType();
10518   } else {
10519     LHS = DefaultLvalueConversion(LHS.get());
10520     if (LHS.isInvalid())
10521       return QualType();
10522     RHS = DefaultLvalueConversion(RHS.get());
10523     if (RHS.isInvalid())
10524       return QualType();
10525   }
10526 
10527   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10528   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10529     CheckPtrComparisonWithNullChar(LHS, RHS);
10530     CheckPtrComparisonWithNullChar(RHS, LHS);
10531   }
10532 
10533   // Handle vector comparisons separately.
10534   if (LHS.get()->getType()->isVectorType() ||
10535       RHS.get()->getType()->isVectorType())
10536     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10537 
10538   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10539   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10540 
10541   QualType LHSType = LHS.get()->getType();
10542   QualType RHSType = RHS.get()->getType();
10543   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10544       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10545     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10546 
10547   const Expr::NullPointerConstantKind LHSNullKind =
10548       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10549   const Expr::NullPointerConstantKind RHSNullKind =
10550       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10551   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10552   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10553 
10554   auto computeResultTy = [&]() {
10555     if (Opc != BO_Cmp)
10556       return Context.getLogicalOperationType();
10557     assert(getLangOpts().CPlusPlus);
10558     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10559 
10560     QualType CompositeTy = LHS.get()->getType();
10561     assert(!CompositeTy->isReferenceType());
10562 
10563     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10564       return CheckComparisonCategoryType(Kind, Loc);
10565     };
10566 
10567     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10568     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10569     // result is of type std::strong_equality
10570     if (CompositeTy->isFunctionPointerType() ||
10571         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10572       // FIXME: consider making the function pointer case produce
10573       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10574       // and direction polls
10575       return buildResultTy(ComparisonCategoryType::StrongEquality);
10576 
10577     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10578     // pointer type, p <=> q is of type std::strong_ordering.
10579     if (CompositeTy->isPointerType()) {
10580       // P0946R0: Comparisons between a null pointer constant and an object
10581       // pointer result in std::strong_equality
10582       if (LHSIsNull != RHSIsNull)
10583         return buildResultTy(ComparisonCategoryType::StrongEquality);
10584       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10585     }
10586     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10587     // TODO: Extend support for operator<=> to ObjC types.
10588     return InvalidOperands(Loc, LHS, RHS);
10589   };
10590 
10591 
10592   if (!IsRelational && LHSIsNull != RHSIsNull) {
10593     bool IsEquality = Opc == BO_EQ;
10594     if (RHSIsNull)
10595       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10596                                    RHS.get()->getSourceRange());
10597     else
10598       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10599                                    LHS.get()->getSourceRange());
10600   }
10601 
10602   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10603       (RHSType->isIntegerType() && !RHSIsNull)) {
10604     // Skip normal pointer conversion checks in this case; we have better
10605     // diagnostics for this below.
10606   } else if (getLangOpts().CPlusPlus) {
10607     // Equality comparison of a function pointer to a void pointer is invalid,
10608     // but we allow it as an extension.
10609     // FIXME: If we really want to allow this, should it be part of composite
10610     // pointer type computation so it works in conditionals too?
10611     if (!IsRelational &&
10612         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10613          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10614       // This is a gcc extension compatibility comparison.
10615       // In a SFINAE context, we treat this as a hard error to maintain
10616       // conformance with the C++ standard.
10617       diagnoseFunctionPointerToVoidComparison(
10618           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10619 
10620       if (isSFINAEContext())
10621         return QualType();
10622 
10623       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10624       return computeResultTy();
10625     }
10626 
10627     // C++ [expr.eq]p2:
10628     //   If at least one operand is a pointer [...] bring them to their
10629     //   composite pointer type.
10630     // C++ [expr.spaceship]p6
10631     //  If at least one of the operands is of pointer type, [...] bring them
10632     //  to their composite pointer type.
10633     // C++ [expr.rel]p2:
10634     //   If both operands are pointers, [...] bring them to their composite
10635     //   pointer type.
10636     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10637             (IsRelational ? 2 : 1) &&
10638         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10639                                          RHSType->isObjCObjectPointerType()))) {
10640       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10641         return QualType();
10642       return computeResultTy();
10643     }
10644   } else if (LHSType->isPointerType() &&
10645              RHSType->isPointerType()) { // C99 6.5.8p2
10646     // All of the following pointer-related warnings are GCC extensions, except
10647     // when handling null pointer constants.
10648     QualType LCanPointeeTy =
10649       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10650     QualType RCanPointeeTy =
10651       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10652 
10653     // C99 6.5.9p2 and C99 6.5.8p2
10654     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10655                                    RCanPointeeTy.getUnqualifiedType())) {
10656       // Valid unless a relational comparison of function pointers
10657       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10658         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10659           << LHSType << RHSType << LHS.get()->getSourceRange()
10660           << RHS.get()->getSourceRange();
10661       }
10662     } else if (!IsRelational &&
10663                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10664       // Valid unless comparison between non-null pointer and function pointer
10665       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10666           && !LHSIsNull && !RHSIsNull)
10667         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10668                                                 /*isError*/false);
10669     } else {
10670       // Invalid
10671       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10672     }
10673     if (LCanPointeeTy != RCanPointeeTy) {
10674       // Treat NULL constant as a special case in OpenCL.
10675       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10676         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10677         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10678           Diag(Loc,
10679                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10680               << LHSType << RHSType << 0 /* comparison */
10681               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10682         }
10683       }
10684       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10685       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10686       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10687                                                : CK_BitCast;
10688       if (LHSIsNull && !RHSIsNull)
10689         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10690       else
10691         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10692     }
10693     return computeResultTy();
10694   }
10695 
10696   if (getLangOpts().CPlusPlus) {
10697     // C++ [expr.eq]p4:
10698     //   Two operands of type std::nullptr_t or one operand of type
10699     //   std::nullptr_t and the other a null pointer constant compare equal.
10700     if (!IsRelational && LHSIsNull && RHSIsNull) {
10701       if (LHSType->isNullPtrType()) {
10702         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10703         return computeResultTy();
10704       }
10705       if (RHSType->isNullPtrType()) {
10706         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10707         return computeResultTy();
10708       }
10709     }
10710 
10711     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10712     // These aren't covered by the composite pointer type rules.
10713     if (!IsRelational && RHSType->isNullPtrType() &&
10714         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10715       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10716       return computeResultTy();
10717     }
10718     if (!IsRelational && LHSType->isNullPtrType() &&
10719         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10720       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10721       return computeResultTy();
10722     }
10723 
10724     if (IsRelational &&
10725         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10726          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10727       // HACK: Relational comparison of nullptr_t against a pointer type is
10728       // invalid per DR583, but we allow it within std::less<> and friends,
10729       // since otherwise common uses of it break.
10730       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10731       // friends to have std::nullptr_t overload candidates.
10732       DeclContext *DC = CurContext;
10733       if (isa<FunctionDecl>(DC))
10734         DC = DC->getParent();
10735       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10736         if (CTSD->isInStdNamespace() &&
10737             llvm::StringSwitch<bool>(CTSD->getName())
10738                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10739                 .Default(false)) {
10740           if (RHSType->isNullPtrType())
10741             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10742           else
10743             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10744           return computeResultTy();
10745         }
10746       }
10747     }
10748 
10749     // C++ [expr.eq]p2:
10750     //   If at least one operand is a pointer to member, [...] bring them to
10751     //   their composite pointer type.
10752     if (!IsRelational &&
10753         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10754       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10755         return QualType();
10756       else
10757         return computeResultTy();
10758     }
10759   }
10760 
10761   // Handle block pointer types.
10762   if (!IsRelational && LHSType->isBlockPointerType() &&
10763       RHSType->isBlockPointerType()) {
10764     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10765     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10766 
10767     if (!LHSIsNull && !RHSIsNull &&
10768         !Context.typesAreCompatible(lpointee, rpointee)) {
10769       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10770         << LHSType << RHSType << LHS.get()->getSourceRange()
10771         << RHS.get()->getSourceRange();
10772     }
10773     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10774     return computeResultTy();
10775   }
10776 
10777   // Allow block pointers to be compared with null pointer constants.
10778   if (!IsRelational
10779       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10780           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10781     if (!LHSIsNull && !RHSIsNull) {
10782       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10783              ->getPointeeType()->isVoidType())
10784             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10785                 ->getPointeeType()->isVoidType())))
10786         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10787           << LHSType << RHSType << LHS.get()->getSourceRange()
10788           << RHS.get()->getSourceRange();
10789     }
10790     if (LHSIsNull && !RHSIsNull)
10791       LHS = ImpCastExprToType(LHS.get(), RHSType,
10792                               RHSType->isPointerType() ? CK_BitCast
10793                                 : CK_AnyPointerToBlockPointerCast);
10794     else
10795       RHS = ImpCastExprToType(RHS.get(), LHSType,
10796                               LHSType->isPointerType() ? CK_BitCast
10797                                 : CK_AnyPointerToBlockPointerCast);
10798     return computeResultTy();
10799   }
10800 
10801   if (LHSType->isObjCObjectPointerType() ||
10802       RHSType->isObjCObjectPointerType()) {
10803     const PointerType *LPT = LHSType->getAs<PointerType>();
10804     const PointerType *RPT = RHSType->getAs<PointerType>();
10805     if (LPT || RPT) {
10806       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10807       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10808 
10809       if (!LPtrToVoid && !RPtrToVoid &&
10810           !Context.typesAreCompatible(LHSType, RHSType)) {
10811         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10812                                           /*isError*/false);
10813       }
10814       if (LHSIsNull && !RHSIsNull) {
10815         Expr *E = LHS.get();
10816         if (getLangOpts().ObjCAutoRefCount)
10817           CheckObjCConversion(SourceRange(), RHSType, E,
10818                               CCK_ImplicitConversion);
10819         LHS = ImpCastExprToType(E, RHSType,
10820                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10821       }
10822       else {
10823         Expr *E = RHS.get();
10824         if (getLangOpts().ObjCAutoRefCount)
10825           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10826                               /*Diagnose=*/true,
10827                               /*DiagnoseCFAudited=*/false, Opc);
10828         RHS = ImpCastExprToType(E, LHSType,
10829                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10830       }
10831       return computeResultTy();
10832     }
10833     if (LHSType->isObjCObjectPointerType() &&
10834         RHSType->isObjCObjectPointerType()) {
10835       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10836         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10837                                           /*isError*/false);
10838       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10839         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10840 
10841       if (LHSIsNull && !RHSIsNull)
10842         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10843       else
10844         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10845       return computeResultTy();
10846     }
10847 
10848     if (!IsRelational && LHSType->isBlockPointerType() &&
10849         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10850       LHS = ImpCastExprToType(LHS.get(), RHSType,
10851                               CK_BlockPointerToObjCPointerCast);
10852       return computeResultTy();
10853     } else if (!IsRelational &&
10854                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10855                RHSType->isBlockPointerType()) {
10856       RHS = ImpCastExprToType(RHS.get(), LHSType,
10857                               CK_BlockPointerToObjCPointerCast);
10858       return computeResultTy();
10859     }
10860   }
10861   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10862       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10863     unsigned DiagID = 0;
10864     bool isError = false;
10865     if (LangOpts.DebuggerSupport) {
10866       // Under a debugger, allow the comparison of pointers to integers,
10867       // since users tend to want to compare addresses.
10868     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10869                (RHSIsNull && RHSType->isIntegerType())) {
10870       if (IsRelational) {
10871         isError = getLangOpts().CPlusPlus;
10872         DiagID =
10873           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10874                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10875       }
10876     } else if (getLangOpts().CPlusPlus) {
10877       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10878       isError = true;
10879     } else if (IsRelational)
10880       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10881     else
10882       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10883 
10884     if (DiagID) {
10885       Diag(Loc, DiagID)
10886         << LHSType << RHSType << LHS.get()->getSourceRange()
10887         << RHS.get()->getSourceRange();
10888       if (isError)
10889         return QualType();
10890     }
10891 
10892     if (LHSType->isIntegerType())
10893       LHS = ImpCastExprToType(LHS.get(), RHSType,
10894                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10895     else
10896       RHS = ImpCastExprToType(RHS.get(), LHSType,
10897                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10898     return computeResultTy();
10899   }
10900 
10901   // Handle block pointers.
10902   if (!IsRelational && RHSIsNull
10903       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10904     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10905     return computeResultTy();
10906   }
10907   if (!IsRelational && LHSIsNull
10908       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10909     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10910     return computeResultTy();
10911   }
10912 
10913   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
10914     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10915       return computeResultTy();
10916     }
10917 
10918     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10919       return computeResultTy();
10920     }
10921 
10922     if (LHSIsNull && RHSType->isQueueT()) {
10923       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10924       return computeResultTy();
10925     }
10926 
10927     if (LHSType->isQueueT() && RHSIsNull) {
10928       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10929       return computeResultTy();
10930     }
10931   }
10932 
10933   return InvalidOperands(Loc, LHS, RHS);
10934 }
10935 
10936 // Return a signed ext_vector_type that is of identical size and number of
10937 // elements. For floating point vectors, return an integer type of identical
10938 // size and number of elements. In the non ext_vector_type case, search from
10939 // the largest type to the smallest type to avoid cases where long long == long,
10940 // where long gets picked over long long.
10941 QualType Sema::GetSignedVectorType(QualType V) {
10942   const VectorType *VTy = V->getAs<VectorType>();
10943   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10944 
10945   if (isa<ExtVectorType>(VTy)) {
10946     if (TypeSize == Context.getTypeSize(Context.CharTy))
10947       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10948     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10949       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10950     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10951       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10952     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10953       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10954     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10955            "Unhandled vector element size in vector compare");
10956     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10957   }
10958 
10959   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10960     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10961                                  VectorType::GenericVector);
10962   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10963     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10964                                  VectorType::GenericVector);
10965   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10966     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10967                                  VectorType::GenericVector);
10968   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10969     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10970                                  VectorType::GenericVector);
10971   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10972          "Unhandled vector element size in vector compare");
10973   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10974                                VectorType::GenericVector);
10975 }
10976 
10977 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10978 /// operates on extended vector types.  Instead of producing an IntTy result,
10979 /// like a scalar comparison, a vector comparison produces a vector of integer
10980 /// types.
10981 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10982                                           SourceLocation Loc,
10983                                           BinaryOperatorKind Opc) {
10984   // Check to make sure we're operating on vectors of the same type and width,
10985   // Allowing one side to be a scalar of element type.
10986   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10987                               /*AllowBothBool*/true,
10988                               /*AllowBoolConversions*/getLangOpts().ZVector);
10989   if (vType.isNull())
10990     return vType;
10991 
10992   QualType LHSType = LHS.get()->getType();
10993 
10994   // If AltiVec, the comparison results in a numeric type, i.e.
10995   // bool for C++, int for C
10996   if (getLangOpts().AltiVec &&
10997       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10998     return Context.getLogicalOperationType();
10999 
11000   // For non-floating point types, check for self-comparisons of the form
11001   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11002   // often indicate logic errors in the program.
11003   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11004 
11005   // Check for comparisons of floating point operands using != and ==.
11006   if (BinaryOperator::isEqualityOp(Opc) &&
11007       LHSType->hasFloatingRepresentation()) {
11008     assert(RHS.get()->getType()->hasFloatingRepresentation());
11009     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11010   }
11011 
11012   // Return a signed type for the vector.
11013   return GetSignedVectorType(vType);
11014 }
11015 
11016 static void diagnoseXorMisusedAsPow(Sema &S, ExprResult &LHS, ExprResult &RHS,
11017                                     SourceLocation Loc) {
11018   // Do not diagnose macros.
11019   if (Loc.isMacroID())
11020     return;
11021 
11022   bool Negative = false;
11023   const auto *LHSInt = dyn_cast<IntegerLiteral>(LHS.get());
11024   const auto *RHSInt = dyn_cast<IntegerLiteral>(RHS.get());
11025 
11026   if (!LHSInt)
11027     return;
11028   if (!RHSInt) {
11029     // Check negative literals.
11030     if (const auto *UO = dyn_cast<UnaryOperator>(RHS.get())) {
11031       if (UO->getOpcode() != UO_Minus)
11032         return;
11033       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11034       if (!RHSInt)
11035         return;
11036       Negative = true;
11037     } else {
11038       return;
11039     }
11040   }
11041 
11042   if (LHSInt->getValue().getBitWidth() != RHSInt->getValue().getBitWidth())
11043     return;
11044 
11045   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11046       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11047   llvm::StringRef ExprStr =
11048       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11049 
11050   CharSourceRange XorRange =
11051       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11052   llvm::StringRef XorStr =
11053       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11054   // Do not diagnose if xor keyword/macro is used.
11055   if (XorStr == "xor")
11056     return;
11057 
11058   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11059   const llvm::APInt &RightSideValue = RHSInt->getValue();
11060   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11061 
11062   std::string LHSStr = Lexer::getSourceText(
11063       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11064       S.getSourceManager(), S.getLangOpts());
11065   std::string RHSStr = Lexer::getSourceText(
11066       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11067       S.getSourceManager(), S.getLangOpts());
11068 
11069   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11070   if (Negative) {
11071     RightSideIntValue = -RightSideIntValue;
11072     RHSStr = "-" + RHSStr;
11073   }
11074 
11075   StringRef LHSStrRef = LHSStr;
11076   StringRef RHSStrRef = RHSStr;
11077   // Do not diagnose binary, hexadecimal, octal literals.
11078   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11079       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11080       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11081       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11082       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11083       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")))
11084     return;
11085 
11086   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11087     std::string SuggestedExpr = "1 << " + RHSStr;
11088     bool Overflow = false;
11089     llvm::APInt One = (LeftSideValue - 1);
11090     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11091     if (Overflow) {
11092       if (RightSideIntValue < 64)
11093         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11094             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11095             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11096       else
11097          // TODO: 2 ^ 64 - 1
11098         return;
11099     } else {
11100       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11101           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11102           << PowValue.toString(10, true)
11103           << FixItHint::CreateReplacement(
11104                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11105     }
11106 
11107     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr);
11108   } else if (LeftSideValue == 10) {
11109     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11110     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11111         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11112         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11113     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr);
11114   }
11115 }
11116 
11117 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11118                                           SourceLocation Loc) {
11119   // Ensure that either both operands are of the same vector type, or
11120   // one operand is of a vector type and the other is of its element type.
11121   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11122                                        /*AllowBothBool*/true,
11123                                        /*AllowBoolConversions*/false);
11124   if (vType.isNull())
11125     return InvalidOperands(Loc, LHS, RHS);
11126   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11127       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11128     return InvalidOperands(Loc, LHS, RHS);
11129   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11130   //        usage of the logical operators && and || with vectors in C. This
11131   //        check could be notionally dropped.
11132   if (!getLangOpts().CPlusPlus &&
11133       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11134     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11135 
11136   return GetSignedVectorType(LHS.get()->getType());
11137 }
11138 
11139 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11140                                            SourceLocation Loc,
11141                                            BinaryOperatorKind Opc) {
11142   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11143 
11144   bool IsCompAssign =
11145       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11146 
11147   if (LHS.get()->getType()->isVectorType() ||
11148       RHS.get()->getType()->isVectorType()) {
11149     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11150         RHS.get()->getType()->hasIntegerRepresentation())
11151       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11152                         /*AllowBothBool*/true,
11153                         /*AllowBoolConversions*/getLangOpts().ZVector);
11154     return InvalidOperands(Loc, LHS, RHS);
11155   }
11156 
11157   if (Opc == BO_And)
11158     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11159 
11160   if (Opc == BO_Xor)
11161     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11162 
11163   ExprResult LHSResult = LHS, RHSResult = RHS;
11164   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
11165                                                  IsCompAssign);
11166   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11167     return QualType();
11168   LHS = LHSResult.get();
11169   RHS = RHSResult.get();
11170 
11171   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11172     return compType;
11173   return InvalidOperands(Loc, LHS, RHS);
11174 }
11175 
11176 // C99 6.5.[13,14]
11177 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11178                                            SourceLocation Loc,
11179                                            BinaryOperatorKind Opc) {
11180   // Check vector operands differently.
11181   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11182     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11183 
11184   // Diagnose cases where the user write a logical and/or but probably meant a
11185   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11186   // is a constant.
11187   if (LHS.get()->getType()->isIntegerType() &&
11188       !LHS.get()->getType()->isBooleanType() &&
11189       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11190       // Don't warn in macros or template instantiations.
11191       !Loc.isMacroID() && !inTemplateInstantiation()) {
11192     // If the RHS can be constant folded, and if it constant folds to something
11193     // that isn't 0 or 1 (which indicate a potential logical operation that
11194     // happened to fold to true/false) then warn.
11195     // Parens on the RHS are ignored.
11196     Expr::EvalResult EVResult;
11197     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11198       llvm::APSInt Result = EVResult.Val.getInt();
11199       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11200            !RHS.get()->getExprLoc().isMacroID()) ||
11201           (Result != 0 && Result != 1)) {
11202         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11203           << RHS.get()->getSourceRange()
11204           << (Opc == BO_LAnd ? "&&" : "||");
11205         // Suggest replacing the logical operator with the bitwise version
11206         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11207             << (Opc == BO_LAnd ? "&" : "|")
11208             << FixItHint::CreateReplacement(SourceRange(
11209                                                  Loc, getLocForEndOfToken(Loc)),
11210                                             Opc == BO_LAnd ? "&" : "|");
11211         if (Opc == BO_LAnd)
11212           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11213           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11214               << FixItHint::CreateRemoval(
11215                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11216                                  RHS.get()->getEndLoc()));
11217       }
11218     }
11219   }
11220 
11221   if (!Context.getLangOpts().CPlusPlus) {
11222     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11223     // not operate on the built-in scalar and vector float types.
11224     if (Context.getLangOpts().OpenCL &&
11225         Context.getLangOpts().OpenCLVersion < 120) {
11226       if (LHS.get()->getType()->isFloatingType() ||
11227           RHS.get()->getType()->isFloatingType())
11228         return InvalidOperands(Loc, LHS, RHS);
11229     }
11230 
11231     LHS = UsualUnaryConversions(LHS.get());
11232     if (LHS.isInvalid())
11233       return QualType();
11234 
11235     RHS = UsualUnaryConversions(RHS.get());
11236     if (RHS.isInvalid())
11237       return QualType();
11238 
11239     if (!LHS.get()->getType()->isScalarType() ||
11240         !RHS.get()->getType()->isScalarType())
11241       return InvalidOperands(Loc, LHS, RHS);
11242 
11243     return Context.IntTy;
11244   }
11245 
11246   // The following is safe because we only use this method for
11247   // non-overloadable operands.
11248 
11249   // C++ [expr.log.and]p1
11250   // C++ [expr.log.or]p1
11251   // The operands are both contextually converted to type bool.
11252   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11253   if (LHSRes.isInvalid())
11254     return InvalidOperands(Loc, LHS, RHS);
11255   LHS = LHSRes;
11256 
11257   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11258   if (RHSRes.isInvalid())
11259     return InvalidOperands(Loc, LHS, RHS);
11260   RHS = RHSRes;
11261 
11262   // C++ [expr.log.and]p2
11263   // C++ [expr.log.or]p2
11264   // The result is a bool.
11265   return Context.BoolTy;
11266 }
11267 
11268 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11269   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11270   if (!ME) return false;
11271   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11272   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11273       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11274   if (!Base) return false;
11275   return Base->getMethodDecl() != nullptr;
11276 }
11277 
11278 /// Is the given expression (which must be 'const') a reference to a
11279 /// variable which was originally non-const, but which has become
11280 /// 'const' due to being captured within a block?
11281 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11282 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11283   assert(E->isLValue() && E->getType().isConstQualified());
11284   E = E->IgnoreParens();
11285 
11286   // Must be a reference to a declaration from an enclosing scope.
11287   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11288   if (!DRE) return NCCK_None;
11289   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11290 
11291   // The declaration must be a variable which is not declared 'const'.
11292   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11293   if (!var) return NCCK_None;
11294   if (var->getType().isConstQualified()) return NCCK_None;
11295   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11296 
11297   // Decide whether the first capture was for a block or a lambda.
11298   DeclContext *DC = S.CurContext, *Prev = nullptr;
11299   // Decide whether the first capture was for a block or a lambda.
11300   while (DC) {
11301     // For init-capture, it is possible that the variable belongs to the
11302     // template pattern of the current context.
11303     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11304       if (var->isInitCapture() &&
11305           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11306         break;
11307     if (DC == var->getDeclContext())
11308       break;
11309     Prev = DC;
11310     DC = DC->getParent();
11311   }
11312   // Unless we have an init-capture, we've gone one step too far.
11313   if (!var->isInitCapture())
11314     DC = Prev;
11315   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11316 }
11317 
11318 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11319   Ty = Ty.getNonReferenceType();
11320   if (IsDereference && Ty->isPointerType())
11321     Ty = Ty->getPointeeType();
11322   return !Ty.isConstQualified();
11323 }
11324 
11325 // Update err_typecheck_assign_const and note_typecheck_assign_const
11326 // when this enum is changed.
11327 enum {
11328   ConstFunction,
11329   ConstVariable,
11330   ConstMember,
11331   ConstMethod,
11332   NestedConstMember,
11333   ConstUnknown,  // Keep as last element
11334 };
11335 
11336 /// Emit the "read-only variable not assignable" error and print notes to give
11337 /// more information about why the variable is not assignable, such as pointing
11338 /// to the declaration of a const variable, showing that a method is const, or
11339 /// that the function is returning a const reference.
11340 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11341                                     SourceLocation Loc) {
11342   SourceRange ExprRange = E->getSourceRange();
11343 
11344   // Only emit one error on the first const found.  All other consts will emit
11345   // a note to the error.
11346   bool DiagnosticEmitted = false;
11347 
11348   // Track if the current expression is the result of a dereference, and if the
11349   // next checked expression is the result of a dereference.
11350   bool IsDereference = false;
11351   bool NextIsDereference = false;
11352 
11353   // Loop to process MemberExpr chains.
11354   while (true) {
11355     IsDereference = NextIsDereference;
11356 
11357     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11358     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11359       NextIsDereference = ME->isArrow();
11360       const ValueDecl *VD = ME->getMemberDecl();
11361       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11362         // Mutable fields can be modified even if the class is const.
11363         if (Field->isMutable()) {
11364           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11365           break;
11366         }
11367 
11368         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11369           if (!DiagnosticEmitted) {
11370             S.Diag(Loc, diag::err_typecheck_assign_const)
11371                 << ExprRange << ConstMember << false /*static*/ << Field
11372                 << Field->getType();
11373             DiagnosticEmitted = true;
11374           }
11375           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11376               << ConstMember << false /*static*/ << Field << Field->getType()
11377               << Field->getSourceRange();
11378         }
11379         E = ME->getBase();
11380         continue;
11381       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11382         if (VDecl->getType().isConstQualified()) {
11383           if (!DiagnosticEmitted) {
11384             S.Diag(Loc, diag::err_typecheck_assign_const)
11385                 << ExprRange << ConstMember << true /*static*/ << VDecl
11386                 << VDecl->getType();
11387             DiagnosticEmitted = true;
11388           }
11389           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11390               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11391               << VDecl->getSourceRange();
11392         }
11393         // Static fields do not inherit constness from parents.
11394         break;
11395       }
11396       break; // End MemberExpr
11397     } else if (const ArraySubscriptExpr *ASE =
11398                    dyn_cast<ArraySubscriptExpr>(E)) {
11399       E = ASE->getBase()->IgnoreParenImpCasts();
11400       continue;
11401     } else if (const ExtVectorElementExpr *EVE =
11402                    dyn_cast<ExtVectorElementExpr>(E)) {
11403       E = EVE->getBase()->IgnoreParenImpCasts();
11404       continue;
11405     }
11406     break;
11407   }
11408 
11409   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11410     // Function calls
11411     const FunctionDecl *FD = CE->getDirectCallee();
11412     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11413       if (!DiagnosticEmitted) {
11414         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11415                                                       << ConstFunction << FD;
11416         DiagnosticEmitted = true;
11417       }
11418       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11419              diag::note_typecheck_assign_const)
11420           << ConstFunction << FD << FD->getReturnType()
11421           << FD->getReturnTypeSourceRange();
11422     }
11423   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11424     // Point to variable declaration.
11425     if (const ValueDecl *VD = DRE->getDecl()) {
11426       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11427         if (!DiagnosticEmitted) {
11428           S.Diag(Loc, diag::err_typecheck_assign_const)
11429               << ExprRange << ConstVariable << VD << VD->getType();
11430           DiagnosticEmitted = true;
11431         }
11432         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11433             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11434       }
11435     }
11436   } else if (isa<CXXThisExpr>(E)) {
11437     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11438       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11439         if (MD->isConst()) {
11440           if (!DiagnosticEmitted) {
11441             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11442                                                           << ConstMethod << MD;
11443             DiagnosticEmitted = true;
11444           }
11445           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11446               << ConstMethod << MD << MD->getSourceRange();
11447         }
11448       }
11449     }
11450   }
11451 
11452   if (DiagnosticEmitted)
11453     return;
11454 
11455   // Can't determine a more specific message, so display the generic error.
11456   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11457 }
11458 
11459 enum OriginalExprKind {
11460   OEK_Variable,
11461   OEK_Member,
11462   OEK_LValue
11463 };
11464 
11465 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11466                                          const RecordType *Ty,
11467                                          SourceLocation Loc, SourceRange Range,
11468                                          OriginalExprKind OEK,
11469                                          bool &DiagnosticEmitted) {
11470   std::vector<const RecordType *> RecordTypeList;
11471   RecordTypeList.push_back(Ty);
11472   unsigned NextToCheckIndex = 0;
11473   // We walk the record hierarchy breadth-first to ensure that we print
11474   // diagnostics in field nesting order.
11475   while (RecordTypeList.size() > NextToCheckIndex) {
11476     bool IsNested = NextToCheckIndex > 0;
11477     for (const FieldDecl *Field :
11478          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11479       // First, check every field for constness.
11480       QualType FieldTy = Field->getType();
11481       if (FieldTy.isConstQualified()) {
11482         if (!DiagnosticEmitted) {
11483           S.Diag(Loc, diag::err_typecheck_assign_const)
11484               << Range << NestedConstMember << OEK << VD
11485               << IsNested << Field;
11486           DiagnosticEmitted = true;
11487         }
11488         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11489             << NestedConstMember << IsNested << Field
11490             << FieldTy << Field->getSourceRange();
11491       }
11492 
11493       // Then we append it to the list to check next in order.
11494       FieldTy = FieldTy.getCanonicalType();
11495       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11496         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11497           RecordTypeList.push_back(FieldRecTy);
11498       }
11499     }
11500     ++NextToCheckIndex;
11501   }
11502 }
11503 
11504 /// Emit an error for the case where a record we are trying to assign to has a
11505 /// const-qualified field somewhere in its hierarchy.
11506 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11507                                          SourceLocation Loc) {
11508   QualType Ty = E->getType();
11509   assert(Ty->isRecordType() && "lvalue was not record?");
11510   SourceRange Range = E->getSourceRange();
11511   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11512   bool DiagEmitted = false;
11513 
11514   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11515     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11516             Range, OEK_Member, DiagEmitted);
11517   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11518     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11519             Range, OEK_Variable, DiagEmitted);
11520   else
11521     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11522             Range, OEK_LValue, DiagEmitted);
11523   if (!DiagEmitted)
11524     DiagnoseConstAssignment(S, E, Loc);
11525 }
11526 
11527 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11528 /// emit an error and return true.  If so, return false.
11529 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11530   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11531 
11532   S.CheckShadowingDeclModification(E, Loc);
11533 
11534   SourceLocation OrigLoc = Loc;
11535   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11536                                                               &Loc);
11537   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11538     IsLV = Expr::MLV_InvalidMessageExpression;
11539   if (IsLV == Expr::MLV_Valid)
11540     return false;
11541 
11542   unsigned DiagID = 0;
11543   bool NeedType = false;
11544   switch (IsLV) { // C99 6.5.16p2
11545   case Expr::MLV_ConstQualified:
11546     // Use a specialized diagnostic when we're assigning to an object
11547     // from an enclosing function or block.
11548     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11549       if (NCCK == NCCK_Block)
11550         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11551       else
11552         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11553       break;
11554     }
11555 
11556     // In ARC, use some specialized diagnostics for occasions where we
11557     // infer 'const'.  These are always pseudo-strong variables.
11558     if (S.getLangOpts().ObjCAutoRefCount) {
11559       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11560       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11561         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11562 
11563         // Use the normal diagnostic if it's pseudo-__strong but the
11564         // user actually wrote 'const'.
11565         if (var->isARCPseudoStrong() &&
11566             (!var->getTypeSourceInfo() ||
11567              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11568           // There are three pseudo-strong cases:
11569           //  - self
11570           ObjCMethodDecl *method = S.getCurMethodDecl();
11571           if (method && var == method->getSelfDecl()) {
11572             DiagID = method->isClassMethod()
11573               ? diag::err_typecheck_arc_assign_self_class_method
11574               : diag::err_typecheck_arc_assign_self;
11575 
11576           //  - Objective-C externally_retained attribute.
11577           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11578                      isa<ParmVarDecl>(var)) {
11579             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11580 
11581           //  - fast enumeration variables
11582           } else {
11583             DiagID = diag::err_typecheck_arr_assign_enumeration;
11584           }
11585 
11586           SourceRange Assign;
11587           if (Loc != OrigLoc)
11588             Assign = SourceRange(OrigLoc, OrigLoc);
11589           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11590           // We need to preserve the AST regardless, so migration tool
11591           // can do its job.
11592           return false;
11593         }
11594       }
11595     }
11596 
11597     // If none of the special cases above are triggered, then this is a
11598     // simple const assignment.
11599     if (DiagID == 0) {
11600       DiagnoseConstAssignment(S, E, Loc);
11601       return true;
11602     }
11603 
11604     break;
11605   case Expr::MLV_ConstAddrSpace:
11606     DiagnoseConstAssignment(S, E, Loc);
11607     return true;
11608   case Expr::MLV_ConstQualifiedField:
11609     DiagnoseRecursiveConstFields(S, E, Loc);
11610     return true;
11611   case Expr::MLV_ArrayType:
11612   case Expr::MLV_ArrayTemporary:
11613     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11614     NeedType = true;
11615     break;
11616   case Expr::MLV_NotObjectType:
11617     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11618     NeedType = true;
11619     break;
11620   case Expr::MLV_LValueCast:
11621     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11622     break;
11623   case Expr::MLV_Valid:
11624     llvm_unreachable("did not take early return for MLV_Valid");
11625   case Expr::MLV_InvalidExpression:
11626   case Expr::MLV_MemberFunction:
11627   case Expr::MLV_ClassTemporary:
11628     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11629     break;
11630   case Expr::MLV_IncompleteType:
11631   case Expr::MLV_IncompleteVoidType:
11632     return S.RequireCompleteType(Loc, E->getType(),
11633              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11634   case Expr::MLV_DuplicateVectorComponents:
11635     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11636     break;
11637   case Expr::MLV_NoSetterProperty:
11638     llvm_unreachable("readonly properties should be processed differently");
11639   case Expr::MLV_InvalidMessageExpression:
11640     DiagID = diag::err_readonly_message_assignment;
11641     break;
11642   case Expr::MLV_SubObjCPropertySetting:
11643     DiagID = diag::err_no_subobject_property_setting;
11644     break;
11645   }
11646 
11647   SourceRange Assign;
11648   if (Loc != OrigLoc)
11649     Assign = SourceRange(OrigLoc, OrigLoc);
11650   if (NeedType)
11651     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11652   else
11653     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11654   return true;
11655 }
11656 
11657 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11658                                          SourceLocation Loc,
11659                                          Sema &Sema) {
11660   if (Sema.inTemplateInstantiation())
11661     return;
11662   if (Sema.isUnevaluatedContext())
11663     return;
11664   if (Loc.isInvalid() || Loc.isMacroID())
11665     return;
11666   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11667     return;
11668 
11669   // C / C++ fields
11670   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11671   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11672   if (ML && MR) {
11673     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11674       return;
11675     const ValueDecl *LHSDecl =
11676         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11677     const ValueDecl *RHSDecl =
11678         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11679     if (LHSDecl != RHSDecl)
11680       return;
11681     if (LHSDecl->getType().isVolatileQualified())
11682       return;
11683     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11684       if (RefTy->getPointeeType().isVolatileQualified())
11685         return;
11686 
11687     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11688   }
11689 
11690   // Objective-C instance variables
11691   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11692   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11693   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11694     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11695     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11696     if (RL && RR && RL->getDecl() == RR->getDecl())
11697       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11698   }
11699 }
11700 
11701 // C99 6.5.16.1
11702 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11703                                        SourceLocation Loc,
11704                                        QualType CompoundType) {
11705   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11706 
11707   // Verify that LHS is a modifiable lvalue, and emit error if not.
11708   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11709     return QualType();
11710 
11711   QualType LHSType = LHSExpr->getType();
11712   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11713                                              CompoundType;
11714   // OpenCL v1.2 s6.1.1.1 p2:
11715   // The half data type can only be used to declare a pointer to a buffer that
11716   // contains half values
11717   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11718     LHSType->isHalfType()) {
11719     Diag(Loc, diag::err_opencl_half_load_store) << 1
11720         << LHSType.getUnqualifiedType();
11721     return QualType();
11722   }
11723 
11724   AssignConvertType ConvTy;
11725   if (CompoundType.isNull()) {
11726     Expr *RHSCheck = RHS.get();
11727 
11728     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11729 
11730     QualType LHSTy(LHSType);
11731     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11732     if (RHS.isInvalid())
11733       return QualType();
11734     // Special case of NSObject attributes on c-style pointer types.
11735     if (ConvTy == IncompatiblePointer &&
11736         ((Context.isObjCNSObjectType(LHSType) &&
11737           RHSType->isObjCObjectPointerType()) ||
11738          (Context.isObjCNSObjectType(RHSType) &&
11739           LHSType->isObjCObjectPointerType())))
11740       ConvTy = Compatible;
11741 
11742     if (ConvTy == Compatible &&
11743         LHSType->isObjCObjectType())
11744         Diag(Loc, diag::err_objc_object_assignment)
11745           << LHSType;
11746 
11747     // If the RHS is a unary plus or minus, check to see if they = and + are
11748     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11749     // instead of "x += 4".
11750     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11751       RHSCheck = ICE->getSubExpr();
11752     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11753       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11754           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11755           // Only if the two operators are exactly adjacent.
11756           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11757           // And there is a space or other character before the subexpr of the
11758           // unary +/-.  We don't want to warn on "x=-1".
11759           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11760           UO->getSubExpr()->getBeginLoc().isFileID()) {
11761         Diag(Loc, diag::warn_not_compound_assign)
11762           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11763           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11764       }
11765     }
11766 
11767     if (ConvTy == Compatible) {
11768       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11769         // Warn about retain cycles where a block captures the LHS, but
11770         // not if the LHS is a simple variable into which the block is
11771         // being stored...unless that variable can be captured by reference!
11772         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11773         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11774         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11775           checkRetainCycles(LHSExpr, RHS.get());
11776       }
11777 
11778       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11779           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11780         // It is safe to assign a weak reference into a strong variable.
11781         // Although this code can still have problems:
11782         //   id x = self.weakProp;
11783         //   id y = self.weakProp;
11784         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11785         // paths through the function. This should be revisited if
11786         // -Wrepeated-use-of-weak is made flow-sensitive.
11787         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11788         // variable, which will be valid for the current autorelease scope.
11789         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11790                              RHS.get()->getBeginLoc()))
11791           getCurFunction()->markSafeWeakUse(RHS.get());
11792 
11793       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11794         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11795       }
11796     }
11797   } else {
11798     // Compound assignment "x += y"
11799     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11800   }
11801 
11802   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11803                                RHS.get(), AA_Assigning))
11804     return QualType();
11805 
11806   CheckForNullPointerDereference(*this, LHSExpr);
11807 
11808   // C99 6.5.16p3: The type of an assignment expression is the type of the
11809   // left operand unless the left operand has qualified type, in which case
11810   // it is the unqualified version of the type of the left operand.
11811   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11812   // is converted to the type of the assignment expression (above).
11813   // C++ 5.17p1: the type of the assignment expression is that of its left
11814   // operand.
11815   return (getLangOpts().CPlusPlus
11816           ? LHSType : LHSType.getUnqualifiedType());
11817 }
11818 
11819 // Only ignore explicit casts to void.
11820 static bool IgnoreCommaOperand(const Expr *E) {
11821   E = E->IgnoreParens();
11822 
11823   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11824     if (CE->getCastKind() == CK_ToVoid) {
11825       return true;
11826     }
11827 
11828     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11829     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11830         CE->getSubExpr()->getType()->isDependentType()) {
11831       return true;
11832     }
11833   }
11834 
11835   return false;
11836 }
11837 
11838 // Look for instances where it is likely the comma operator is confused with
11839 // another operator.  There is a whitelist of acceptable expressions for the
11840 // left hand side of the comma operator, otherwise emit a warning.
11841 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11842   // No warnings in macros
11843   if (Loc.isMacroID())
11844     return;
11845 
11846   // Don't warn in template instantiations.
11847   if (inTemplateInstantiation())
11848     return;
11849 
11850   // Scope isn't fine-grained enough to whitelist the specific cases, so
11851   // instead, skip more than needed, then call back into here with the
11852   // CommaVisitor in SemaStmt.cpp.
11853   // The whitelisted locations are the initialization and increment portions
11854   // of a for loop.  The additional checks are on the condition of
11855   // if statements, do/while loops, and for loops.
11856   // Differences in scope flags for C89 mode requires the extra logic.
11857   const unsigned ForIncrementFlags =
11858       getLangOpts().C99 || getLangOpts().CPlusPlus
11859           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11860           : Scope::ContinueScope | Scope::BreakScope;
11861   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11862   const unsigned ScopeFlags = getCurScope()->getFlags();
11863   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11864       (ScopeFlags & ForInitFlags) == ForInitFlags)
11865     return;
11866 
11867   // If there are multiple comma operators used together, get the RHS of the
11868   // of the comma operator as the LHS.
11869   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11870     if (BO->getOpcode() != BO_Comma)
11871       break;
11872     LHS = BO->getRHS();
11873   }
11874 
11875   // Only allow some expressions on LHS to not warn.
11876   if (IgnoreCommaOperand(LHS))
11877     return;
11878 
11879   Diag(Loc, diag::warn_comma_operator);
11880   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11881       << LHS->getSourceRange()
11882       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11883                                     LangOpts.CPlusPlus ? "static_cast<void>("
11884                                                        : "(void)(")
11885       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11886                                     ")");
11887 }
11888 
11889 // C99 6.5.17
11890 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11891                                    SourceLocation Loc) {
11892   LHS = S.CheckPlaceholderExpr(LHS.get());
11893   RHS = S.CheckPlaceholderExpr(RHS.get());
11894   if (LHS.isInvalid() || RHS.isInvalid())
11895     return QualType();
11896 
11897   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11898   // operands, but not unary promotions.
11899   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11900 
11901   // So we treat the LHS as a ignored value, and in C++ we allow the
11902   // containing site to determine what should be done with the RHS.
11903   LHS = S.IgnoredValueConversions(LHS.get());
11904   if (LHS.isInvalid())
11905     return QualType();
11906 
11907   S.DiagnoseUnusedExprResult(LHS.get());
11908 
11909   if (!S.getLangOpts().CPlusPlus) {
11910     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11911     if (RHS.isInvalid())
11912       return QualType();
11913     if (!RHS.get()->getType()->isVoidType())
11914       S.RequireCompleteType(Loc, RHS.get()->getType(),
11915                             diag::err_incomplete_type);
11916   }
11917 
11918   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11919     S.DiagnoseCommaOperator(LHS.get(), Loc);
11920 
11921   return RHS.get()->getType();
11922 }
11923 
11924 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11925 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11926 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11927                                                ExprValueKind &VK,
11928                                                ExprObjectKind &OK,
11929                                                SourceLocation OpLoc,
11930                                                bool IsInc, bool IsPrefix) {
11931   if (Op->isTypeDependent())
11932     return S.Context.DependentTy;
11933 
11934   QualType ResType = Op->getType();
11935   // Atomic types can be used for increment / decrement where the non-atomic
11936   // versions can, so ignore the _Atomic() specifier for the purpose of
11937   // checking.
11938   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11939     ResType = ResAtomicType->getValueType();
11940 
11941   assert(!ResType.isNull() && "no type for increment/decrement expression");
11942 
11943   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11944     // Decrement of bool is not allowed.
11945     if (!IsInc) {
11946       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11947       return QualType();
11948     }
11949     // Increment of bool sets it to true, but is deprecated.
11950     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11951                                               : diag::warn_increment_bool)
11952       << Op->getSourceRange();
11953   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11954     // Error on enum increments and decrements in C++ mode
11955     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11956     return QualType();
11957   } else if (ResType->isRealType()) {
11958     // OK!
11959   } else if (ResType->isPointerType()) {
11960     // C99 6.5.2.4p2, 6.5.6p2
11961     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11962       return QualType();
11963   } else if (ResType->isObjCObjectPointerType()) {
11964     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11965     // Otherwise, we just need a complete type.
11966     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11967         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11968       return QualType();
11969   } else if (ResType->isAnyComplexType()) {
11970     // C99 does not support ++/-- on complex types, we allow as an extension.
11971     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11972       << ResType << Op->getSourceRange();
11973   } else if (ResType->isPlaceholderType()) {
11974     ExprResult PR = S.CheckPlaceholderExpr(Op);
11975     if (PR.isInvalid()) return QualType();
11976     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11977                                           IsInc, IsPrefix);
11978   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11979     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11980   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11981              (ResType->getAs<VectorType>()->getVectorKind() !=
11982               VectorType::AltiVecBool)) {
11983     // The z vector extensions allow ++ and -- for non-bool vectors.
11984   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11985             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11986     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11987   } else {
11988     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11989       << ResType << int(IsInc) << Op->getSourceRange();
11990     return QualType();
11991   }
11992   // At this point, we know we have a real, complex or pointer type.
11993   // Now make sure the operand is a modifiable lvalue.
11994   if (CheckForModifiableLvalue(Op, OpLoc, S))
11995     return QualType();
11996   // In C++, a prefix increment is the same type as the operand. Otherwise
11997   // (in C or with postfix), the increment is the unqualified type of the
11998   // operand.
11999   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12000     VK = VK_LValue;
12001     OK = Op->getObjectKind();
12002     return ResType;
12003   } else {
12004     VK = VK_RValue;
12005     return ResType.getUnqualifiedType();
12006   }
12007 }
12008 
12009 
12010 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12011 /// This routine allows us to typecheck complex/recursive expressions
12012 /// where the declaration is needed for type checking. We only need to
12013 /// handle cases when the expression references a function designator
12014 /// or is an lvalue. Here are some examples:
12015 ///  - &(x) => x
12016 ///  - &*****f => f for f a function designator.
12017 ///  - &s.xx => s
12018 ///  - &s.zz[1].yy -> s, if zz is an array
12019 ///  - *(x + 1) -> x, if x is an array
12020 ///  - &"123"[2] -> 0
12021 ///  - & __real__ x -> x
12022 static ValueDecl *getPrimaryDecl(Expr *E) {
12023   switch (E->getStmtClass()) {
12024   case Stmt::DeclRefExprClass:
12025     return cast<DeclRefExpr>(E)->getDecl();
12026   case Stmt::MemberExprClass:
12027     // If this is an arrow operator, the address is an offset from
12028     // the base's value, so the object the base refers to is
12029     // irrelevant.
12030     if (cast<MemberExpr>(E)->isArrow())
12031       return nullptr;
12032     // Otherwise, the expression refers to a part of the base
12033     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12034   case Stmt::ArraySubscriptExprClass: {
12035     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12036     // promotion of register arrays earlier.
12037     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12038     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12039       if (ICE->getSubExpr()->getType()->isArrayType())
12040         return getPrimaryDecl(ICE->getSubExpr());
12041     }
12042     return nullptr;
12043   }
12044   case Stmt::UnaryOperatorClass: {
12045     UnaryOperator *UO = cast<UnaryOperator>(E);
12046 
12047     switch(UO->getOpcode()) {
12048     case UO_Real:
12049     case UO_Imag:
12050     case UO_Extension:
12051       return getPrimaryDecl(UO->getSubExpr());
12052     default:
12053       return nullptr;
12054     }
12055   }
12056   case Stmt::ParenExprClass:
12057     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12058   case Stmt::ImplicitCastExprClass:
12059     // If the result of an implicit cast is an l-value, we care about
12060     // the sub-expression; otherwise, the result here doesn't matter.
12061     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12062   default:
12063     return nullptr;
12064   }
12065 }
12066 
12067 namespace {
12068   enum {
12069     AO_Bit_Field = 0,
12070     AO_Vector_Element = 1,
12071     AO_Property_Expansion = 2,
12072     AO_Register_Variable = 3,
12073     AO_No_Error = 4
12074   };
12075 }
12076 /// Diagnose invalid operand for address of operations.
12077 ///
12078 /// \param Type The type of operand which cannot have its address taken.
12079 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12080                                          Expr *E, unsigned Type) {
12081   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12082 }
12083 
12084 /// CheckAddressOfOperand - The operand of & must be either a function
12085 /// designator or an lvalue designating an object. If it is an lvalue, the
12086 /// object cannot be declared with storage class register or be a bit field.
12087 /// Note: The usual conversions are *not* applied to the operand of the &
12088 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12089 /// In C++, the operand might be an overloaded function name, in which case
12090 /// we allow the '&' but retain the overloaded-function type.
12091 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12092   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12093     if (PTy->getKind() == BuiltinType::Overload) {
12094       Expr *E = OrigOp.get()->IgnoreParens();
12095       if (!isa<OverloadExpr>(E)) {
12096         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12097         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12098           << OrigOp.get()->getSourceRange();
12099         return QualType();
12100       }
12101 
12102       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12103       if (isa<UnresolvedMemberExpr>(Ovl))
12104         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12105           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12106             << OrigOp.get()->getSourceRange();
12107           return QualType();
12108         }
12109 
12110       return Context.OverloadTy;
12111     }
12112 
12113     if (PTy->getKind() == BuiltinType::UnknownAny)
12114       return Context.UnknownAnyTy;
12115 
12116     if (PTy->getKind() == BuiltinType::BoundMember) {
12117       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12118         << OrigOp.get()->getSourceRange();
12119       return QualType();
12120     }
12121 
12122     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12123     if (OrigOp.isInvalid()) return QualType();
12124   }
12125 
12126   if (OrigOp.get()->isTypeDependent())
12127     return Context.DependentTy;
12128 
12129   assert(!OrigOp.get()->getType()->isPlaceholderType());
12130 
12131   // Make sure to ignore parentheses in subsequent checks
12132   Expr *op = OrigOp.get()->IgnoreParens();
12133 
12134   // In OpenCL captures for blocks called as lambda functions
12135   // are located in the private address space. Blocks used in
12136   // enqueue_kernel can be located in a different address space
12137   // depending on a vendor implementation. Thus preventing
12138   // taking an address of the capture to avoid invalid AS casts.
12139   if (LangOpts.OpenCL) {
12140     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12141     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12142       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12143       return QualType();
12144     }
12145   }
12146 
12147   if (getLangOpts().C99) {
12148     // Implement C99-only parts of addressof rules.
12149     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12150       if (uOp->getOpcode() == UO_Deref)
12151         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12152         // (assuming the deref expression is valid).
12153         return uOp->getSubExpr()->getType();
12154     }
12155     // Technically, there should be a check for array subscript
12156     // expressions here, but the result of one is always an lvalue anyway.
12157   }
12158   ValueDecl *dcl = getPrimaryDecl(op);
12159 
12160   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12161     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12162                                            op->getBeginLoc()))
12163       return QualType();
12164 
12165   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12166   unsigned AddressOfError = AO_No_Error;
12167 
12168   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12169     bool sfinae = (bool)isSFINAEContext();
12170     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12171                                   : diag::ext_typecheck_addrof_temporary)
12172       << op->getType() << op->getSourceRange();
12173     if (sfinae)
12174       return QualType();
12175     // Materialize the temporary as an lvalue so that we can take its address.
12176     OrigOp = op =
12177         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12178   } else if (isa<ObjCSelectorExpr>(op)) {
12179     return Context.getPointerType(op->getType());
12180   } else if (lval == Expr::LV_MemberFunction) {
12181     // If it's an instance method, make a member pointer.
12182     // The expression must have exactly the form &A::foo.
12183 
12184     // If the underlying expression isn't a decl ref, give up.
12185     if (!isa<DeclRefExpr>(op)) {
12186       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12187         << OrigOp.get()->getSourceRange();
12188       return QualType();
12189     }
12190     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12191     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12192 
12193     // The id-expression was parenthesized.
12194     if (OrigOp.get() != DRE) {
12195       Diag(OpLoc, diag::err_parens_pointer_member_function)
12196         << OrigOp.get()->getSourceRange();
12197 
12198     // The method was named without a qualifier.
12199     } else if (!DRE->getQualifier()) {
12200       if (MD->getParent()->getName().empty())
12201         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12202           << op->getSourceRange();
12203       else {
12204         SmallString<32> Str;
12205         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12206         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12207           << op->getSourceRange()
12208           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12209       }
12210     }
12211 
12212     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12213     if (isa<CXXDestructorDecl>(MD))
12214       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12215 
12216     QualType MPTy = Context.getMemberPointerType(
12217         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12218     // Under the MS ABI, lock down the inheritance model now.
12219     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12220       (void)isCompleteType(OpLoc, MPTy);
12221     return MPTy;
12222   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12223     // C99 6.5.3.2p1
12224     // The operand must be either an l-value or a function designator
12225     if (!op->getType()->isFunctionType()) {
12226       // Use a special diagnostic for loads from property references.
12227       if (isa<PseudoObjectExpr>(op)) {
12228         AddressOfError = AO_Property_Expansion;
12229       } else {
12230         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12231           << op->getType() << op->getSourceRange();
12232         return QualType();
12233       }
12234     }
12235   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12236     // The operand cannot be a bit-field
12237     AddressOfError = AO_Bit_Field;
12238   } else if (op->getObjectKind() == OK_VectorComponent) {
12239     // The operand cannot be an element of a vector
12240     AddressOfError = AO_Vector_Element;
12241   } else if (dcl) { // C99 6.5.3.2p1
12242     // We have an lvalue with a decl. Make sure the decl is not declared
12243     // with the register storage-class specifier.
12244     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12245       // in C++ it is not error to take address of a register
12246       // variable (c++03 7.1.1P3)
12247       if (vd->getStorageClass() == SC_Register &&
12248           !getLangOpts().CPlusPlus) {
12249         AddressOfError = AO_Register_Variable;
12250       }
12251     } else if (isa<MSPropertyDecl>(dcl)) {
12252       AddressOfError = AO_Property_Expansion;
12253     } else if (isa<FunctionTemplateDecl>(dcl)) {
12254       return Context.OverloadTy;
12255     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12256       // Okay: we can take the address of a field.
12257       // Could be a pointer to member, though, if there is an explicit
12258       // scope qualifier for the class.
12259       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12260         DeclContext *Ctx = dcl->getDeclContext();
12261         if (Ctx && Ctx->isRecord()) {
12262           if (dcl->getType()->isReferenceType()) {
12263             Diag(OpLoc,
12264                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12265               << dcl->getDeclName() << dcl->getType();
12266             return QualType();
12267           }
12268 
12269           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12270             Ctx = Ctx->getParent();
12271 
12272           QualType MPTy = Context.getMemberPointerType(
12273               op->getType(),
12274               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12275           // Under the MS ABI, lock down the inheritance model now.
12276           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12277             (void)isCompleteType(OpLoc, MPTy);
12278           return MPTy;
12279         }
12280       }
12281     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12282                !isa<BindingDecl>(dcl))
12283       llvm_unreachable("Unknown/unexpected decl type");
12284   }
12285 
12286   if (AddressOfError != AO_No_Error) {
12287     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12288     return QualType();
12289   }
12290 
12291   if (lval == Expr::LV_IncompleteVoidType) {
12292     // Taking the address of a void variable is technically illegal, but we
12293     // allow it in cases which are otherwise valid.
12294     // Example: "extern void x; void* y = &x;".
12295     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12296   }
12297 
12298   // If the operand has type "type", the result has type "pointer to type".
12299   if (op->getType()->isObjCObjectType())
12300     return Context.getObjCObjectPointerType(op->getType());
12301 
12302   CheckAddressOfPackedMember(op);
12303 
12304   return Context.getPointerType(op->getType());
12305 }
12306 
12307 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12308   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12309   if (!DRE)
12310     return;
12311   const Decl *D = DRE->getDecl();
12312   if (!D)
12313     return;
12314   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12315   if (!Param)
12316     return;
12317   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12318     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12319       return;
12320   if (FunctionScopeInfo *FD = S.getCurFunction())
12321     if (!FD->ModifiedNonNullParams.count(Param))
12322       FD->ModifiedNonNullParams.insert(Param);
12323 }
12324 
12325 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12326 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12327                                         SourceLocation OpLoc) {
12328   if (Op->isTypeDependent())
12329     return S.Context.DependentTy;
12330 
12331   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12332   if (ConvResult.isInvalid())
12333     return QualType();
12334   Op = ConvResult.get();
12335   QualType OpTy = Op->getType();
12336   QualType Result;
12337 
12338   if (isa<CXXReinterpretCastExpr>(Op)) {
12339     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12340     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12341                                      Op->getSourceRange());
12342   }
12343 
12344   if (const PointerType *PT = OpTy->getAs<PointerType>())
12345   {
12346     Result = PT->getPointeeType();
12347   }
12348   else if (const ObjCObjectPointerType *OPT =
12349              OpTy->getAs<ObjCObjectPointerType>())
12350     Result = OPT->getPointeeType();
12351   else {
12352     ExprResult PR = S.CheckPlaceholderExpr(Op);
12353     if (PR.isInvalid()) return QualType();
12354     if (PR.get() != Op)
12355       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12356   }
12357 
12358   if (Result.isNull()) {
12359     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12360       << OpTy << Op->getSourceRange();
12361     return QualType();
12362   }
12363 
12364   // Note that per both C89 and C99, indirection is always legal, even if Result
12365   // is an incomplete type or void.  It would be possible to warn about
12366   // dereferencing a void pointer, but it's completely well-defined, and such a
12367   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12368   // for pointers to 'void' but is fine for any other pointer type:
12369   //
12370   // C++ [expr.unary.op]p1:
12371   //   [...] the expression to which [the unary * operator] is applied shall
12372   //   be a pointer to an object type, or a pointer to a function type
12373   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12374     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12375       << OpTy << Op->getSourceRange();
12376 
12377   // Dereferences are usually l-values...
12378   VK = VK_LValue;
12379 
12380   // ...except that certain expressions are never l-values in C.
12381   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12382     VK = VK_RValue;
12383 
12384   return Result;
12385 }
12386 
12387 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12388   BinaryOperatorKind Opc;
12389   switch (Kind) {
12390   default: llvm_unreachable("Unknown binop!");
12391   case tok::periodstar:           Opc = BO_PtrMemD; break;
12392   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12393   case tok::star:                 Opc = BO_Mul; break;
12394   case tok::slash:                Opc = BO_Div; break;
12395   case tok::percent:              Opc = BO_Rem; break;
12396   case tok::plus:                 Opc = BO_Add; break;
12397   case tok::minus:                Opc = BO_Sub; break;
12398   case tok::lessless:             Opc = BO_Shl; break;
12399   case tok::greatergreater:       Opc = BO_Shr; break;
12400   case tok::lessequal:            Opc = BO_LE; break;
12401   case tok::less:                 Opc = BO_LT; break;
12402   case tok::greaterequal:         Opc = BO_GE; break;
12403   case tok::greater:              Opc = BO_GT; break;
12404   case tok::exclaimequal:         Opc = BO_NE; break;
12405   case tok::equalequal:           Opc = BO_EQ; break;
12406   case tok::spaceship:            Opc = BO_Cmp; break;
12407   case tok::amp:                  Opc = BO_And; break;
12408   case tok::caret:                Opc = BO_Xor; break;
12409   case tok::pipe:                 Opc = BO_Or; break;
12410   case tok::ampamp:               Opc = BO_LAnd; break;
12411   case tok::pipepipe:             Opc = BO_LOr; break;
12412   case tok::equal:                Opc = BO_Assign; break;
12413   case tok::starequal:            Opc = BO_MulAssign; break;
12414   case tok::slashequal:           Opc = BO_DivAssign; break;
12415   case tok::percentequal:         Opc = BO_RemAssign; break;
12416   case tok::plusequal:            Opc = BO_AddAssign; break;
12417   case tok::minusequal:           Opc = BO_SubAssign; break;
12418   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12419   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12420   case tok::ampequal:             Opc = BO_AndAssign; break;
12421   case tok::caretequal:           Opc = BO_XorAssign; break;
12422   case tok::pipeequal:            Opc = BO_OrAssign; break;
12423   case tok::comma:                Opc = BO_Comma; break;
12424   }
12425   return Opc;
12426 }
12427 
12428 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12429   tok::TokenKind Kind) {
12430   UnaryOperatorKind Opc;
12431   switch (Kind) {
12432   default: llvm_unreachable("Unknown unary op!");
12433   case tok::plusplus:     Opc = UO_PreInc; break;
12434   case tok::minusminus:   Opc = UO_PreDec; break;
12435   case tok::amp:          Opc = UO_AddrOf; break;
12436   case tok::star:         Opc = UO_Deref; break;
12437   case tok::plus:         Opc = UO_Plus; break;
12438   case tok::minus:        Opc = UO_Minus; break;
12439   case tok::tilde:        Opc = UO_Not; break;
12440   case tok::exclaim:      Opc = UO_LNot; break;
12441   case tok::kw___real:    Opc = UO_Real; break;
12442   case tok::kw___imag:    Opc = UO_Imag; break;
12443   case tok::kw___extension__: Opc = UO_Extension; break;
12444   }
12445   return Opc;
12446 }
12447 
12448 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12449 /// This warning suppressed in the event of macro expansions.
12450 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12451                                    SourceLocation OpLoc, bool IsBuiltin) {
12452   if (S.inTemplateInstantiation())
12453     return;
12454   if (S.isUnevaluatedContext())
12455     return;
12456   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12457     return;
12458   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12459   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12460   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12461   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12462   if (!LHSDeclRef || !RHSDeclRef ||
12463       LHSDeclRef->getLocation().isMacroID() ||
12464       RHSDeclRef->getLocation().isMacroID())
12465     return;
12466   const ValueDecl *LHSDecl =
12467     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12468   const ValueDecl *RHSDecl =
12469     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12470   if (LHSDecl != RHSDecl)
12471     return;
12472   if (LHSDecl->getType().isVolatileQualified())
12473     return;
12474   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12475     if (RefTy->getPointeeType().isVolatileQualified())
12476       return;
12477 
12478   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12479                           : diag::warn_self_assignment_overloaded)
12480       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12481       << RHSExpr->getSourceRange();
12482 }
12483 
12484 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12485 /// is usually indicative of introspection within the Objective-C pointer.
12486 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12487                                           SourceLocation OpLoc) {
12488   if (!S.getLangOpts().ObjC)
12489     return;
12490 
12491   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12492   const Expr *LHS = L.get();
12493   const Expr *RHS = R.get();
12494 
12495   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12496     ObjCPointerExpr = LHS;
12497     OtherExpr = RHS;
12498   }
12499   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12500     ObjCPointerExpr = RHS;
12501     OtherExpr = LHS;
12502   }
12503 
12504   // This warning is deliberately made very specific to reduce false
12505   // positives with logic that uses '&' for hashing.  This logic mainly
12506   // looks for code trying to introspect into tagged pointers, which
12507   // code should generally never do.
12508   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12509     unsigned Diag = diag::warn_objc_pointer_masking;
12510     // Determine if we are introspecting the result of performSelectorXXX.
12511     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12512     // Special case messages to -performSelector and friends, which
12513     // can return non-pointer values boxed in a pointer value.
12514     // Some clients may wish to silence warnings in this subcase.
12515     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12516       Selector S = ME->getSelector();
12517       StringRef SelArg0 = S.getNameForSlot(0);
12518       if (SelArg0.startswith("performSelector"))
12519         Diag = diag::warn_objc_pointer_masking_performSelector;
12520     }
12521 
12522     S.Diag(OpLoc, Diag)
12523       << ObjCPointerExpr->getSourceRange();
12524   }
12525 }
12526 
12527 static NamedDecl *getDeclFromExpr(Expr *E) {
12528   if (!E)
12529     return nullptr;
12530   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12531     return DRE->getDecl();
12532   if (auto *ME = dyn_cast<MemberExpr>(E))
12533     return ME->getMemberDecl();
12534   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12535     return IRE->getDecl();
12536   return nullptr;
12537 }
12538 
12539 // This helper function promotes a binary operator's operands (which are of a
12540 // half vector type) to a vector of floats and then truncates the result to
12541 // a vector of either half or short.
12542 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12543                                       BinaryOperatorKind Opc, QualType ResultTy,
12544                                       ExprValueKind VK, ExprObjectKind OK,
12545                                       bool IsCompAssign, SourceLocation OpLoc,
12546                                       FPOptions FPFeatures) {
12547   auto &Context = S.getASTContext();
12548   assert((isVector(ResultTy, Context.HalfTy) ||
12549           isVector(ResultTy, Context.ShortTy)) &&
12550          "Result must be a vector of half or short");
12551   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12552          isVector(RHS.get()->getType(), Context.HalfTy) &&
12553          "both operands expected to be a half vector");
12554 
12555   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12556   QualType BinOpResTy = RHS.get()->getType();
12557 
12558   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12559   // change BinOpResTy to a vector of ints.
12560   if (isVector(ResultTy, Context.ShortTy))
12561     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12562 
12563   if (IsCompAssign)
12564     return new (Context) CompoundAssignOperator(
12565         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12566         OpLoc, FPFeatures);
12567 
12568   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12569   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12570                                           VK, OK, OpLoc, FPFeatures);
12571   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12572 }
12573 
12574 static std::pair<ExprResult, ExprResult>
12575 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12576                            Expr *RHSExpr) {
12577   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12578   if (!S.getLangOpts().CPlusPlus) {
12579     // C cannot handle TypoExpr nodes on either side of a binop because it
12580     // doesn't handle dependent types properly, so make sure any TypoExprs have
12581     // been dealt with before checking the operands.
12582     LHS = S.CorrectDelayedTyposInExpr(LHS);
12583     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12584       if (Opc != BO_Assign)
12585         return ExprResult(E);
12586       // Avoid correcting the RHS to the same Expr as the LHS.
12587       Decl *D = getDeclFromExpr(E);
12588       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12589     });
12590   }
12591   return std::make_pair(LHS, RHS);
12592 }
12593 
12594 /// Returns true if conversion between vectors of halfs and vectors of floats
12595 /// is needed.
12596 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12597                                      QualType SrcType) {
12598   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12599          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12600          isVector(SrcType, Ctx.HalfTy);
12601 }
12602 
12603 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12604 /// operator @p Opc at location @c TokLoc. This routine only supports
12605 /// built-in operations; ActOnBinOp handles overloaded operators.
12606 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12607                                     BinaryOperatorKind Opc,
12608                                     Expr *LHSExpr, Expr *RHSExpr) {
12609   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12610     // The syntax only allows initializer lists on the RHS of assignment,
12611     // so we don't need to worry about accepting invalid code for
12612     // non-assignment operators.
12613     // C++11 5.17p9:
12614     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12615     //   of x = {} is x = T().
12616     InitializationKind Kind = InitializationKind::CreateDirectList(
12617         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12618     InitializedEntity Entity =
12619         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12620     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12621     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12622     if (Init.isInvalid())
12623       return Init;
12624     RHSExpr = Init.get();
12625   }
12626 
12627   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12628   QualType ResultTy;     // Result type of the binary operator.
12629   // The following two variables are used for compound assignment operators
12630   QualType CompLHSTy;    // Type of LHS after promotions for computation
12631   QualType CompResultTy; // Type of computation result
12632   ExprValueKind VK = VK_RValue;
12633   ExprObjectKind OK = OK_Ordinary;
12634   bool ConvertHalfVec = false;
12635 
12636   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12637   if (!LHS.isUsable() || !RHS.isUsable())
12638     return ExprError();
12639 
12640   if (getLangOpts().OpenCL) {
12641     QualType LHSTy = LHSExpr->getType();
12642     QualType RHSTy = RHSExpr->getType();
12643     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12644     // the ATOMIC_VAR_INIT macro.
12645     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12646       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12647       if (BO_Assign == Opc)
12648         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12649       else
12650         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12651       return ExprError();
12652     }
12653 
12654     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12655     // only with a builtin functions and therefore should be disallowed here.
12656     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12657         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12658         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12659         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12660       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12661       return ExprError();
12662     }
12663   }
12664 
12665   // Diagnose operations on the unsupported types for OpenMP device compilation.
12666   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12667     if (Opc != BO_Assign && Opc != BO_Comma) {
12668       checkOpenMPDeviceExpr(LHSExpr);
12669       checkOpenMPDeviceExpr(RHSExpr);
12670     }
12671   }
12672 
12673   switch (Opc) {
12674   case BO_Assign:
12675     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12676     if (getLangOpts().CPlusPlus &&
12677         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12678       VK = LHS.get()->getValueKind();
12679       OK = LHS.get()->getObjectKind();
12680     }
12681     if (!ResultTy.isNull()) {
12682       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12683       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12684 
12685       // Avoid copying a block to the heap if the block is assigned to a local
12686       // auto variable that is declared in the same scope as the block. This
12687       // optimization is unsafe if the local variable is declared in an outer
12688       // scope. For example:
12689       //
12690       // BlockTy b;
12691       // {
12692       //   b = ^{...};
12693       // }
12694       // // It is unsafe to invoke the block here if it wasn't copied to the
12695       // // heap.
12696       // b();
12697 
12698       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12699         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12700           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12701             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12702               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12703     }
12704     RecordModifiableNonNullParam(*this, LHS.get());
12705     break;
12706   case BO_PtrMemD:
12707   case BO_PtrMemI:
12708     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12709                                             Opc == BO_PtrMemI);
12710     break;
12711   case BO_Mul:
12712   case BO_Div:
12713     ConvertHalfVec = true;
12714     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12715                                            Opc == BO_Div);
12716     break;
12717   case BO_Rem:
12718     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12719     break;
12720   case BO_Add:
12721     ConvertHalfVec = true;
12722     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12723     break;
12724   case BO_Sub:
12725     ConvertHalfVec = true;
12726     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12727     break;
12728   case BO_Shl:
12729   case BO_Shr:
12730     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12731     break;
12732   case BO_LE:
12733   case BO_LT:
12734   case BO_GE:
12735   case BO_GT:
12736     ConvertHalfVec = true;
12737     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12738     break;
12739   case BO_EQ:
12740   case BO_NE:
12741     ConvertHalfVec = true;
12742     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12743     break;
12744   case BO_Cmp:
12745     ConvertHalfVec = true;
12746     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12747     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12748     break;
12749   case BO_And:
12750     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12751     LLVM_FALLTHROUGH;
12752   case BO_Xor:
12753   case BO_Or:
12754     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12755     break;
12756   case BO_LAnd:
12757   case BO_LOr:
12758     ConvertHalfVec = true;
12759     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12760     break;
12761   case BO_MulAssign:
12762   case BO_DivAssign:
12763     ConvertHalfVec = true;
12764     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12765                                                Opc == BO_DivAssign);
12766     CompLHSTy = CompResultTy;
12767     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12768       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12769     break;
12770   case BO_RemAssign:
12771     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12772     CompLHSTy = CompResultTy;
12773     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12774       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12775     break;
12776   case BO_AddAssign:
12777     ConvertHalfVec = true;
12778     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12779     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12780       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12781     break;
12782   case BO_SubAssign:
12783     ConvertHalfVec = true;
12784     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12785     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12786       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12787     break;
12788   case BO_ShlAssign:
12789   case BO_ShrAssign:
12790     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12791     CompLHSTy = CompResultTy;
12792     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12793       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12794     break;
12795   case BO_AndAssign:
12796   case BO_OrAssign: // fallthrough
12797     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12798     LLVM_FALLTHROUGH;
12799   case BO_XorAssign:
12800     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12801     CompLHSTy = CompResultTy;
12802     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12803       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12804     break;
12805   case BO_Comma:
12806     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12807     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12808       VK = RHS.get()->getValueKind();
12809       OK = RHS.get()->getObjectKind();
12810     }
12811     break;
12812   }
12813   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12814     return ExprError();
12815 
12816   // Some of the binary operations require promoting operands of half vector to
12817   // float vectors and truncating the result back to half vector. For now, we do
12818   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12819   // arm64).
12820   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12821          isVector(LHS.get()->getType(), Context.HalfTy) &&
12822          "both sides are half vectors or neither sides are");
12823   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12824                                             LHS.get()->getType());
12825 
12826   // Check for array bounds violations for both sides of the BinaryOperator
12827   CheckArrayAccess(LHS.get());
12828   CheckArrayAccess(RHS.get());
12829 
12830   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12831     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12832                                                  &Context.Idents.get("object_setClass"),
12833                                                  SourceLocation(), LookupOrdinaryName);
12834     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12835       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12836       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12837           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12838                                         "object_setClass(")
12839           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12840                                           ",")
12841           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12842     }
12843     else
12844       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12845   }
12846   else if (const ObjCIvarRefExpr *OIRE =
12847            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12848     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12849 
12850   // Opc is not a compound assignment if CompResultTy is null.
12851   if (CompResultTy.isNull()) {
12852     if (ConvertHalfVec)
12853       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12854                                  OpLoc, FPFeatures);
12855     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12856                                         OK, OpLoc, FPFeatures);
12857   }
12858 
12859   // Handle compound assignments.
12860   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12861       OK_ObjCProperty) {
12862     VK = VK_LValue;
12863     OK = LHS.get()->getObjectKind();
12864   }
12865 
12866   if (ConvertHalfVec)
12867     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12868                                OpLoc, FPFeatures);
12869 
12870   return new (Context) CompoundAssignOperator(
12871       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12872       OpLoc, FPFeatures);
12873 }
12874 
12875 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12876 /// operators are mixed in a way that suggests that the programmer forgot that
12877 /// comparison operators have higher precedence. The most typical example of
12878 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12879 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12880                                       SourceLocation OpLoc, Expr *LHSExpr,
12881                                       Expr *RHSExpr) {
12882   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12883   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12884 
12885   // Check that one of the sides is a comparison operator and the other isn't.
12886   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12887   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12888   if (isLeftComp == isRightComp)
12889     return;
12890 
12891   // Bitwise operations are sometimes used as eager logical ops.
12892   // Don't diagnose this.
12893   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12894   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12895   if (isLeftBitwise || isRightBitwise)
12896     return;
12897 
12898   SourceRange DiagRange = isLeftComp
12899                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12900                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12901   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12902   SourceRange ParensRange =
12903       isLeftComp
12904           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12905           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12906 
12907   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12908     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12909   SuggestParentheses(Self, OpLoc,
12910     Self.PDiag(diag::note_precedence_silence) << OpStr,
12911     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12912   SuggestParentheses(Self, OpLoc,
12913     Self.PDiag(diag::note_precedence_bitwise_first)
12914       << BinaryOperator::getOpcodeStr(Opc),
12915     ParensRange);
12916 }
12917 
12918 /// It accepts a '&&' expr that is inside a '||' one.
12919 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12920 /// in parentheses.
12921 static void
12922 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12923                                        BinaryOperator *Bop) {
12924   assert(Bop->getOpcode() == BO_LAnd);
12925   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12926       << Bop->getSourceRange() << OpLoc;
12927   SuggestParentheses(Self, Bop->getOperatorLoc(),
12928     Self.PDiag(diag::note_precedence_silence)
12929       << Bop->getOpcodeStr(),
12930     Bop->getSourceRange());
12931 }
12932 
12933 /// Returns true if the given expression can be evaluated as a constant
12934 /// 'true'.
12935 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12936   bool Res;
12937   return !E->isValueDependent() &&
12938          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12939 }
12940 
12941 /// Returns true if the given expression can be evaluated as a constant
12942 /// 'false'.
12943 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12944   bool Res;
12945   return !E->isValueDependent() &&
12946          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12947 }
12948 
12949 /// Look for '&&' in the left hand of a '||' expr.
12950 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12951                                              Expr *LHSExpr, Expr *RHSExpr) {
12952   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12953     if (Bop->getOpcode() == BO_LAnd) {
12954       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12955       if (EvaluatesAsFalse(S, RHSExpr))
12956         return;
12957       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12958       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12959         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12960     } else if (Bop->getOpcode() == BO_LOr) {
12961       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12962         // If it's "a || b && 1 || c" we didn't warn earlier for
12963         // "a || b && 1", but warn now.
12964         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12965           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12966       }
12967     }
12968   }
12969 }
12970 
12971 /// Look for '&&' in the right hand of a '||' expr.
12972 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12973                                              Expr *LHSExpr, Expr *RHSExpr) {
12974   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12975     if (Bop->getOpcode() == BO_LAnd) {
12976       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12977       if (EvaluatesAsFalse(S, LHSExpr))
12978         return;
12979       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12980       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12981         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12982     }
12983   }
12984 }
12985 
12986 /// Look for bitwise op in the left or right hand of a bitwise op with
12987 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12988 /// the '&' expression in parentheses.
12989 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12990                                          SourceLocation OpLoc, Expr *SubExpr) {
12991   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12992     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12993       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12994         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12995         << Bop->getSourceRange() << OpLoc;
12996       SuggestParentheses(S, Bop->getOperatorLoc(),
12997         S.PDiag(diag::note_precedence_silence)
12998           << Bop->getOpcodeStr(),
12999         Bop->getSourceRange());
13000     }
13001   }
13002 }
13003 
13004 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13005                                     Expr *SubExpr, StringRef Shift) {
13006   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13007     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13008       StringRef Op = Bop->getOpcodeStr();
13009       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13010           << Bop->getSourceRange() << OpLoc << Shift << Op;
13011       SuggestParentheses(S, Bop->getOperatorLoc(),
13012           S.PDiag(diag::note_precedence_silence) << Op,
13013           Bop->getSourceRange());
13014     }
13015   }
13016 }
13017 
13018 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13019                                  Expr *LHSExpr, Expr *RHSExpr) {
13020   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13021   if (!OCE)
13022     return;
13023 
13024   FunctionDecl *FD = OCE->getDirectCallee();
13025   if (!FD || !FD->isOverloadedOperator())
13026     return;
13027 
13028   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13029   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13030     return;
13031 
13032   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13033       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13034       << (Kind == OO_LessLess);
13035   SuggestParentheses(S, OCE->getOperatorLoc(),
13036                      S.PDiag(diag::note_precedence_silence)
13037                          << (Kind == OO_LessLess ? "<<" : ">>"),
13038                      OCE->getSourceRange());
13039   SuggestParentheses(
13040       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13041       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13042 }
13043 
13044 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13045 /// precedence.
13046 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13047                                     SourceLocation OpLoc, Expr *LHSExpr,
13048                                     Expr *RHSExpr){
13049   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13050   if (BinaryOperator::isBitwiseOp(Opc))
13051     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13052 
13053   // Diagnose "arg1 & arg2 | arg3"
13054   if ((Opc == BO_Or || Opc == BO_Xor) &&
13055       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13056     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13057     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13058   }
13059 
13060   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13061   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13062   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13063     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13064     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13065   }
13066 
13067   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13068       || Opc == BO_Shr) {
13069     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13070     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13071     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13072   }
13073 
13074   // Warn on overloaded shift operators and comparisons, such as:
13075   // cout << 5 == 4;
13076   if (BinaryOperator::isComparisonOp(Opc))
13077     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13078 }
13079 
13080 // Binary Operators.  'Tok' is the token for the operator.
13081 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13082                             tok::TokenKind Kind,
13083                             Expr *LHSExpr, Expr *RHSExpr) {
13084   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13085   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13086   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13087 
13088   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13089   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13090 
13091   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13092 }
13093 
13094 /// Build an overloaded binary operator expression in the given scope.
13095 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13096                                        BinaryOperatorKind Opc,
13097                                        Expr *LHS, Expr *RHS) {
13098   switch (Opc) {
13099   case BO_Assign:
13100   case BO_DivAssign:
13101   case BO_RemAssign:
13102   case BO_SubAssign:
13103   case BO_AndAssign:
13104   case BO_OrAssign:
13105   case BO_XorAssign:
13106     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13107     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13108     break;
13109   default:
13110     break;
13111   }
13112 
13113   // Find all of the overloaded operators visible from this
13114   // point. We perform both an operator-name lookup from the local
13115   // scope and an argument-dependent lookup based on the types of
13116   // the arguments.
13117   UnresolvedSet<16> Functions;
13118   OverloadedOperatorKind OverOp
13119     = BinaryOperator::getOverloadedOperator(Opc);
13120   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13121     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13122                                    RHS->getType(), Functions);
13123 
13124   // Build the (potentially-overloaded, potentially-dependent)
13125   // binary operation.
13126   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13127 }
13128 
13129 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13130                             BinaryOperatorKind Opc,
13131                             Expr *LHSExpr, Expr *RHSExpr) {
13132   ExprResult LHS, RHS;
13133   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13134   if (!LHS.isUsable() || !RHS.isUsable())
13135     return ExprError();
13136   LHSExpr = LHS.get();
13137   RHSExpr = RHS.get();
13138 
13139   // We want to end up calling one of checkPseudoObjectAssignment
13140   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13141   // both expressions are overloadable or either is type-dependent),
13142   // or CreateBuiltinBinOp (in any other case).  We also want to get
13143   // any placeholder types out of the way.
13144 
13145   // Handle pseudo-objects in the LHS.
13146   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13147     // Assignments with a pseudo-object l-value need special analysis.
13148     if (pty->getKind() == BuiltinType::PseudoObject &&
13149         BinaryOperator::isAssignmentOp(Opc))
13150       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13151 
13152     // Don't resolve overloads if the other type is overloadable.
13153     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13154       // We can't actually test that if we still have a placeholder,
13155       // though.  Fortunately, none of the exceptions we see in that
13156       // code below are valid when the LHS is an overload set.  Note
13157       // that an overload set can be dependently-typed, but it never
13158       // instantiates to having an overloadable type.
13159       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13160       if (resolvedRHS.isInvalid()) return ExprError();
13161       RHSExpr = resolvedRHS.get();
13162 
13163       if (RHSExpr->isTypeDependent() ||
13164           RHSExpr->getType()->isOverloadableType())
13165         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13166     }
13167 
13168     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13169     // template, diagnose the missing 'template' keyword instead of diagnosing
13170     // an invalid use of a bound member function.
13171     //
13172     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13173     // to C++1z [over.over]/1.4, but we already checked for that case above.
13174     if (Opc == BO_LT && inTemplateInstantiation() &&
13175         (pty->getKind() == BuiltinType::BoundMember ||
13176          pty->getKind() == BuiltinType::Overload)) {
13177       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13178       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13179           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13180             return isa<FunctionTemplateDecl>(ND);
13181           })) {
13182         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13183                                 : OE->getNameLoc(),
13184              diag::err_template_kw_missing)
13185           << OE->getName().getAsString() << "";
13186         return ExprError();
13187       }
13188     }
13189 
13190     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13191     if (LHS.isInvalid()) return ExprError();
13192     LHSExpr = LHS.get();
13193   }
13194 
13195   // Handle pseudo-objects in the RHS.
13196   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13197     // An overload in the RHS can potentially be resolved by the type
13198     // being assigned to.
13199     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13200       if (getLangOpts().CPlusPlus &&
13201           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13202            LHSExpr->getType()->isOverloadableType()))
13203         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13204 
13205       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13206     }
13207 
13208     // Don't resolve overloads if the other type is overloadable.
13209     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13210         LHSExpr->getType()->isOverloadableType())
13211       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13212 
13213     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13214     if (!resolvedRHS.isUsable()) return ExprError();
13215     RHSExpr = resolvedRHS.get();
13216   }
13217 
13218   if (getLangOpts().CPlusPlus) {
13219     // If either expression is type-dependent, always build an
13220     // overloaded op.
13221     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13222       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13223 
13224     // Otherwise, build an overloaded op if either expression has an
13225     // overloadable type.
13226     if (LHSExpr->getType()->isOverloadableType() ||
13227         RHSExpr->getType()->isOverloadableType())
13228       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13229   }
13230 
13231   // Build a built-in binary operation.
13232   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13233 }
13234 
13235 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13236   if (T.isNull() || T->isDependentType())
13237     return false;
13238 
13239   if (!T->isPromotableIntegerType())
13240     return true;
13241 
13242   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13243 }
13244 
13245 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13246                                       UnaryOperatorKind Opc,
13247                                       Expr *InputExpr) {
13248   ExprResult Input = InputExpr;
13249   ExprValueKind VK = VK_RValue;
13250   ExprObjectKind OK = OK_Ordinary;
13251   QualType resultType;
13252   bool CanOverflow = false;
13253 
13254   bool ConvertHalfVec = false;
13255   if (getLangOpts().OpenCL) {
13256     QualType Ty = InputExpr->getType();
13257     // The only legal unary operation for atomics is '&'.
13258     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13259     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13260     // only with a builtin functions and therefore should be disallowed here.
13261         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13262         || Ty->isBlockPointerType())) {
13263       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13264                        << InputExpr->getType()
13265                        << Input.get()->getSourceRange());
13266     }
13267   }
13268   // Diagnose operations on the unsupported types for OpenMP device compilation.
13269   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13270     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13271         UnaryOperator::isArithmeticOp(Opc))
13272       checkOpenMPDeviceExpr(InputExpr);
13273   }
13274 
13275   switch (Opc) {
13276   case UO_PreInc:
13277   case UO_PreDec:
13278   case UO_PostInc:
13279   case UO_PostDec:
13280     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13281                                                 OpLoc,
13282                                                 Opc == UO_PreInc ||
13283                                                 Opc == UO_PostInc,
13284                                                 Opc == UO_PreInc ||
13285                                                 Opc == UO_PreDec);
13286     CanOverflow = isOverflowingIntegerType(Context, resultType);
13287     break;
13288   case UO_AddrOf:
13289     resultType = CheckAddressOfOperand(Input, OpLoc);
13290     CheckAddressOfNoDeref(InputExpr);
13291     RecordModifiableNonNullParam(*this, InputExpr);
13292     break;
13293   case UO_Deref: {
13294     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13295     if (Input.isInvalid()) return ExprError();
13296     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13297     break;
13298   }
13299   case UO_Plus:
13300   case UO_Minus:
13301     CanOverflow = Opc == UO_Minus &&
13302                   isOverflowingIntegerType(Context, Input.get()->getType());
13303     Input = UsualUnaryConversions(Input.get());
13304     if (Input.isInvalid()) return ExprError();
13305     // Unary plus and minus require promoting an operand of half vector to a
13306     // float vector and truncating the result back to a half vector. For now, we
13307     // do this only when HalfArgsAndReturns is set (that is, when the target is
13308     // arm or arm64).
13309     ConvertHalfVec =
13310         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13311 
13312     // If the operand is a half vector, promote it to a float vector.
13313     if (ConvertHalfVec)
13314       Input = convertVector(Input.get(), Context.FloatTy, *this);
13315     resultType = Input.get()->getType();
13316     if (resultType->isDependentType())
13317       break;
13318     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13319       break;
13320     else if (resultType->isVectorType() &&
13321              // The z vector extensions don't allow + or - with bool vectors.
13322              (!Context.getLangOpts().ZVector ||
13323               resultType->getAs<VectorType>()->getVectorKind() !=
13324               VectorType::AltiVecBool))
13325       break;
13326     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13327              Opc == UO_Plus &&
13328              resultType->isPointerType())
13329       break;
13330 
13331     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13332       << resultType << Input.get()->getSourceRange());
13333 
13334   case UO_Not: // bitwise complement
13335     Input = UsualUnaryConversions(Input.get());
13336     if (Input.isInvalid())
13337       return ExprError();
13338     resultType = Input.get()->getType();
13339 
13340     if (resultType->isDependentType())
13341       break;
13342     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13343     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13344       // C99 does not support '~' for complex conjugation.
13345       Diag(OpLoc, diag::ext_integer_complement_complex)
13346           << resultType << Input.get()->getSourceRange();
13347     else if (resultType->hasIntegerRepresentation())
13348       break;
13349     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13350       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13351       // on vector float types.
13352       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13353       if (!T->isIntegerType())
13354         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13355                           << resultType << Input.get()->getSourceRange());
13356     } else {
13357       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13358                        << resultType << Input.get()->getSourceRange());
13359     }
13360     break;
13361 
13362   case UO_LNot: // logical negation
13363     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13364     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13365     if (Input.isInvalid()) return ExprError();
13366     resultType = Input.get()->getType();
13367 
13368     // Though we still have to promote half FP to float...
13369     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13370       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13371       resultType = Context.FloatTy;
13372     }
13373 
13374     if (resultType->isDependentType())
13375       break;
13376     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13377       // C99 6.5.3.3p1: ok, fallthrough;
13378       if (Context.getLangOpts().CPlusPlus) {
13379         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13380         // operand contextually converted to bool.
13381         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13382                                   ScalarTypeToBooleanCastKind(resultType));
13383       } else if (Context.getLangOpts().OpenCL &&
13384                  Context.getLangOpts().OpenCLVersion < 120) {
13385         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13386         // operate on scalar float types.
13387         if (!resultType->isIntegerType() && !resultType->isPointerType())
13388           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13389                            << resultType << Input.get()->getSourceRange());
13390       }
13391     } else if (resultType->isExtVectorType()) {
13392       if (Context.getLangOpts().OpenCL &&
13393           Context.getLangOpts().OpenCLVersion < 120 &&
13394           !Context.getLangOpts().OpenCLCPlusPlus) {
13395         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13396         // operate on vector float types.
13397         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13398         if (!T->isIntegerType())
13399           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13400                            << resultType << Input.get()->getSourceRange());
13401       }
13402       // Vector logical not returns the signed variant of the operand type.
13403       resultType = GetSignedVectorType(resultType);
13404       break;
13405     } else {
13406       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13407       //        type in C++. We should allow that here too.
13408       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13409         << resultType << Input.get()->getSourceRange());
13410     }
13411 
13412     // LNot always has type int. C99 6.5.3.3p5.
13413     // In C++, it's bool. C++ 5.3.1p8
13414     resultType = Context.getLogicalOperationType();
13415     break;
13416   case UO_Real:
13417   case UO_Imag:
13418     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13419     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13420     // complex l-values to ordinary l-values and all other values to r-values.
13421     if (Input.isInvalid()) return ExprError();
13422     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13423       if (Input.get()->getValueKind() != VK_RValue &&
13424           Input.get()->getObjectKind() == OK_Ordinary)
13425         VK = Input.get()->getValueKind();
13426     } else if (!getLangOpts().CPlusPlus) {
13427       // In C, a volatile scalar is read by __imag. In C++, it is not.
13428       Input = DefaultLvalueConversion(Input.get());
13429     }
13430     break;
13431   case UO_Extension:
13432     resultType = Input.get()->getType();
13433     VK = Input.get()->getValueKind();
13434     OK = Input.get()->getObjectKind();
13435     break;
13436   case UO_Coawait:
13437     // It's unnecessary to represent the pass-through operator co_await in the
13438     // AST; just return the input expression instead.
13439     assert(!Input.get()->getType()->isDependentType() &&
13440                    "the co_await expression must be non-dependant before "
13441                    "building operator co_await");
13442     return Input;
13443   }
13444   if (resultType.isNull() || Input.isInvalid())
13445     return ExprError();
13446 
13447   // Check for array bounds violations in the operand of the UnaryOperator,
13448   // except for the '*' and '&' operators that have to be handled specially
13449   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13450   // that are explicitly defined as valid by the standard).
13451   if (Opc != UO_AddrOf && Opc != UO_Deref)
13452     CheckArrayAccess(Input.get());
13453 
13454   auto *UO = new (Context)
13455       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13456 
13457   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13458       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13459     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13460 
13461   // Convert the result back to a half vector.
13462   if (ConvertHalfVec)
13463     return convertVector(UO, Context.HalfTy, *this);
13464   return UO;
13465 }
13466 
13467 /// Determine whether the given expression is a qualified member
13468 /// access expression, of a form that could be turned into a pointer to member
13469 /// with the address-of operator.
13470 bool Sema::isQualifiedMemberAccess(Expr *E) {
13471   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13472     if (!DRE->getQualifier())
13473       return false;
13474 
13475     ValueDecl *VD = DRE->getDecl();
13476     if (!VD->isCXXClassMember())
13477       return false;
13478 
13479     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13480       return true;
13481     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13482       return Method->isInstance();
13483 
13484     return false;
13485   }
13486 
13487   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13488     if (!ULE->getQualifier())
13489       return false;
13490 
13491     for (NamedDecl *D : ULE->decls()) {
13492       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13493         if (Method->isInstance())
13494           return true;
13495       } else {
13496         // Overload set does not contain methods.
13497         break;
13498       }
13499     }
13500 
13501     return false;
13502   }
13503 
13504   return false;
13505 }
13506 
13507 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13508                               UnaryOperatorKind Opc, Expr *Input) {
13509   // First things first: handle placeholders so that the
13510   // overloaded-operator check considers the right type.
13511   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13512     // Increment and decrement of pseudo-object references.
13513     if (pty->getKind() == BuiltinType::PseudoObject &&
13514         UnaryOperator::isIncrementDecrementOp(Opc))
13515       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13516 
13517     // extension is always a builtin operator.
13518     if (Opc == UO_Extension)
13519       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13520 
13521     // & gets special logic for several kinds of placeholder.
13522     // The builtin code knows what to do.
13523     if (Opc == UO_AddrOf &&
13524         (pty->getKind() == BuiltinType::Overload ||
13525          pty->getKind() == BuiltinType::UnknownAny ||
13526          pty->getKind() == BuiltinType::BoundMember))
13527       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13528 
13529     // Anything else needs to be handled now.
13530     ExprResult Result = CheckPlaceholderExpr(Input);
13531     if (Result.isInvalid()) return ExprError();
13532     Input = Result.get();
13533   }
13534 
13535   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13536       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13537       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13538     // Find all of the overloaded operators visible from this
13539     // point. We perform both an operator-name lookup from the local
13540     // scope and an argument-dependent lookup based on the types of
13541     // the arguments.
13542     UnresolvedSet<16> Functions;
13543     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13544     if (S && OverOp != OO_None)
13545       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13546                                    Functions);
13547 
13548     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13549   }
13550 
13551   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13552 }
13553 
13554 // Unary Operators.  'Tok' is the token for the operator.
13555 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13556                               tok::TokenKind Op, Expr *Input) {
13557   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13558 }
13559 
13560 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13561 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13562                                 LabelDecl *TheDecl) {
13563   TheDecl->markUsed(Context);
13564   // Create the AST node.  The address of a label always has type 'void*'.
13565   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13566                                      Context.getPointerType(Context.VoidTy));
13567 }
13568 
13569 void Sema::ActOnStartStmtExpr() {
13570   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13571 }
13572 
13573 void Sema::ActOnStmtExprError() {
13574   // Note that function is also called by TreeTransform when leaving a
13575   // StmtExpr scope without rebuilding anything.
13576 
13577   DiscardCleanupsInEvaluationContext();
13578   PopExpressionEvaluationContext();
13579 }
13580 
13581 ExprResult
13582 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13583                     SourceLocation RPLoc) { // "({..})"
13584   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13585   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13586 
13587   if (hasAnyUnrecoverableErrorsInThisFunction())
13588     DiscardCleanupsInEvaluationContext();
13589   assert(!Cleanup.exprNeedsCleanups() &&
13590          "cleanups within StmtExpr not correctly bound!");
13591   PopExpressionEvaluationContext();
13592 
13593   // FIXME: there are a variety of strange constraints to enforce here, for
13594   // example, it is not possible to goto into a stmt expression apparently.
13595   // More semantic analysis is needed.
13596 
13597   // If there are sub-stmts in the compound stmt, take the type of the last one
13598   // as the type of the stmtexpr.
13599   QualType Ty = Context.VoidTy;
13600   bool StmtExprMayBindToTemp = false;
13601   if (!Compound->body_empty()) {
13602     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13603     if (const auto *LastStmt =
13604             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13605       if (const Expr *Value = LastStmt->getExprStmt()) {
13606         StmtExprMayBindToTemp = true;
13607         Ty = Value->getType();
13608       }
13609     }
13610   }
13611 
13612   // FIXME: Check that expression type is complete/non-abstract; statement
13613   // expressions are not lvalues.
13614   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13615   if (StmtExprMayBindToTemp)
13616     return MaybeBindToTemporary(ResStmtExpr);
13617   return ResStmtExpr;
13618 }
13619 
13620 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13621   if (ER.isInvalid())
13622     return ExprError();
13623 
13624   // Do function/array conversion on the last expression, but not
13625   // lvalue-to-rvalue.  However, initialize an unqualified type.
13626   ER = DefaultFunctionArrayConversion(ER.get());
13627   if (ER.isInvalid())
13628     return ExprError();
13629   Expr *E = ER.get();
13630 
13631   if (E->isTypeDependent())
13632     return E;
13633 
13634   // In ARC, if the final expression ends in a consume, splice
13635   // the consume out and bind it later.  In the alternate case
13636   // (when dealing with a retainable type), the result
13637   // initialization will create a produce.  In both cases the
13638   // result will be +1, and we'll need to balance that out with
13639   // a bind.
13640   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13641   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13642     return Cast->getSubExpr();
13643 
13644   // FIXME: Provide a better location for the initialization.
13645   return PerformCopyInitialization(
13646       InitializedEntity::InitializeStmtExprResult(
13647           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13648       SourceLocation(), E);
13649 }
13650 
13651 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13652                                       TypeSourceInfo *TInfo,
13653                                       ArrayRef<OffsetOfComponent> Components,
13654                                       SourceLocation RParenLoc) {
13655   QualType ArgTy = TInfo->getType();
13656   bool Dependent = ArgTy->isDependentType();
13657   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13658 
13659   // We must have at least one component that refers to the type, and the first
13660   // one is known to be a field designator.  Verify that the ArgTy represents
13661   // a struct/union/class.
13662   if (!Dependent && !ArgTy->isRecordType())
13663     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13664                        << ArgTy << TypeRange);
13665 
13666   // Type must be complete per C99 7.17p3 because a declaring a variable
13667   // with an incomplete type would be ill-formed.
13668   if (!Dependent
13669       && RequireCompleteType(BuiltinLoc, ArgTy,
13670                              diag::err_offsetof_incomplete_type, TypeRange))
13671     return ExprError();
13672 
13673   bool DidWarnAboutNonPOD = false;
13674   QualType CurrentType = ArgTy;
13675   SmallVector<OffsetOfNode, 4> Comps;
13676   SmallVector<Expr*, 4> Exprs;
13677   for (const OffsetOfComponent &OC : Components) {
13678     if (OC.isBrackets) {
13679       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13680       if (!CurrentType->isDependentType()) {
13681         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13682         if(!AT)
13683           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13684                            << CurrentType);
13685         CurrentType = AT->getElementType();
13686       } else
13687         CurrentType = Context.DependentTy;
13688 
13689       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13690       if (IdxRval.isInvalid())
13691         return ExprError();
13692       Expr *Idx = IdxRval.get();
13693 
13694       // The expression must be an integral expression.
13695       // FIXME: An integral constant expression?
13696       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13697           !Idx->getType()->isIntegerType())
13698         return ExprError(
13699             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13700             << Idx->getSourceRange());
13701 
13702       // Record this array index.
13703       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13704       Exprs.push_back(Idx);
13705       continue;
13706     }
13707 
13708     // Offset of a field.
13709     if (CurrentType->isDependentType()) {
13710       // We have the offset of a field, but we can't look into the dependent
13711       // type. Just record the identifier of the field.
13712       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13713       CurrentType = Context.DependentTy;
13714       continue;
13715     }
13716 
13717     // We need to have a complete type to look into.
13718     if (RequireCompleteType(OC.LocStart, CurrentType,
13719                             diag::err_offsetof_incomplete_type))
13720       return ExprError();
13721 
13722     // Look for the designated field.
13723     const RecordType *RC = CurrentType->getAs<RecordType>();
13724     if (!RC)
13725       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13726                        << CurrentType);
13727     RecordDecl *RD = RC->getDecl();
13728 
13729     // C++ [lib.support.types]p5:
13730     //   The macro offsetof accepts a restricted set of type arguments in this
13731     //   International Standard. type shall be a POD structure or a POD union
13732     //   (clause 9).
13733     // C++11 [support.types]p4:
13734     //   If type is not a standard-layout class (Clause 9), the results are
13735     //   undefined.
13736     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13737       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13738       unsigned DiagID =
13739         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13740                             : diag::ext_offsetof_non_pod_type;
13741 
13742       if (!IsSafe && !DidWarnAboutNonPOD &&
13743           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13744                               PDiag(DiagID)
13745                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13746                               << CurrentType))
13747         DidWarnAboutNonPOD = true;
13748     }
13749 
13750     // Look for the field.
13751     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13752     LookupQualifiedName(R, RD);
13753     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13754     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13755     if (!MemberDecl) {
13756       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13757         MemberDecl = IndirectMemberDecl->getAnonField();
13758     }
13759 
13760     if (!MemberDecl)
13761       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13762                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13763                                                               OC.LocEnd));
13764 
13765     // C99 7.17p3:
13766     //   (If the specified member is a bit-field, the behavior is undefined.)
13767     //
13768     // We diagnose this as an error.
13769     if (MemberDecl->isBitField()) {
13770       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13771         << MemberDecl->getDeclName()
13772         << SourceRange(BuiltinLoc, RParenLoc);
13773       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13774       return ExprError();
13775     }
13776 
13777     RecordDecl *Parent = MemberDecl->getParent();
13778     if (IndirectMemberDecl)
13779       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13780 
13781     // If the member was found in a base class, introduce OffsetOfNodes for
13782     // the base class indirections.
13783     CXXBasePaths Paths;
13784     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13785                       Paths)) {
13786       if (Paths.getDetectedVirtual()) {
13787         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13788           << MemberDecl->getDeclName()
13789           << SourceRange(BuiltinLoc, RParenLoc);
13790         return ExprError();
13791       }
13792 
13793       CXXBasePath &Path = Paths.front();
13794       for (const CXXBasePathElement &B : Path)
13795         Comps.push_back(OffsetOfNode(B.Base));
13796     }
13797 
13798     if (IndirectMemberDecl) {
13799       for (auto *FI : IndirectMemberDecl->chain()) {
13800         assert(isa<FieldDecl>(FI));
13801         Comps.push_back(OffsetOfNode(OC.LocStart,
13802                                      cast<FieldDecl>(FI), OC.LocEnd));
13803       }
13804     } else
13805       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13806 
13807     CurrentType = MemberDecl->getType().getNonReferenceType();
13808   }
13809 
13810   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13811                               Comps, Exprs, RParenLoc);
13812 }
13813 
13814 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13815                                       SourceLocation BuiltinLoc,
13816                                       SourceLocation TypeLoc,
13817                                       ParsedType ParsedArgTy,
13818                                       ArrayRef<OffsetOfComponent> Components,
13819                                       SourceLocation RParenLoc) {
13820 
13821   TypeSourceInfo *ArgTInfo;
13822   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13823   if (ArgTy.isNull())
13824     return ExprError();
13825 
13826   if (!ArgTInfo)
13827     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13828 
13829   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13830 }
13831 
13832 
13833 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13834                                  Expr *CondExpr,
13835                                  Expr *LHSExpr, Expr *RHSExpr,
13836                                  SourceLocation RPLoc) {
13837   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13838 
13839   ExprValueKind VK = VK_RValue;
13840   ExprObjectKind OK = OK_Ordinary;
13841   QualType resType;
13842   bool ValueDependent = false;
13843   bool CondIsTrue = false;
13844   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13845     resType = Context.DependentTy;
13846     ValueDependent = true;
13847   } else {
13848     // The conditional expression is required to be a constant expression.
13849     llvm::APSInt condEval(32);
13850     ExprResult CondICE
13851       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13852           diag::err_typecheck_choose_expr_requires_constant, false);
13853     if (CondICE.isInvalid())
13854       return ExprError();
13855     CondExpr = CondICE.get();
13856     CondIsTrue = condEval.getZExtValue();
13857 
13858     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13859     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13860 
13861     resType = ActiveExpr->getType();
13862     ValueDependent = ActiveExpr->isValueDependent();
13863     VK = ActiveExpr->getValueKind();
13864     OK = ActiveExpr->getObjectKind();
13865   }
13866 
13867   return new (Context)
13868       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13869                  CondIsTrue, resType->isDependentType(), ValueDependent);
13870 }
13871 
13872 //===----------------------------------------------------------------------===//
13873 // Clang Extensions.
13874 //===----------------------------------------------------------------------===//
13875 
13876 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13877 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13878   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13879 
13880   if (LangOpts.CPlusPlus) {
13881     Decl *ManglingContextDecl;
13882     if (MangleNumberingContext *MCtx =
13883             getCurrentMangleNumberContext(Block->getDeclContext(),
13884                                           ManglingContextDecl)) {
13885       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13886       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13887     }
13888   }
13889 
13890   PushBlockScope(CurScope, Block);
13891   CurContext->addDecl(Block);
13892   if (CurScope)
13893     PushDeclContext(CurScope, Block);
13894   else
13895     CurContext = Block;
13896 
13897   getCurBlock()->HasImplicitReturnType = true;
13898 
13899   // Enter a new evaluation context to insulate the block from any
13900   // cleanups from the enclosing full-expression.
13901   PushExpressionEvaluationContext(
13902       ExpressionEvaluationContext::PotentiallyEvaluated);
13903 }
13904 
13905 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13906                                Scope *CurScope) {
13907   assert(ParamInfo.getIdentifier() == nullptr &&
13908          "block-id should have no identifier!");
13909   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13910   BlockScopeInfo *CurBlock = getCurBlock();
13911 
13912   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13913   QualType T = Sig->getType();
13914 
13915   // FIXME: We should allow unexpanded parameter packs here, but that would,
13916   // in turn, make the block expression contain unexpanded parameter packs.
13917   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13918     // Drop the parameters.
13919     FunctionProtoType::ExtProtoInfo EPI;
13920     EPI.HasTrailingReturn = false;
13921     EPI.TypeQuals.addConst();
13922     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13923     Sig = Context.getTrivialTypeSourceInfo(T);
13924   }
13925 
13926   // GetTypeForDeclarator always produces a function type for a block
13927   // literal signature.  Furthermore, it is always a FunctionProtoType
13928   // unless the function was written with a typedef.
13929   assert(T->isFunctionType() &&
13930          "GetTypeForDeclarator made a non-function block signature");
13931 
13932   // Look for an explicit signature in that function type.
13933   FunctionProtoTypeLoc ExplicitSignature;
13934 
13935   if ((ExplicitSignature = Sig->getTypeLoc()
13936                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
13937 
13938     // Check whether that explicit signature was synthesized by
13939     // GetTypeForDeclarator.  If so, don't save that as part of the
13940     // written signature.
13941     if (ExplicitSignature.getLocalRangeBegin() ==
13942         ExplicitSignature.getLocalRangeEnd()) {
13943       // This would be much cheaper if we stored TypeLocs instead of
13944       // TypeSourceInfos.
13945       TypeLoc Result = ExplicitSignature.getReturnLoc();
13946       unsigned Size = Result.getFullDataSize();
13947       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13948       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13949 
13950       ExplicitSignature = FunctionProtoTypeLoc();
13951     }
13952   }
13953 
13954   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13955   CurBlock->FunctionType = T;
13956 
13957   const FunctionType *Fn = T->getAs<FunctionType>();
13958   QualType RetTy = Fn->getReturnType();
13959   bool isVariadic =
13960     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13961 
13962   CurBlock->TheDecl->setIsVariadic(isVariadic);
13963 
13964   // Context.DependentTy is used as a placeholder for a missing block
13965   // return type.  TODO:  what should we do with declarators like:
13966   //   ^ * { ... }
13967   // If the answer is "apply template argument deduction"....
13968   if (RetTy != Context.DependentTy) {
13969     CurBlock->ReturnType = RetTy;
13970     CurBlock->TheDecl->setBlockMissingReturnType(false);
13971     CurBlock->HasImplicitReturnType = false;
13972   }
13973 
13974   // Push block parameters from the declarator if we had them.
13975   SmallVector<ParmVarDecl*, 8> Params;
13976   if (ExplicitSignature) {
13977     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13978       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13979       if (Param->getIdentifier() == nullptr &&
13980           !Param->isImplicit() &&
13981           !Param->isInvalidDecl() &&
13982           !getLangOpts().CPlusPlus)
13983         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13984       Params.push_back(Param);
13985     }
13986 
13987   // Fake up parameter variables if we have a typedef, like
13988   //   ^ fntype { ... }
13989   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13990     for (const auto &I : Fn->param_types()) {
13991       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13992           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13993       Params.push_back(Param);
13994     }
13995   }
13996 
13997   // Set the parameters on the block decl.
13998   if (!Params.empty()) {
13999     CurBlock->TheDecl->setParams(Params);
14000     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14001                              /*CheckParameterNames=*/false);
14002   }
14003 
14004   // Finally we can process decl attributes.
14005   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14006 
14007   // Put the parameter variables in scope.
14008   for (auto AI : CurBlock->TheDecl->parameters()) {
14009     AI->setOwningFunction(CurBlock->TheDecl);
14010 
14011     // If this has an identifier, add it to the scope stack.
14012     if (AI->getIdentifier()) {
14013       CheckShadow(CurBlock->TheScope, AI);
14014 
14015       PushOnScopeChains(AI, CurBlock->TheScope);
14016     }
14017   }
14018 }
14019 
14020 /// ActOnBlockError - If there is an error parsing a block, this callback
14021 /// is invoked to pop the information about the block from the action impl.
14022 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14023   // Leave the expression-evaluation context.
14024   DiscardCleanupsInEvaluationContext();
14025   PopExpressionEvaluationContext();
14026 
14027   // Pop off CurBlock, handle nested blocks.
14028   PopDeclContext();
14029   PopFunctionScopeInfo();
14030 }
14031 
14032 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14033 /// literal was successfully completed.  ^(int x){...}
14034 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14035                                     Stmt *Body, Scope *CurScope) {
14036   // If blocks are disabled, emit an error.
14037   if (!LangOpts.Blocks)
14038     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14039 
14040   // Leave the expression-evaluation context.
14041   if (hasAnyUnrecoverableErrorsInThisFunction())
14042     DiscardCleanupsInEvaluationContext();
14043   assert(!Cleanup.exprNeedsCleanups() &&
14044          "cleanups within block not correctly bound!");
14045   PopExpressionEvaluationContext();
14046 
14047   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14048   BlockDecl *BD = BSI->TheDecl;
14049 
14050   if (BSI->HasImplicitReturnType)
14051     deduceClosureReturnType(*BSI);
14052 
14053   QualType RetTy = Context.VoidTy;
14054   if (!BSI->ReturnType.isNull())
14055     RetTy = BSI->ReturnType;
14056 
14057   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14058   QualType BlockTy;
14059 
14060   // If the user wrote a function type in some form, try to use that.
14061   if (!BSI->FunctionType.isNull()) {
14062     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
14063 
14064     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14065     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14066 
14067     // Turn protoless block types into nullary block types.
14068     if (isa<FunctionNoProtoType>(FTy)) {
14069       FunctionProtoType::ExtProtoInfo EPI;
14070       EPI.ExtInfo = Ext;
14071       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14072 
14073     // Otherwise, if we don't need to change anything about the function type,
14074     // preserve its sugar structure.
14075     } else if (FTy->getReturnType() == RetTy &&
14076                (!NoReturn || FTy->getNoReturnAttr())) {
14077       BlockTy = BSI->FunctionType;
14078 
14079     // Otherwise, make the minimal modifications to the function type.
14080     } else {
14081       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14082       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14083       EPI.TypeQuals = Qualifiers();
14084       EPI.ExtInfo = Ext;
14085       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14086     }
14087 
14088   // If we don't have a function type, just build one from nothing.
14089   } else {
14090     FunctionProtoType::ExtProtoInfo EPI;
14091     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14092     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14093   }
14094 
14095   DiagnoseUnusedParameters(BD->parameters());
14096   BlockTy = Context.getBlockPointerType(BlockTy);
14097 
14098   // If needed, diagnose invalid gotos and switches in the block.
14099   if (getCurFunction()->NeedsScopeChecking() &&
14100       !PP.isCodeCompletionEnabled())
14101     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14102 
14103   BD->setBody(cast<CompoundStmt>(Body));
14104 
14105   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14106     DiagnoseUnguardedAvailabilityViolations(BD);
14107 
14108   // Try to apply the named return value optimization. We have to check again
14109   // if we can do this, though, because blocks keep return statements around
14110   // to deduce an implicit return type.
14111   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14112       !BD->isDependentContext())
14113     computeNRVO(Body, BSI);
14114 
14115   PopDeclContext();
14116 
14117   // Pop the block scope now but keep it alive to the end of this function.
14118   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14119   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14120 
14121   // Set the captured variables on the block.
14122   SmallVector<BlockDecl::Capture, 4> Captures;
14123   for (Capture &Cap : BSI->Captures) {
14124     if (Cap.isInvalid() || Cap.isThisCapture())
14125       continue;
14126 
14127     VarDecl *Var = Cap.getVariable();
14128     Expr *CopyExpr = nullptr;
14129     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14130       if (const RecordType *Record =
14131               Cap.getCaptureType()->getAs<RecordType>()) {
14132         // The capture logic needs the destructor, so make sure we mark it.
14133         // Usually this is unnecessary because most local variables have
14134         // their destructors marked at declaration time, but parameters are
14135         // an exception because it's technically only the call site that
14136         // actually requires the destructor.
14137         if (isa<ParmVarDecl>(Var))
14138           FinalizeVarWithDestructor(Var, Record);
14139 
14140         // Enter a separate potentially-evaluated context while building block
14141         // initializers to isolate their cleanups from those of the block
14142         // itself.
14143         // FIXME: Is this appropriate even when the block itself occurs in an
14144         // unevaluated operand?
14145         EnterExpressionEvaluationContext EvalContext(
14146             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14147 
14148         SourceLocation Loc = Cap.getLocation();
14149 
14150         ExprResult Result = BuildDeclarationNameExpr(
14151             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14152 
14153         // According to the blocks spec, the capture of a variable from
14154         // the stack requires a const copy constructor.  This is not true
14155         // of the copy/move done to move a __block variable to the heap.
14156         if (!Result.isInvalid() &&
14157             !Result.get()->getType().isConstQualified()) {
14158           Result = ImpCastExprToType(Result.get(),
14159                                      Result.get()->getType().withConst(),
14160                                      CK_NoOp, VK_LValue);
14161         }
14162 
14163         if (!Result.isInvalid()) {
14164           Result = PerformCopyInitialization(
14165               InitializedEntity::InitializeBlock(Var->getLocation(),
14166                                                  Cap.getCaptureType(), false),
14167               Loc, Result.get());
14168         }
14169 
14170         // Build a full-expression copy expression if initialization
14171         // succeeded and used a non-trivial constructor.  Recover from
14172         // errors by pretending that the copy isn't necessary.
14173         if (!Result.isInvalid() &&
14174             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14175                 ->isTrivial()) {
14176           Result = MaybeCreateExprWithCleanups(Result);
14177           CopyExpr = Result.get();
14178         }
14179       }
14180     }
14181 
14182     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14183                               CopyExpr);
14184     Captures.push_back(NewCap);
14185   }
14186   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14187 
14188   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14189 
14190   // If the block isn't obviously global, i.e. it captures anything at
14191   // all, then we need to do a few things in the surrounding context:
14192   if (Result->getBlockDecl()->hasCaptures()) {
14193     // First, this expression has a new cleanup object.
14194     ExprCleanupObjects.push_back(Result->getBlockDecl());
14195     Cleanup.setExprNeedsCleanups(true);
14196 
14197     // It also gets a branch-protected scope if any of the captured
14198     // variables needs destruction.
14199     for (const auto &CI : Result->getBlockDecl()->captures()) {
14200       const VarDecl *var = CI.getVariable();
14201       if (var->getType().isDestructedType() != QualType::DK_none) {
14202         setFunctionHasBranchProtectedScope();
14203         break;
14204       }
14205     }
14206   }
14207 
14208   if (getCurFunction())
14209     getCurFunction()->addBlock(BD);
14210 
14211   return Result;
14212 }
14213 
14214 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14215                             SourceLocation RPLoc) {
14216   TypeSourceInfo *TInfo;
14217   GetTypeFromParser(Ty, &TInfo);
14218   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14219 }
14220 
14221 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14222                                 Expr *E, TypeSourceInfo *TInfo,
14223                                 SourceLocation RPLoc) {
14224   Expr *OrigExpr = E;
14225   bool IsMS = false;
14226 
14227   // CUDA device code does not support varargs.
14228   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14229     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14230       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14231       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14232         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14233     }
14234   }
14235 
14236   // NVPTX does not support va_arg expression.
14237   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14238       Context.getTargetInfo().getTriple().isNVPTX())
14239     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14240 
14241   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14242   // as Microsoft ABI on an actual Microsoft platform, where
14243   // __builtin_ms_va_list and __builtin_va_list are the same.)
14244   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14245       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14246     QualType MSVaListType = Context.getBuiltinMSVaListType();
14247     if (Context.hasSameType(MSVaListType, E->getType())) {
14248       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14249         return ExprError();
14250       IsMS = true;
14251     }
14252   }
14253 
14254   // Get the va_list type
14255   QualType VaListType = Context.getBuiltinVaListType();
14256   if (!IsMS) {
14257     if (VaListType->isArrayType()) {
14258       // Deal with implicit array decay; for example, on x86-64,
14259       // va_list is an array, but it's supposed to decay to
14260       // a pointer for va_arg.
14261       VaListType = Context.getArrayDecayedType(VaListType);
14262       // Make sure the input expression also decays appropriately.
14263       ExprResult Result = UsualUnaryConversions(E);
14264       if (Result.isInvalid())
14265         return ExprError();
14266       E = Result.get();
14267     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14268       // If va_list is a record type and we are compiling in C++ mode,
14269       // check the argument using reference binding.
14270       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14271           Context, Context.getLValueReferenceType(VaListType), false);
14272       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14273       if (Init.isInvalid())
14274         return ExprError();
14275       E = Init.getAs<Expr>();
14276     } else {
14277       // Otherwise, the va_list argument must be an l-value because
14278       // it is modified by va_arg.
14279       if (!E->isTypeDependent() &&
14280           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14281         return ExprError();
14282     }
14283   }
14284 
14285   if (!IsMS && !E->isTypeDependent() &&
14286       !Context.hasSameType(VaListType, E->getType()))
14287     return ExprError(
14288         Diag(E->getBeginLoc(),
14289              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14290         << OrigExpr->getType() << E->getSourceRange());
14291 
14292   if (!TInfo->getType()->isDependentType()) {
14293     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14294                             diag::err_second_parameter_to_va_arg_incomplete,
14295                             TInfo->getTypeLoc()))
14296       return ExprError();
14297 
14298     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14299                                TInfo->getType(),
14300                                diag::err_second_parameter_to_va_arg_abstract,
14301                                TInfo->getTypeLoc()))
14302       return ExprError();
14303 
14304     if (!TInfo->getType().isPODType(Context)) {
14305       Diag(TInfo->getTypeLoc().getBeginLoc(),
14306            TInfo->getType()->isObjCLifetimeType()
14307              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14308              : diag::warn_second_parameter_to_va_arg_not_pod)
14309         << TInfo->getType()
14310         << TInfo->getTypeLoc().getSourceRange();
14311     }
14312 
14313     // Check for va_arg where arguments of the given type will be promoted
14314     // (i.e. this va_arg is guaranteed to have undefined behavior).
14315     QualType PromoteType;
14316     if (TInfo->getType()->isPromotableIntegerType()) {
14317       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14318       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14319         PromoteType = QualType();
14320     }
14321     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14322       PromoteType = Context.DoubleTy;
14323     if (!PromoteType.isNull())
14324       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14325                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14326                           << TInfo->getType()
14327                           << PromoteType
14328                           << TInfo->getTypeLoc().getSourceRange());
14329   }
14330 
14331   QualType T = TInfo->getType().getNonLValueExprType(Context);
14332   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14333 }
14334 
14335 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14336   // The type of __null will be int or long, depending on the size of
14337   // pointers on the target.
14338   QualType Ty;
14339   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14340   if (pw == Context.getTargetInfo().getIntWidth())
14341     Ty = Context.IntTy;
14342   else if (pw == Context.getTargetInfo().getLongWidth())
14343     Ty = Context.LongTy;
14344   else if (pw == Context.getTargetInfo().getLongLongWidth())
14345     Ty = Context.LongLongTy;
14346   else {
14347     llvm_unreachable("I don't know size of pointer!");
14348   }
14349 
14350   return new (Context) GNUNullExpr(Ty, TokenLoc);
14351 }
14352 
14353 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14354                                     SourceLocation BuiltinLoc,
14355                                     SourceLocation RPLoc) {
14356   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14357 }
14358 
14359 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14360                                     SourceLocation BuiltinLoc,
14361                                     SourceLocation RPLoc,
14362                                     DeclContext *ParentContext) {
14363   return new (Context)
14364       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14365 }
14366 
14367 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14368                                               bool Diagnose) {
14369   if (!getLangOpts().ObjC)
14370     return false;
14371 
14372   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14373   if (!PT)
14374     return false;
14375 
14376   if (!PT->isObjCIdType()) {
14377     // Check if the destination is the 'NSString' interface.
14378     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14379     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14380       return false;
14381   }
14382 
14383   // Ignore any parens, implicit casts (should only be
14384   // array-to-pointer decays), and not-so-opaque values.  The last is
14385   // important for making this trigger for property assignments.
14386   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14387   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14388     if (OV->getSourceExpr())
14389       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14390 
14391   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14392   if (!SL || !SL->isAscii())
14393     return false;
14394   if (Diagnose) {
14395     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14396         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14397     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14398   }
14399   return true;
14400 }
14401 
14402 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14403                                               const Expr *SrcExpr) {
14404   if (!DstType->isFunctionPointerType() ||
14405       !SrcExpr->getType()->isFunctionType())
14406     return false;
14407 
14408   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14409   if (!DRE)
14410     return false;
14411 
14412   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14413   if (!FD)
14414     return false;
14415 
14416   return !S.checkAddressOfFunctionIsAvailable(FD,
14417                                               /*Complain=*/true,
14418                                               SrcExpr->getBeginLoc());
14419 }
14420 
14421 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14422                                     SourceLocation Loc,
14423                                     QualType DstType, QualType SrcType,
14424                                     Expr *SrcExpr, AssignmentAction Action,
14425                                     bool *Complained) {
14426   if (Complained)
14427     *Complained = false;
14428 
14429   // Decode the result (notice that AST's are still created for extensions).
14430   bool CheckInferredResultType = false;
14431   bool isInvalid = false;
14432   unsigned DiagKind = 0;
14433   FixItHint Hint;
14434   ConversionFixItGenerator ConvHints;
14435   bool MayHaveConvFixit = false;
14436   bool MayHaveFunctionDiff = false;
14437   const ObjCInterfaceDecl *IFace = nullptr;
14438   const ObjCProtocolDecl *PDecl = nullptr;
14439 
14440   switch (ConvTy) {
14441   case Compatible:
14442       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14443       return false;
14444 
14445   case PointerToInt:
14446     DiagKind = diag::ext_typecheck_convert_pointer_int;
14447     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14448     MayHaveConvFixit = true;
14449     break;
14450   case IntToPointer:
14451     DiagKind = diag::ext_typecheck_convert_int_pointer;
14452     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14453     MayHaveConvFixit = true;
14454     break;
14455   case IncompatiblePointer:
14456     if (Action == AA_Passing_CFAudited)
14457       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14458     else if (SrcType->isFunctionPointerType() &&
14459              DstType->isFunctionPointerType())
14460       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14461     else
14462       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14463 
14464     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14465       SrcType->isObjCObjectPointerType();
14466     if (Hint.isNull() && !CheckInferredResultType) {
14467       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14468     }
14469     else if (CheckInferredResultType) {
14470       SrcType = SrcType.getUnqualifiedType();
14471       DstType = DstType.getUnqualifiedType();
14472     }
14473     MayHaveConvFixit = true;
14474     break;
14475   case IncompatiblePointerSign:
14476     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14477     break;
14478   case FunctionVoidPointer:
14479     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14480     break;
14481   case IncompatiblePointerDiscardsQualifiers: {
14482     // Perform array-to-pointer decay if necessary.
14483     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14484 
14485     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14486     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14487     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14488       DiagKind = diag::err_typecheck_incompatible_address_space;
14489       break;
14490 
14491     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14492       DiagKind = diag::err_typecheck_incompatible_ownership;
14493       break;
14494     }
14495 
14496     llvm_unreachable("unknown error case for discarding qualifiers!");
14497     // fallthrough
14498   }
14499   case CompatiblePointerDiscardsQualifiers:
14500     // If the qualifiers lost were because we were applying the
14501     // (deprecated) C++ conversion from a string literal to a char*
14502     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14503     // Ideally, this check would be performed in
14504     // checkPointerTypesForAssignment. However, that would require a
14505     // bit of refactoring (so that the second argument is an
14506     // expression, rather than a type), which should be done as part
14507     // of a larger effort to fix checkPointerTypesForAssignment for
14508     // C++ semantics.
14509     if (getLangOpts().CPlusPlus &&
14510         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14511       return false;
14512     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14513     break;
14514   case IncompatibleNestedPointerQualifiers:
14515     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14516     break;
14517   case IncompatibleNestedPointerAddressSpaceMismatch:
14518     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14519     break;
14520   case IntToBlockPointer:
14521     DiagKind = diag::err_int_to_block_pointer;
14522     break;
14523   case IncompatibleBlockPointer:
14524     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14525     break;
14526   case IncompatibleObjCQualifiedId: {
14527     if (SrcType->isObjCQualifiedIdType()) {
14528       const ObjCObjectPointerType *srcOPT =
14529                 SrcType->getAs<ObjCObjectPointerType>();
14530       for (auto *srcProto : srcOPT->quals()) {
14531         PDecl = srcProto;
14532         break;
14533       }
14534       if (const ObjCInterfaceType *IFaceT =
14535             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14536         IFace = IFaceT->getDecl();
14537     }
14538     else if (DstType->isObjCQualifiedIdType()) {
14539       const ObjCObjectPointerType *dstOPT =
14540         DstType->getAs<ObjCObjectPointerType>();
14541       for (auto *dstProto : dstOPT->quals()) {
14542         PDecl = dstProto;
14543         break;
14544       }
14545       if (const ObjCInterfaceType *IFaceT =
14546             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14547         IFace = IFaceT->getDecl();
14548     }
14549     DiagKind = diag::warn_incompatible_qualified_id;
14550     break;
14551   }
14552   case IncompatibleVectors:
14553     DiagKind = diag::warn_incompatible_vectors;
14554     break;
14555   case IncompatibleObjCWeakRef:
14556     DiagKind = diag::err_arc_weak_unavailable_assign;
14557     break;
14558   case Incompatible:
14559     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14560       if (Complained)
14561         *Complained = true;
14562       return true;
14563     }
14564 
14565     DiagKind = diag::err_typecheck_convert_incompatible;
14566     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14567     MayHaveConvFixit = true;
14568     isInvalid = true;
14569     MayHaveFunctionDiff = true;
14570     break;
14571   }
14572 
14573   QualType FirstType, SecondType;
14574   switch (Action) {
14575   case AA_Assigning:
14576   case AA_Initializing:
14577     // The destination type comes first.
14578     FirstType = DstType;
14579     SecondType = SrcType;
14580     break;
14581 
14582   case AA_Returning:
14583   case AA_Passing:
14584   case AA_Passing_CFAudited:
14585   case AA_Converting:
14586   case AA_Sending:
14587   case AA_Casting:
14588     // The source type comes first.
14589     FirstType = SrcType;
14590     SecondType = DstType;
14591     break;
14592   }
14593 
14594   PartialDiagnostic FDiag = PDiag(DiagKind);
14595   if (Action == AA_Passing_CFAudited)
14596     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14597   else
14598     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14599 
14600   // If we can fix the conversion, suggest the FixIts.
14601   assert(ConvHints.isNull() || Hint.isNull());
14602   if (!ConvHints.isNull()) {
14603     for (FixItHint &H : ConvHints.Hints)
14604       FDiag << H;
14605   } else {
14606     FDiag << Hint;
14607   }
14608   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14609 
14610   if (MayHaveFunctionDiff)
14611     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14612 
14613   Diag(Loc, FDiag);
14614   if (DiagKind == diag::warn_incompatible_qualified_id &&
14615       PDecl && IFace && !IFace->hasDefinition())
14616       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14617         << IFace << PDecl;
14618 
14619   if (SecondType == Context.OverloadTy)
14620     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14621                               FirstType, /*TakingAddress=*/true);
14622 
14623   if (CheckInferredResultType)
14624     EmitRelatedResultTypeNote(SrcExpr);
14625 
14626   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14627     EmitRelatedResultTypeNoteForReturn(DstType);
14628 
14629   if (Complained)
14630     *Complained = true;
14631   return isInvalid;
14632 }
14633 
14634 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14635                                                  llvm::APSInt *Result) {
14636   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14637   public:
14638     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14639       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14640     }
14641   } Diagnoser;
14642 
14643   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14644 }
14645 
14646 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14647                                                  llvm::APSInt *Result,
14648                                                  unsigned DiagID,
14649                                                  bool AllowFold) {
14650   class IDDiagnoser : public VerifyICEDiagnoser {
14651     unsigned DiagID;
14652 
14653   public:
14654     IDDiagnoser(unsigned DiagID)
14655       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14656 
14657     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14658       S.Diag(Loc, DiagID) << SR;
14659     }
14660   } Diagnoser(DiagID);
14661 
14662   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14663 }
14664 
14665 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14666                                             SourceRange SR) {
14667   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14668 }
14669 
14670 ExprResult
14671 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14672                                       VerifyICEDiagnoser &Diagnoser,
14673                                       bool AllowFold) {
14674   SourceLocation DiagLoc = E->getBeginLoc();
14675 
14676   if (getLangOpts().CPlusPlus11) {
14677     // C++11 [expr.const]p5:
14678     //   If an expression of literal class type is used in a context where an
14679     //   integral constant expression is required, then that class type shall
14680     //   have a single non-explicit conversion function to an integral or
14681     //   unscoped enumeration type
14682     ExprResult Converted;
14683     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14684     public:
14685       CXX11ConvertDiagnoser(bool Silent)
14686           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14687                                 Silent, true) {}
14688 
14689       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14690                                            QualType T) override {
14691         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14692       }
14693 
14694       SemaDiagnosticBuilder diagnoseIncomplete(
14695           Sema &S, SourceLocation Loc, QualType T) override {
14696         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14697       }
14698 
14699       SemaDiagnosticBuilder diagnoseExplicitConv(
14700           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14701         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14702       }
14703 
14704       SemaDiagnosticBuilder noteExplicitConv(
14705           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14706         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14707                  << ConvTy->isEnumeralType() << ConvTy;
14708       }
14709 
14710       SemaDiagnosticBuilder diagnoseAmbiguous(
14711           Sema &S, SourceLocation Loc, QualType T) override {
14712         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14713       }
14714 
14715       SemaDiagnosticBuilder noteAmbiguous(
14716           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14717         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14718                  << ConvTy->isEnumeralType() << ConvTy;
14719       }
14720 
14721       SemaDiagnosticBuilder diagnoseConversion(
14722           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14723         llvm_unreachable("conversion functions are permitted");
14724       }
14725     } ConvertDiagnoser(Diagnoser.Suppress);
14726 
14727     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14728                                                     ConvertDiagnoser);
14729     if (Converted.isInvalid())
14730       return Converted;
14731     E = Converted.get();
14732     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14733       return ExprError();
14734   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14735     // An ICE must be of integral or unscoped enumeration type.
14736     if (!Diagnoser.Suppress)
14737       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14738     return ExprError();
14739   }
14740 
14741   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14742   // in the non-ICE case.
14743   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14744     if (Result)
14745       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14746     if (!isa<ConstantExpr>(E))
14747       E = ConstantExpr::Create(Context, E);
14748     return E;
14749   }
14750 
14751   Expr::EvalResult EvalResult;
14752   SmallVector<PartialDiagnosticAt, 8> Notes;
14753   EvalResult.Diag = &Notes;
14754 
14755   // Try to evaluate the expression, and produce diagnostics explaining why it's
14756   // not a constant expression as a side-effect.
14757   bool Folded =
14758       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14759       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14760 
14761   if (!isa<ConstantExpr>(E))
14762     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14763 
14764   // In C++11, we can rely on diagnostics being produced for any expression
14765   // which is not a constant expression. If no diagnostics were produced, then
14766   // this is a constant expression.
14767   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14768     if (Result)
14769       *Result = EvalResult.Val.getInt();
14770     return E;
14771   }
14772 
14773   // If our only note is the usual "invalid subexpression" note, just point
14774   // the caret at its location rather than producing an essentially
14775   // redundant note.
14776   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14777         diag::note_invalid_subexpr_in_const_expr) {
14778     DiagLoc = Notes[0].first;
14779     Notes.clear();
14780   }
14781 
14782   if (!Folded || !AllowFold) {
14783     if (!Diagnoser.Suppress) {
14784       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14785       for (const PartialDiagnosticAt &Note : Notes)
14786         Diag(Note.first, Note.second);
14787     }
14788 
14789     return ExprError();
14790   }
14791 
14792   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14793   for (const PartialDiagnosticAt &Note : Notes)
14794     Diag(Note.first, Note.second);
14795 
14796   if (Result)
14797     *Result = EvalResult.Val.getInt();
14798   return E;
14799 }
14800 
14801 namespace {
14802   // Handle the case where we conclude a expression which we speculatively
14803   // considered to be unevaluated is actually evaluated.
14804   class TransformToPE : public TreeTransform<TransformToPE> {
14805     typedef TreeTransform<TransformToPE> BaseTransform;
14806 
14807   public:
14808     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14809 
14810     // Make sure we redo semantic analysis
14811     bool AlwaysRebuild() { return true; }
14812     bool ReplacingOriginal() { return true; }
14813 
14814     // We need to special-case DeclRefExprs referring to FieldDecls which
14815     // are not part of a member pointer formation; normal TreeTransforming
14816     // doesn't catch this case because of the way we represent them in the AST.
14817     // FIXME: This is a bit ugly; is it really the best way to handle this
14818     // case?
14819     //
14820     // Error on DeclRefExprs referring to FieldDecls.
14821     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14822       if (isa<FieldDecl>(E->getDecl()) &&
14823           !SemaRef.isUnevaluatedContext())
14824         return SemaRef.Diag(E->getLocation(),
14825                             diag::err_invalid_non_static_member_use)
14826             << E->getDecl() << E->getSourceRange();
14827 
14828       return BaseTransform::TransformDeclRefExpr(E);
14829     }
14830 
14831     // Exception: filter out member pointer formation
14832     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14833       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14834         return E;
14835 
14836       return BaseTransform::TransformUnaryOperator(E);
14837     }
14838 
14839     // The body of a lambda-expression is in a separate expression evaluation
14840     // context so never needs to be transformed.
14841     // FIXME: Ideally we wouldn't transform the closure type either, and would
14842     // just recreate the capture expressions and lambda expression.
14843     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
14844       return SkipLambdaBody(E, Body);
14845     }
14846   };
14847 }
14848 
14849 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14850   assert(isUnevaluatedContext() &&
14851          "Should only transform unevaluated expressions");
14852   ExprEvalContexts.back().Context =
14853       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14854   if (isUnevaluatedContext())
14855     return E;
14856   return TransformToPE(*this).TransformExpr(E);
14857 }
14858 
14859 void
14860 Sema::PushExpressionEvaluationContext(
14861     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14862     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14863   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14864                                 LambdaContextDecl, ExprContext);
14865   Cleanup.reset();
14866   if (!MaybeODRUseExprs.empty())
14867     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14868 }
14869 
14870 void
14871 Sema::PushExpressionEvaluationContext(
14872     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14873     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14874   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14875   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14876 }
14877 
14878 namespace {
14879 
14880 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14881   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14882   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14883     if (E->getOpcode() == UO_Deref)
14884       return CheckPossibleDeref(S, E->getSubExpr());
14885   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14886     return CheckPossibleDeref(S, E->getBase());
14887   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14888     return CheckPossibleDeref(S, E->getBase());
14889   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14890     QualType Inner;
14891     QualType Ty = E->getType();
14892     if (const auto *Ptr = Ty->getAs<PointerType>())
14893       Inner = Ptr->getPointeeType();
14894     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14895       Inner = Arr->getElementType();
14896     else
14897       return nullptr;
14898 
14899     if (Inner->hasAttr(attr::NoDeref))
14900       return E;
14901   }
14902   return nullptr;
14903 }
14904 
14905 } // namespace
14906 
14907 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14908   for (const Expr *E : Rec.PossibleDerefs) {
14909     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14910     if (DeclRef) {
14911       const ValueDecl *Decl = DeclRef->getDecl();
14912       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14913           << Decl->getName() << E->getSourceRange();
14914       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14915     } else {
14916       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14917           << E->getSourceRange();
14918     }
14919   }
14920   Rec.PossibleDerefs.clear();
14921 }
14922 
14923 void Sema::PopExpressionEvaluationContext() {
14924   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14925   unsigned NumTypos = Rec.NumTypos;
14926 
14927   if (!Rec.Lambdas.empty()) {
14928     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14929     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14930         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14931       unsigned D;
14932       if (Rec.isUnevaluated()) {
14933         // C++11 [expr.prim.lambda]p2:
14934         //   A lambda-expression shall not appear in an unevaluated operand
14935         //   (Clause 5).
14936         D = diag::err_lambda_unevaluated_operand;
14937       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14938         // C++1y [expr.const]p2:
14939         //   A conditional-expression e is a core constant expression unless the
14940         //   evaluation of e, following the rules of the abstract machine, would
14941         //   evaluate [...] a lambda-expression.
14942         D = diag::err_lambda_in_constant_expression;
14943       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14944         // C++17 [expr.prim.lamda]p2:
14945         // A lambda-expression shall not appear [...] in a template-argument.
14946         D = diag::err_lambda_in_invalid_context;
14947       } else
14948         llvm_unreachable("Couldn't infer lambda error message.");
14949 
14950       for (const auto *L : Rec.Lambdas)
14951         Diag(L->getBeginLoc(), D);
14952     }
14953   }
14954 
14955   WarnOnPendingNoDerefs(Rec);
14956 
14957   // When are coming out of an unevaluated context, clear out any
14958   // temporaries that we may have created as part of the evaluation of
14959   // the expression in that context: they aren't relevant because they
14960   // will never be constructed.
14961   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14962     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14963                              ExprCleanupObjects.end());
14964     Cleanup = Rec.ParentCleanup;
14965     CleanupVarDeclMarking();
14966     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14967   // Otherwise, merge the contexts together.
14968   } else {
14969     Cleanup.mergeFrom(Rec.ParentCleanup);
14970     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14971                             Rec.SavedMaybeODRUseExprs.end());
14972   }
14973 
14974   // Pop the current expression evaluation context off the stack.
14975   ExprEvalContexts.pop_back();
14976 
14977   // The global expression evaluation context record is never popped.
14978   ExprEvalContexts.back().NumTypos += NumTypos;
14979 }
14980 
14981 void Sema::DiscardCleanupsInEvaluationContext() {
14982   ExprCleanupObjects.erase(
14983          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14984          ExprCleanupObjects.end());
14985   Cleanup.reset();
14986   MaybeODRUseExprs.clear();
14987 }
14988 
14989 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14990   ExprResult Result = CheckPlaceholderExpr(E);
14991   if (Result.isInvalid())
14992     return ExprError();
14993   E = Result.get();
14994   if (!E->getType()->isVariablyModifiedType())
14995     return E;
14996   return TransformToPotentiallyEvaluated(E);
14997 }
14998 
14999 /// Are we in a context that is potentially constant evaluated per C++20
15000 /// [expr.const]p12?
15001 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15002   /// C++2a [expr.const]p12:
15003   //   An expression or conversion is potentially constant evaluated if it is
15004   switch (SemaRef.ExprEvalContexts.back().Context) {
15005     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15006       // -- a manifestly constant-evaluated expression,
15007     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15008     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15009     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15010       // -- a potentially-evaluated expression,
15011     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15012       // -- an immediate subexpression of a braced-init-list,
15013 
15014       // -- [FIXME] an expression of the form & cast-expression that occurs
15015       //    within a templated entity
15016       // -- a subexpression of one of the above that is not a subexpression of
15017       // a nested unevaluated operand.
15018       return true;
15019 
15020     case Sema::ExpressionEvaluationContext::Unevaluated:
15021     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15022       // Expressions in this context are never evaluated.
15023       return false;
15024   }
15025   llvm_unreachable("Invalid context");
15026 }
15027 
15028 /// Return true if this function has a calling convention that requires mangling
15029 /// in the size of the parameter pack.
15030 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15031   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15032   // we don't need parameter type sizes.
15033   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15034   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
15035                             TT.getArch() != llvm::Triple::x86_64))
15036     return false;
15037 
15038   // If this is C++ and this isn't an extern "C" function, parameters do not
15039   // need to be complete. In this case, C++ mangling will apply, which doesn't
15040   // use the size of the parameters.
15041   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15042     return false;
15043 
15044   // Stdcall, fastcall, and vectorcall need this special treatment.
15045   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15046   switch (CC) {
15047   case CC_X86StdCall:
15048   case CC_X86FastCall:
15049   case CC_X86VectorCall:
15050     return true;
15051   default:
15052     break;
15053   }
15054   return false;
15055 }
15056 
15057 /// Require that all of the parameter types of function be complete. Normally,
15058 /// parameter types are only required to be complete when a function is called
15059 /// or defined, but to mangle functions with certain calling conventions, the
15060 /// mangler needs to know the size of the parameter list. In this situation,
15061 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15062 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15063 /// result in a linker error. Clang doesn't implement this behavior, and instead
15064 /// attempts to error at compile time.
15065 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15066                                                   SourceLocation Loc) {
15067   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15068     FunctionDecl *FD;
15069     ParmVarDecl *Param;
15070 
15071   public:
15072     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15073         : FD(FD), Param(Param) {}
15074 
15075     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15076       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15077       StringRef CCName;
15078       switch (CC) {
15079       case CC_X86StdCall:
15080         CCName = "stdcall";
15081         break;
15082       case CC_X86FastCall:
15083         CCName = "fastcall";
15084         break;
15085       case CC_X86VectorCall:
15086         CCName = "vectorcall";
15087         break;
15088       default:
15089         llvm_unreachable("CC does not need mangling");
15090       }
15091 
15092       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15093           << Param->getDeclName() << FD->getDeclName() << CCName;
15094     }
15095   };
15096 
15097   for (ParmVarDecl *Param : FD->parameters()) {
15098     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15099     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15100   }
15101 }
15102 
15103 namespace {
15104 enum class OdrUseContext {
15105   /// Declarations in this context are not odr-used.
15106   None,
15107   /// Declarations in this context are formally odr-used, but this is a
15108   /// dependent context.
15109   Dependent,
15110   /// Declarations in this context are odr-used but not actually used (yet).
15111   FormallyOdrUsed,
15112   /// Declarations in this context are used.
15113   Used
15114 };
15115 }
15116 
15117 /// Are we within a context in which references to resolved functions or to
15118 /// variables result in odr-use?
15119 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15120   OdrUseContext Result;
15121 
15122   switch (SemaRef.ExprEvalContexts.back().Context) {
15123     case Sema::ExpressionEvaluationContext::Unevaluated:
15124     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15125     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15126       return OdrUseContext::None;
15127 
15128     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15129     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15130       Result = OdrUseContext::Used;
15131       break;
15132 
15133     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15134       Result = OdrUseContext::FormallyOdrUsed;
15135       break;
15136 
15137     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15138       // A default argument formally results in odr-use, but doesn't actually
15139       // result in a use in any real sense until it itself is used.
15140       Result = OdrUseContext::FormallyOdrUsed;
15141       break;
15142   }
15143 
15144   if (SemaRef.CurContext->isDependentContext())
15145     return OdrUseContext::Dependent;
15146 
15147   return Result;
15148 }
15149 
15150 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15151   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
15152   return Func->isConstexpr() &&
15153          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
15154 }
15155 
15156 /// Mark a function referenced, and check whether it is odr-used
15157 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15158 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15159                                   bool MightBeOdrUse) {
15160   assert(Func && "No function?");
15161 
15162   Func->setReferenced();
15163 
15164   // Recursive functions aren't really used until they're used from some other
15165   // context.
15166   bool IsRecursiveCall = CurContext == Func;
15167 
15168   // C++11 [basic.def.odr]p3:
15169   //   A function whose name appears as a potentially-evaluated expression is
15170   //   odr-used if it is the unique lookup result or the selected member of a
15171   //   set of overloaded functions [...].
15172   //
15173   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15174   // can just check that here.
15175   OdrUseContext OdrUse =
15176       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15177   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15178     OdrUse = OdrUseContext::FormallyOdrUsed;
15179 
15180   // Trivial default constructors and destructors are never actually used.
15181   // FIXME: What about other special members?
15182   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15183       OdrUse == OdrUseContext::Used) {
15184     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15185       if (Constructor->isDefaultConstructor())
15186         OdrUse = OdrUseContext::FormallyOdrUsed;
15187     if (isa<CXXDestructorDecl>(Func))
15188       OdrUse = OdrUseContext::FormallyOdrUsed;
15189   }
15190 
15191   // C++20 [expr.const]p12:
15192   //   A function [...] is needed for constant evaluation if it is [...] a
15193   //   constexpr function that is named by an expression that is potentially
15194   //   constant evaluated
15195   bool NeededForConstantEvaluation =
15196       isPotentiallyConstantEvaluatedContext(*this) &&
15197       isImplicitlyDefinableConstexprFunction(Func);
15198 
15199   // Determine whether we require a function definition to exist, per
15200   // C++11 [temp.inst]p3:
15201   //   Unless a function template specialization has been explicitly
15202   //   instantiated or explicitly specialized, the function template
15203   //   specialization is implicitly instantiated when the specialization is
15204   //   referenced in a context that requires a function definition to exist.
15205   // C++20 [temp.inst]p7:
15206   //   The existence of a definition of a [...] function is considered to
15207   //   affect the semantics of the program if the [...] function is needed for
15208   //   constant evaluation by an expression
15209   // C++20 [basic.def.odr]p10:
15210   //   Every program shall contain exactly one definition of every non-inline
15211   //   function or variable that is odr-used in that program outside of a
15212   //   discarded statement
15213   // C++20 [special]p1:
15214   //   The implementation will implicitly define [defaulted special members]
15215   //   if they are odr-used or needed for constant evaluation.
15216   //
15217   // Note that we skip the implicit instantiation of templates that are only
15218   // used in unused default arguments or by recursive calls to themselves.
15219   // This is formally non-conforming, but seems reasonable in practice.
15220   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15221                                              NeededForConstantEvaluation);
15222 
15223   // C++14 [temp.expl.spec]p6:
15224   //   If a template [...] is explicitly specialized then that specialization
15225   //   shall be declared before the first use of that specialization that would
15226   //   cause an implicit instantiation to take place, in every translation unit
15227   //   in which such a use occurs
15228   if (NeedDefinition &&
15229       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15230        Func->getMemberSpecializationInfo()))
15231     checkSpecializationVisibility(Loc, Func);
15232 
15233   // C++14 [except.spec]p17:
15234   //   An exception-specification is considered to be needed when:
15235   //   - the function is odr-used or, if it appears in an unevaluated operand,
15236   //     would be odr-used if the expression were potentially-evaluated;
15237   //
15238   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15239   // function is a pure virtual function we're calling, and in that case the
15240   // function was selected by overload resolution and we need to resolve its
15241   // exception specification for a different reason.
15242   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15243   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15244     ResolveExceptionSpec(Loc, FPT);
15245 
15246   if (getLangOpts().CUDA)
15247     CheckCUDACall(Loc, Func);
15248 
15249   // If we need a definition, try to create one.
15250   if (NeedDefinition && !Func->getBody()) {
15251     runWithSufficientStackSpace(Loc, [&] {
15252       if (CXXConstructorDecl *Constructor =
15253               dyn_cast<CXXConstructorDecl>(Func)) {
15254         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15255         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15256           if (Constructor->isDefaultConstructor()) {
15257             if (Constructor->isTrivial() &&
15258                 !Constructor->hasAttr<DLLExportAttr>())
15259               return;
15260             DefineImplicitDefaultConstructor(Loc, Constructor);
15261           } else if (Constructor->isCopyConstructor()) {
15262             DefineImplicitCopyConstructor(Loc, Constructor);
15263           } else if (Constructor->isMoveConstructor()) {
15264             DefineImplicitMoveConstructor(Loc, Constructor);
15265           }
15266         } else if (Constructor->getInheritedConstructor()) {
15267           DefineInheritingConstructor(Loc, Constructor);
15268         }
15269       } else if (CXXDestructorDecl *Destructor =
15270                      dyn_cast<CXXDestructorDecl>(Func)) {
15271         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15272         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15273           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15274             return;
15275           DefineImplicitDestructor(Loc, Destructor);
15276         }
15277         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15278           MarkVTableUsed(Loc, Destructor->getParent());
15279       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15280         if (MethodDecl->isOverloadedOperator() &&
15281             MethodDecl->getOverloadedOperator() == OO_Equal) {
15282           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15283           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15284             if (MethodDecl->isCopyAssignmentOperator())
15285               DefineImplicitCopyAssignment(Loc, MethodDecl);
15286             else if (MethodDecl->isMoveAssignmentOperator())
15287               DefineImplicitMoveAssignment(Loc, MethodDecl);
15288           }
15289         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15290                    MethodDecl->getParent()->isLambda()) {
15291           CXXConversionDecl *Conversion =
15292               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15293           if (Conversion->isLambdaToBlockPointerConversion())
15294             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15295           else
15296             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15297         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15298           MarkVTableUsed(Loc, MethodDecl->getParent());
15299       }
15300 
15301       // Implicit instantiation of function templates and member functions of
15302       // class templates.
15303       if (Func->isImplicitlyInstantiable()) {
15304         TemplateSpecializationKind TSK =
15305             Func->getTemplateSpecializationKindForInstantiation();
15306         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15307         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15308         if (FirstInstantiation) {
15309           PointOfInstantiation = Loc;
15310           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15311         } else if (TSK != TSK_ImplicitInstantiation) {
15312           // Use the point of use as the point of instantiation, instead of the
15313           // point of explicit instantiation (which we track as the actual point
15314           // of instantiation). This gives better backtraces in diagnostics.
15315           PointOfInstantiation = Loc;
15316         }
15317 
15318         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15319             Func->isConstexpr()) {
15320           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15321               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15322               CodeSynthesisContexts.size())
15323             PendingLocalImplicitInstantiations.push_back(
15324                 std::make_pair(Func, PointOfInstantiation));
15325           else if (Func->isConstexpr())
15326             // Do not defer instantiations of constexpr functions, to avoid the
15327             // expression evaluator needing to call back into Sema if it sees a
15328             // call to such a function.
15329             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15330           else {
15331             Func->setInstantiationIsPending(true);
15332             PendingInstantiations.push_back(
15333                 std::make_pair(Func, PointOfInstantiation));
15334             // Notify the consumer that a function was implicitly instantiated.
15335             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15336           }
15337         }
15338       } else {
15339         // Walk redefinitions, as some of them may be instantiable.
15340         for (auto i : Func->redecls()) {
15341           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15342             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15343         }
15344       }
15345     });
15346   }
15347 
15348   // If this is the first "real" use, act on that.
15349   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15350     // Keep track of used but undefined functions.
15351     if (!Func->isDefined()) {
15352       if (mightHaveNonExternalLinkage(Func))
15353         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15354       else if (Func->getMostRecentDecl()->isInlined() &&
15355                !LangOpts.GNUInline &&
15356                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15357         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15358       else if (isExternalWithNoLinkageType(Func))
15359         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15360     }
15361 
15362     // Some x86 Windows calling conventions mangle the size of the parameter
15363     // pack into the name. Computing the size of the parameters requires the
15364     // parameter types to be complete. Check that now.
15365     if (funcHasParameterSizeMangling(*this, Func))
15366       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15367 
15368     Func->markUsed(Context);
15369   }
15370 
15371   if (LangOpts.OpenMP) {
15372     if (LangOpts.OpenMPIsDevice)
15373       checkOpenMPDeviceFunction(Loc, Func);
15374     else
15375       checkOpenMPHostFunction(Loc, Func);
15376   }
15377 }
15378 
15379 /// Directly mark a variable odr-used. Given a choice, prefer to use
15380 /// MarkVariableReferenced since it does additional checks and then
15381 /// calls MarkVarDeclODRUsed.
15382 /// If the variable must be captured:
15383 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15384 ///  - else capture it in the DeclContext that maps to the
15385 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15386 static void
15387 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15388                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15389   // Keep track of used but undefined variables.
15390   // FIXME: We shouldn't suppress this warning for static data members.
15391   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15392       (!Var->isExternallyVisible() || Var->isInline() ||
15393        SemaRef.isExternalWithNoLinkageType(Var)) &&
15394       !(Var->isStaticDataMember() && Var->hasInit())) {
15395     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15396     if (old.isInvalid())
15397       old = Loc;
15398   }
15399   QualType CaptureType, DeclRefType;
15400   if (SemaRef.LangOpts.OpenMP)
15401     SemaRef.tryCaptureOpenMPLambdas(Var);
15402   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15403     /*EllipsisLoc*/ SourceLocation(),
15404     /*BuildAndDiagnose*/ true,
15405     CaptureType, DeclRefType,
15406     FunctionScopeIndexToStopAt);
15407 
15408   Var->markUsed(SemaRef.Context);
15409 }
15410 
15411 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15412                                              SourceLocation Loc,
15413                                              unsigned CapturingScopeIndex) {
15414   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15415 }
15416 
15417 static void
15418 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15419                                    ValueDecl *var, DeclContext *DC) {
15420   DeclContext *VarDC = var->getDeclContext();
15421 
15422   //  If the parameter still belongs to the translation unit, then
15423   //  we're actually just using one parameter in the declaration of
15424   //  the next.
15425   if (isa<ParmVarDecl>(var) &&
15426       isa<TranslationUnitDecl>(VarDC))
15427     return;
15428 
15429   // For C code, don't diagnose about capture if we're not actually in code
15430   // right now; it's impossible to write a non-constant expression outside of
15431   // function context, so we'll get other (more useful) diagnostics later.
15432   //
15433   // For C++, things get a bit more nasty... it would be nice to suppress this
15434   // diagnostic for certain cases like using a local variable in an array bound
15435   // for a member of a local class, but the correct predicate is not obvious.
15436   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15437     return;
15438 
15439   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15440   unsigned ContextKind = 3; // unknown
15441   if (isa<CXXMethodDecl>(VarDC) &&
15442       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15443     ContextKind = 2;
15444   } else if (isa<FunctionDecl>(VarDC)) {
15445     ContextKind = 0;
15446   } else if (isa<BlockDecl>(VarDC)) {
15447     ContextKind = 1;
15448   }
15449 
15450   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15451     << var << ValueKind << ContextKind << VarDC;
15452   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15453       << var;
15454 
15455   // FIXME: Add additional diagnostic info about class etc. which prevents
15456   // capture.
15457 }
15458 
15459 
15460 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15461                                       bool &SubCapturesAreNested,
15462                                       QualType &CaptureType,
15463                                       QualType &DeclRefType) {
15464    // Check whether we've already captured it.
15465   if (CSI->CaptureMap.count(Var)) {
15466     // If we found a capture, any subcaptures are nested.
15467     SubCapturesAreNested = true;
15468 
15469     // Retrieve the capture type for this variable.
15470     CaptureType = CSI->getCapture(Var).getCaptureType();
15471 
15472     // Compute the type of an expression that refers to this variable.
15473     DeclRefType = CaptureType.getNonReferenceType();
15474 
15475     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15476     // are mutable in the sense that user can change their value - they are
15477     // private instances of the captured declarations.
15478     const Capture &Cap = CSI->getCapture(Var);
15479     if (Cap.isCopyCapture() &&
15480         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15481         !(isa<CapturedRegionScopeInfo>(CSI) &&
15482           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15483       DeclRefType.addConst();
15484     return true;
15485   }
15486   return false;
15487 }
15488 
15489 // Only block literals, captured statements, and lambda expressions can
15490 // capture; other scopes don't work.
15491 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15492                                  SourceLocation Loc,
15493                                  const bool Diagnose, Sema &S) {
15494   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15495     return getLambdaAwareParentOfDeclContext(DC);
15496   else if (Var->hasLocalStorage()) {
15497     if (Diagnose)
15498        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15499   }
15500   return nullptr;
15501 }
15502 
15503 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15504 // certain types of variables (unnamed, variably modified types etc.)
15505 // so check for eligibility.
15506 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15507                                  SourceLocation Loc,
15508                                  const bool Diagnose, Sema &S) {
15509 
15510   bool IsBlock = isa<BlockScopeInfo>(CSI);
15511   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15512 
15513   // Lambdas are not allowed to capture unnamed variables
15514   // (e.g. anonymous unions).
15515   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15516   // assuming that's the intent.
15517   if (IsLambda && !Var->getDeclName()) {
15518     if (Diagnose) {
15519       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15520       S.Diag(Var->getLocation(), diag::note_declared_at);
15521     }
15522     return false;
15523   }
15524 
15525   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15526   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15527     if (Diagnose) {
15528       S.Diag(Loc, diag::err_ref_vm_type);
15529       S.Diag(Var->getLocation(), diag::note_previous_decl)
15530         << Var->getDeclName();
15531     }
15532     return false;
15533   }
15534   // Prohibit structs with flexible array members too.
15535   // We cannot capture what is in the tail end of the struct.
15536   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15537     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15538       if (Diagnose) {
15539         if (IsBlock)
15540           S.Diag(Loc, diag::err_ref_flexarray_type);
15541         else
15542           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15543             << Var->getDeclName();
15544         S.Diag(Var->getLocation(), diag::note_previous_decl)
15545           << Var->getDeclName();
15546       }
15547       return false;
15548     }
15549   }
15550   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15551   // Lambdas and captured statements are not allowed to capture __block
15552   // variables; they don't support the expected semantics.
15553   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15554     if (Diagnose) {
15555       S.Diag(Loc, diag::err_capture_block_variable)
15556         << Var->getDeclName() << !IsLambda;
15557       S.Diag(Var->getLocation(), diag::note_previous_decl)
15558         << Var->getDeclName();
15559     }
15560     return false;
15561   }
15562   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15563   if (S.getLangOpts().OpenCL && IsBlock &&
15564       Var->getType()->isBlockPointerType()) {
15565     if (Diagnose)
15566       S.Diag(Loc, diag::err_opencl_block_ref_block);
15567     return false;
15568   }
15569 
15570   return true;
15571 }
15572 
15573 // Returns true if the capture by block was successful.
15574 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15575                                  SourceLocation Loc,
15576                                  const bool BuildAndDiagnose,
15577                                  QualType &CaptureType,
15578                                  QualType &DeclRefType,
15579                                  const bool Nested,
15580                                  Sema &S, bool Invalid) {
15581   bool ByRef = false;
15582 
15583   // Blocks are not allowed to capture arrays, excepting OpenCL.
15584   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15585   // (decayed to pointers).
15586   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15587     if (BuildAndDiagnose) {
15588       S.Diag(Loc, diag::err_ref_array_type);
15589       S.Diag(Var->getLocation(), diag::note_previous_decl)
15590       << Var->getDeclName();
15591       Invalid = true;
15592     } else {
15593       return false;
15594     }
15595   }
15596 
15597   // Forbid the block-capture of autoreleasing variables.
15598   if (!Invalid &&
15599       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15600     if (BuildAndDiagnose) {
15601       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15602         << /*block*/ 0;
15603       S.Diag(Var->getLocation(), diag::note_previous_decl)
15604         << Var->getDeclName();
15605       Invalid = true;
15606     } else {
15607       return false;
15608     }
15609   }
15610 
15611   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15612   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15613     // This function finds out whether there is an AttributedType of kind
15614     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15615     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15616     // rather than being added implicitly by the compiler.
15617     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15618       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15619         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15620           return true;
15621 
15622         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15623         Ty = AttrTy->getModifiedType();
15624       }
15625 
15626       return false;
15627     };
15628 
15629     QualType PointeeTy = PT->getPointeeType();
15630 
15631     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15632         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15633         !IsObjCOwnershipAttributedType(PointeeTy)) {
15634       if (BuildAndDiagnose) {
15635         SourceLocation VarLoc = Var->getLocation();
15636         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15637         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15638       }
15639     }
15640   }
15641 
15642   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15643   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15644       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15645     // Block capture by reference does not change the capture or
15646     // declaration reference types.
15647     ByRef = true;
15648   } else {
15649     // Block capture by copy introduces 'const'.
15650     CaptureType = CaptureType.getNonReferenceType().withConst();
15651     DeclRefType = CaptureType;
15652   }
15653 
15654   // Actually capture the variable.
15655   if (BuildAndDiagnose)
15656     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15657                     CaptureType, Invalid);
15658 
15659   return !Invalid;
15660 }
15661 
15662 
15663 /// Capture the given variable in the captured region.
15664 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15665                                     VarDecl *Var,
15666                                     SourceLocation Loc,
15667                                     const bool BuildAndDiagnose,
15668                                     QualType &CaptureType,
15669                                     QualType &DeclRefType,
15670                                     const bool RefersToCapturedVariable,
15671                                     Sema &S, bool Invalid) {
15672   // By default, capture variables by reference.
15673   bool ByRef = true;
15674   // Using an LValue reference type is consistent with Lambdas (see below).
15675   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15676     if (S.isOpenMPCapturedDecl(Var)) {
15677       bool HasConst = DeclRefType.isConstQualified();
15678       DeclRefType = DeclRefType.getUnqualifiedType();
15679       // Don't lose diagnostics about assignments to const.
15680       if (HasConst)
15681         DeclRefType.addConst();
15682     }
15683     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
15684                                     RSI->OpenMPCaptureLevel);
15685   }
15686 
15687   if (ByRef)
15688     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15689   else
15690     CaptureType = DeclRefType;
15691 
15692   // Actually capture the variable.
15693   if (BuildAndDiagnose)
15694     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15695                     Loc, SourceLocation(), CaptureType, Invalid);
15696 
15697   return !Invalid;
15698 }
15699 
15700 /// Capture the given variable in the lambda.
15701 static bool captureInLambda(LambdaScopeInfo *LSI,
15702                             VarDecl *Var,
15703                             SourceLocation Loc,
15704                             const bool BuildAndDiagnose,
15705                             QualType &CaptureType,
15706                             QualType &DeclRefType,
15707                             const bool RefersToCapturedVariable,
15708                             const Sema::TryCaptureKind Kind,
15709                             SourceLocation EllipsisLoc,
15710                             const bool IsTopScope,
15711                             Sema &S, bool Invalid) {
15712   // Determine whether we are capturing by reference or by value.
15713   bool ByRef = false;
15714   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15715     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15716   } else {
15717     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15718   }
15719 
15720   // Compute the type of the field that will capture this variable.
15721   if (ByRef) {
15722     // C++11 [expr.prim.lambda]p15:
15723     //   An entity is captured by reference if it is implicitly or
15724     //   explicitly captured but not captured by copy. It is
15725     //   unspecified whether additional unnamed non-static data
15726     //   members are declared in the closure type for entities
15727     //   captured by reference.
15728     //
15729     // FIXME: It is not clear whether we want to build an lvalue reference
15730     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15731     // to do the former, while EDG does the latter. Core issue 1249 will
15732     // clarify, but for now we follow GCC because it's a more permissive and
15733     // easily defensible position.
15734     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15735   } else {
15736     // C++11 [expr.prim.lambda]p14:
15737     //   For each entity captured by copy, an unnamed non-static
15738     //   data member is declared in the closure type. The
15739     //   declaration order of these members is unspecified. The type
15740     //   of such a data member is the type of the corresponding
15741     //   captured entity if the entity is not a reference to an
15742     //   object, or the referenced type otherwise. [Note: If the
15743     //   captured entity is a reference to a function, the
15744     //   corresponding data member is also a reference to a
15745     //   function. - end note ]
15746     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15747       if (!RefType->getPointeeType()->isFunctionType())
15748         CaptureType = RefType->getPointeeType();
15749     }
15750 
15751     // Forbid the lambda copy-capture of autoreleasing variables.
15752     if (!Invalid &&
15753         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15754       if (BuildAndDiagnose) {
15755         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15756         S.Diag(Var->getLocation(), diag::note_previous_decl)
15757           << Var->getDeclName();
15758         Invalid = true;
15759       } else {
15760         return false;
15761       }
15762     }
15763 
15764     // Make sure that by-copy captures are of a complete and non-abstract type.
15765     if (!Invalid && BuildAndDiagnose) {
15766       if (!CaptureType->isDependentType() &&
15767           S.RequireCompleteType(Loc, CaptureType,
15768                                 diag::err_capture_of_incomplete_type,
15769                                 Var->getDeclName()))
15770         Invalid = true;
15771       else if (S.RequireNonAbstractType(Loc, CaptureType,
15772                                         diag::err_capture_of_abstract_type))
15773         Invalid = true;
15774     }
15775   }
15776 
15777   // Compute the type of a reference to this captured variable.
15778   if (ByRef)
15779     DeclRefType = CaptureType.getNonReferenceType();
15780   else {
15781     // C++ [expr.prim.lambda]p5:
15782     //   The closure type for a lambda-expression has a public inline
15783     //   function call operator [...]. This function call operator is
15784     //   declared const (9.3.1) if and only if the lambda-expression's
15785     //   parameter-declaration-clause is not followed by mutable.
15786     DeclRefType = CaptureType.getNonReferenceType();
15787     if (!LSI->Mutable && !CaptureType->isReferenceType())
15788       DeclRefType.addConst();
15789   }
15790 
15791   // Add the capture.
15792   if (BuildAndDiagnose)
15793     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
15794                     Loc, EllipsisLoc, CaptureType, Invalid);
15795 
15796   return !Invalid;
15797 }
15798 
15799 bool Sema::tryCaptureVariable(
15800     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15801     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15802     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15803   // An init-capture is notionally from the context surrounding its
15804   // declaration, but its parent DC is the lambda class.
15805   DeclContext *VarDC = Var->getDeclContext();
15806   if (Var->isInitCapture())
15807     VarDC = VarDC->getParent();
15808 
15809   DeclContext *DC = CurContext;
15810   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15811       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15812   // We need to sync up the Declaration Context with the
15813   // FunctionScopeIndexToStopAt
15814   if (FunctionScopeIndexToStopAt) {
15815     unsigned FSIndex = FunctionScopes.size() - 1;
15816     while (FSIndex != MaxFunctionScopesIndex) {
15817       DC = getLambdaAwareParentOfDeclContext(DC);
15818       --FSIndex;
15819     }
15820   }
15821 
15822 
15823   // If the variable is declared in the current context, there is no need to
15824   // capture it.
15825   if (VarDC == DC) return true;
15826 
15827   // Capture global variables if it is required to use private copy of this
15828   // variable.
15829   bool IsGlobal = !Var->hasLocalStorage();
15830   if (IsGlobal &&
15831       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
15832                                                 MaxFunctionScopesIndex)))
15833     return true;
15834   Var = Var->getCanonicalDecl();
15835 
15836   // Walk up the stack to determine whether we can capture the variable,
15837   // performing the "simple" checks that don't depend on type. We stop when
15838   // we've either hit the declared scope of the variable or find an existing
15839   // capture of that variable.  We start from the innermost capturing-entity
15840   // (the DC) and ensure that all intervening capturing-entities
15841   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15842   // declcontext can either capture the variable or have already captured
15843   // the variable.
15844   CaptureType = Var->getType();
15845   DeclRefType = CaptureType.getNonReferenceType();
15846   bool Nested = false;
15847   bool Explicit = (Kind != TryCapture_Implicit);
15848   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15849   do {
15850     // Only block literals, captured statements, and lambda expressions can
15851     // capture; other scopes don't work.
15852     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15853                                                               ExprLoc,
15854                                                               BuildAndDiagnose,
15855                                                               *this);
15856     // We need to check for the parent *first* because, if we *have*
15857     // private-captured a global variable, we need to recursively capture it in
15858     // intermediate blocks, lambdas, etc.
15859     if (!ParentDC) {
15860       if (IsGlobal) {
15861         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15862         break;
15863       }
15864       return true;
15865     }
15866 
15867     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15868     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15869 
15870 
15871     // Check whether we've already captured it.
15872     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15873                                              DeclRefType)) {
15874       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15875       break;
15876     }
15877     // If we are instantiating a generic lambda call operator body,
15878     // we do not want to capture new variables.  What was captured
15879     // during either a lambdas transformation or initial parsing
15880     // should be used.
15881     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15882       if (BuildAndDiagnose) {
15883         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15884         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15885           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15886           Diag(Var->getLocation(), diag::note_previous_decl)
15887              << Var->getDeclName();
15888           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15889         } else
15890           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15891       }
15892       return true;
15893     }
15894 
15895     // Try to capture variable-length arrays types.
15896     if (Var->getType()->isVariablyModifiedType()) {
15897       // We're going to walk down into the type and look for VLA
15898       // expressions.
15899       QualType QTy = Var->getType();
15900       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15901         QTy = PVD->getOriginalType();
15902       captureVariablyModifiedType(Context, QTy, CSI);
15903     }
15904 
15905     if (getLangOpts().OpenMP) {
15906       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15907         // OpenMP private variables should not be captured in outer scope, so
15908         // just break here. Similarly, global variables that are captured in a
15909         // target region should not be captured outside the scope of the region.
15910         if (RSI->CapRegionKind == CR_OpenMP) {
15911           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15912           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15913                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15914           // When we detect target captures we are looking from inside the
15915           // target region, therefore we need to propagate the capture from the
15916           // enclosing region. Therefore, the capture is not initially nested.
15917           if (IsTargetCap)
15918             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15919 
15920           if (IsTargetCap || IsOpenMPPrivateDecl) {
15921             Nested = !IsTargetCap;
15922             DeclRefType = DeclRefType.getUnqualifiedType();
15923             CaptureType = Context.getLValueReferenceType(DeclRefType);
15924             break;
15925           }
15926         }
15927       }
15928     }
15929     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15930       // No capture-default, and this is not an explicit capture
15931       // so cannot capture this variable.
15932       if (BuildAndDiagnose) {
15933         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15934         Diag(Var->getLocation(), diag::note_previous_decl)
15935           << Var->getDeclName();
15936         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15937           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15938                diag::note_lambda_decl);
15939         // FIXME: If we error out because an outer lambda can not implicitly
15940         // capture a variable that an inner lambda explicitly captures, we
15941         // should have the inner lambda do the explicit capture - because
15942         // it makes for cleaner diagnostics later.  This would purely be done
15943         // so that the diagnostic does not misleadingly claim that a variable
15944         // can not be captured by a lambda implicitly even though it is captured
15945         // explicitly.  Suggestion:
15946         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15947         //    at the function head
15948         //  - cache the StartingDeclContext - this must be a lambda
15949         //  - captureInLambda in the innermost lambda the variable.
15950       }
15951       return true;
15952     }
15953 
15954     FunctionScopesIndex--;
15955     DC = ParentDC;
15956     Explicit = false;
15957   } while (!VarDC->Equals(DC));
15958 
15959   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15960   // computing the type of the capture at each step, checking type-specific
15961   // requirements, and adding captures if requested.
15962   // If the variable had already been captured previously, we start capturing
15963   // at the lambda nested within that one.
15964   bool Invalid = false;
15965   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15966        ++I) {
15967     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15968 
15969     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15970     // certain types of variables (unnamed, variably modified types etc.)
15971     // so check for eligibility.
15972     if (!Invalid)
15973       Invalid =
15974           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
15975 
15976     // After encountering an error, if we're actually supposed to capture, keep
15977     // capturing in nested contexts to suppress any follow-on diagnostics.
15978     if (Invalid && !BuildAndDiagnose)
15979       return true;
15980 
15981     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15982       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
15983                                DeclRefType, Nested, *this, Invalid);
15984       Nested = true;
15985     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15986       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
15987                                          CaptureType, DeclRefType, Nested,
15988                                          *this, Invalid);
15989       Nested = true;
15990     } else {
15991       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15992       Invalid =
15993           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
15994                            DeclRefType, Nested, Kind, EllipsisLoc,
15995                            /*IsTopScope*/ I == N - 1, *this, Invalid);
15996       Nested = true;
15997     }
15998 
15999     if (Invalid && !BuildAndDiagnose)
16000       return true;
16001   }
16002   return Invalid;
16003 }
16004 
16005 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16006                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16007   QualType CaptureType;
16008   QualType DeclRefType;
16009   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16010                             /*BuildAndDiagnose=*/true, CaptureType,
16011                             DeclRefType, nullptr);
16012 }
16013 
16014 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16015   QualType CaptureType;
16016   QualType DeclRefType;
16017   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16018                              /*BuildAndDiagnose=*/false, CaptureType,
16019                              DeclRefType, nullptr);
16020 }
16021 
16022 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16023   QualType CaptureType;
16024   QualType DeclRefType;
16025 
16026   // Determine whether we can capture this variable.
16027   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16028                          /*BuildAndDiagnose=*/false, CaptureType,
16029                          DeclRefType, nullptr))
16030     return QualType();
16031 
16032   return DeclRefType;
16033 }
16034 
16035 namespace {
16036 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16037 // The produced TemplateArgumentListInfo* points to data stored within this
16038 // object, so should only be used in contexts where the pointer will not be
16039 // used after the CopiedTemplateArgs object is destroyed.
16040 class CopiedTemplateArgs {
16041   bool HasArgs;
16042   TemplateArgumentListInfo TemplateArgStorage;
16043 public:
16044   template<typename RefExpr>
16045   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16046     if (HasArgs)
16047       E->copyTemplateArgumentsInto(TemplateArgStorage);
16048   }
16049   operator TemplateArgumentListInfo*()
16050 #ifdef __has_cpp_attribute
16051 #if __has_cpp_attribute(clang::lifetimebound)
16052   [[clang::lifetimebound]]
16053 #endif
16054 #endif
16055   {
16056     return HasArgs ? &TemplateArgStorage : nullptr;
16057   }
16058 };
16059 }
16060 
16061 /// Walk the set of potential results of an expression and mark them all as
16062 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16063 ///
16064 /// \return A new expression if we found any potential results, ExprEmpty() if
16065 ///         not, and ExprError() if we diagnosed an error.
16066 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16067                                                       NonOdrUseReason NOUR) {
16068   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16069   // an object that satisfies the requirements for appearing in a
16070   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16071   // is immediately applied."  This function handles the lvalue-to-rvalue
16072   // conversion part.
16073   //
16074   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16075   // transform it into the relevant kind of non-odr-use node and rebuild the
16076   // tree of nodes leading to it.
16077   //
16078   // This is a mini-TreeTransform that only transforms a restricted subset of
16079   // nodes (and only certain operands of them).
16080 
16081   // Rebuild a subexpression.
16082   auto Rebuild = [&](Expr *Sub) {
16083     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16084   };
16085 
16086   // Check whether a potential result satisfies the requirements of NOUR.
16087   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16088     // Any entity other than a VarDecl is always odr-used whenever it's named
16089     // in a potentially-evaluated expression.
16090     auto *VD = dyn_cast<VarDecl>(D);
16091     if (!VD)
16092       return true;
16093 
16094     // C++2a [basic.def.odr]p4:
16095     //   A variable x whose name appears as a potentially-evalauted expression
16096     //   e is odr-used by e unless
16097     //   -- x is a reference that is usable in constant expressions, or
16098     //   -- x is a variable of non-reference type that is usable in constant
16099     //      expressions and has no mutable subobjects, and e is an element of
16100     //      the set of potential results of an expression of
16101     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16102     //      conversion is applied, or
16103     //   -- x is a variable of non-reference type, and e is an element of the
16104     //      set of potential results of a discarded-value expression to which
16105     //      the lvalue-to-rvalue conversion is not applied
16106     //
16107     // We check the first bullet and the "potentially-evaluated" condition in
16108     // BuildDeclRefExpr. We check the type requirements in the second bullet
16109     // in CheckLValueToRValueConversionOperand below.
16110     switch (NOUR) {
16111     case NOUR_None:
16112     case NOUR_Unevaluated:
16113       llvm_unreachable("unexpected non-odr-use-reason");
16114 
16115     case NOUR_Constant:
16116       // Constant references were handled when they were built.
16117       if (VD->getType()->isReferenceType())
16118         return true;
16119       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16120         if (RD->hasMutableFields())
16121           return true;
16122       if (!VD->isUsableInConstantExpressions(S.Context))
16123         return true;
16124       break;
16125 
16126     case NOUR_Discarded:
16127       if (VD->getType()->isReferenceType())
16128         return true;
16129       break;
16130     }
16131     return false;
16132   };
16133 
16134   // Mark that this expression does not constitute an odr-use.
16135   auto MarkNotOdrUsed = [&] {
16136     S.MaybeODRUseExprs.erase(E);
16137     if (LambdaScopeInfo *LSI = S.getCurLambda())
16138       LSI->markVariableExprAsNonODRUsed(E);
16139   };
16140 
16141   // C++2a [basic.def.odr]p2:
16142   //   The set of potential results of an expression e is defined as follows:
16143   switch (E->getStmtClass()) {
16144   //   -- If e is an id-expression, ...
16145   case Expr::DeclRefExprClass: {
16146     auto *DRE = cast<DeclRefExpr>(E);
16147     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16148       break;
16149 
16150     // Rebuild as a non-odr-use DeclRefExpr.
16151     MarkNotOdrUsed();
16152     return DeclRefExpr::Create(
16153         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16154         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16155         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16156         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16157   }
16158 
16159   case Expr::FunctionParmPackExprClass: {
16160     auto *FPPE = cast<FunctionParmPackExpr>(E);
16161     // If any of the declarations in the pack is odr-used, then the expression
16162     // as a whole constitutes an odr-use.
16163     for (VarDecl *D : *FPPE)
16164       if (IsPotentialResultOdrUsed(D))
16165         return ExprEmpty();
16166 
16167     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16168     // nothing cares about whether we marked this as an odr-use, but it might
16169     // be useful for non-compiler tools.
16170     MarkNotOdrUsed();
16171     break;
16172   }
16173 
16174   //   -- If e is a subscripting operation with an array operand...
16175   case Expr::ArraySubscriptExprClass: {
16176     auto *ASE = cast<ArraySubscriptExpr>(E);
16177     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16178     if (!OldBase->getType()->isArrayType())
16179       break;
16180     ExprResult Base = Rebuild(OldBase);
16181     if (!Base.isUsable())
16182       return Base;
16183     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16184     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16185     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16186     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16187                                      ASE->getRBracketLoc());
16188   }
16189 
16190   case Expr::MemberExprClass: {
16191     auto *ME = cast<MemberExpr>(E);
16192     // -- If e is a class member access expression [...] naming a non-static
16193     //    data member...
16194     if (isa<FieldDecl>(ME->getMemberDecl())) {
16195       ExprResult Base = Rebuild(ME->getBase());
16196       if (!Base.isUsable())
16197         return Base;
16198       return MemberExpr::Create(
16199           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16200           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16201           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16202           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16203           ME->getObjectKind(), ME->isNonOdrUse());
16204     }
16205 
16206     if (ME->getMemberDecl()->isCXXInstanceMember())
16207       break;
16208 
16209     // -- If e is a class member access expression naming a static data member,
16210     //    ...
16211     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16212       break;
16213 
16214     // Rebuild as a non-odr-use MemberExpr.
16215     MarkNotOdrUsed();
16216     return MemberExpr::Create(
16217         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16218         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16219         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16220         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16221     return ExprEmpty();
16222   }
16223 
16224   case Expr::BinaryOperatorClass: {
16225     auto *BO = cast<BinaryOperator>(E);
16226     Expr *LHS = BO->getLHS();
16227     Expr *RHS = BO->getRHS();
16228     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16229     if (BO->getOpcode() == BO_PtrMemD) {
16230       ExprResult Sub = Rebuild(LHS);
16231       if (!Sub.isUsable())
16232         return Sub;
16233       LHS = Sub.get();
16234     //   -- If e is a comma expression, ...
16235     } else if (BO->getOpcode() == BO_Comma) {
16236       ExprResult Sub = Rebuild(RHS);
16237       if (!Sub.isUsable())
16238         return Sub;
16239       RHS = Sub.get();
16240     } else {
16241       break;
16242     }
16243     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16244                         LHS, RHS);
16245   }
16246 
16247   //   -- If e has the form (e1)...
16248   case Expr::ParenExprClass: {
16249     auto *PE = cast<ParenExpr>(E);
16250     ExprResult Sub = Rebuild(PE->getSubExpr());
16251     if (!Sub.isUsable())
16252       return Sub;
16253     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16254   }
16255 
16256   //   -- If e is a glvalue conditional expression, ...
16257   // We don't apply this to a binary conditional operator. FIXME: Should we?
16258   case Expr::ConditionalOperatorClass: {
16259     auto *CO = cast<ConditionalOperator>(E);
16260     ExprResult LHS = Rebuild(CO->getLHS());
16261     if (LHS.isInvalid())
16262       return ExprError();
16263     ExprResult RHS = Rebuild(CO->getRHS());
16264     if (RHS.isInvalid())
16265       return ExprError();
16266     if (!LHS.isUsable() && !RHS.isUsable())
16267       return ExprEmpty();
16268     if (!LHS.isUsable())
16269       LHS = CO->getLHS();
16270     if (!RHS.isUsable())
16271       RHS = CO->getRHS();
16272     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16273                                 CO->getCond(), LHS.get(), RHS.get());
16274   }
16275 
16276   // [Clang extension]
16277   //   -- If e has the form __extension__ e1...
16278   case Expr::UnaryOperatorClass: {
16279     auto *UO = cast<UnaryOperator>(E);
16280     if (UO->getOpcode() != UO_Extension)
16281       break;
16282     ExprResult Sub = Rebuild(UO->getSubExpr());
16283     if (!Sub.isUsable())
16284       return Sub;
16285     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16286                           Sub.get());
16287   }
16288 
16289   // [Clang extension]
16290   //   -- If e has the form _Generic(...), the set of potential results is the
16291   //      union of the sets of potential results of the associated expressions.
16292   case Expr::GenericSelectionExprClass: {
16293     auto *GSE = cast<GenericSelectionExpr>(E);
16294 
16295     SmallVector<Expr *, 4> AssocExprs;
16296     bool AnyChanged = false;
16297     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16298       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16299       if (AssocExpr.isInvalid())
16300         return ExprError();
16301       if (AssocExpr.isUsable()) {
16302         AssocExprs.push_back(AssocExpr.get());
16303         AnyChanged = true;
16304       } else {
16305         AssocExprs.push_back(OrigAssocExpr);
16306       }
16307     }
16308 
16309     return AnyChanged ? S.CreateGenericSelectionExpr(
16310                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16311                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16312                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16313                       : ExprEmpty();
16314   }
16315 
16316   // [Clang extension]
16317   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16318   //      results is the union of the sets of potential results of the
16319   //      second and third subexpressions.
16320   case Expr::ChooseExprClass: {
16321     auto *CE = cast<ChooseExpr>(E);
16322 
16323     ExprResult LHS = Rebuild(CE->getLHS());
16324     if (LHS.isInvalid())
16325       return ExprError();
16326 
16327     ExprResult RHS = Rebuild(CE->getLHS());
16328     if (RHS.isInvalid())
16329       return ExprError();
16330 
16331     if (!LHS.get() && !RHS.get())
16332       return ExprEmpty();
16333     if (!LHS.isUsable())
16334       LHS = CE->getLHS();
16335     if (!RHS.isUsable())
16336       RHS = CE->getRHS();
16337 
16338     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16339                              RHS.get(), CE->getRParenLoc());
16340   }
16341 
16342   // Step through non-syntactic nodes.
16343   case Expr::ConstantExprClass: {
16344     auto *CE = cast<ConstantExpr>(E);
16345     ExprResult Sub = Rebuild(CE->getSubExpr());
16346     if (!Sub.isUsable())
16347       return Sub;
16348     return ConstantExpr::Create(S.Context, Sub.get());
16349   }
16350 
16351   // We could mostly rely on the recursive rebuilding to rebuild implicit
16352   // casts, but not at the top level, so rebuild them here.
16353   case Expr::ImplicitCastExprClass: {
16354     auto *ICE = cast<ImplicitCastExpr>(E);
16355     // Only step through the narrow set of cast kinds we expect to encounter.
16356     // Anything else suggests we've left the region in which potential results
16357     // can be found.
16358     switch (ICE->getCastKind()) {
16359     case CK_NoOp:
16360     case CK_DerivedToBase:
16361     case CK_UncheckedDerivedToBase: {
16362       ExprResult Sub = Rebuild(ICE->getSubExpr());
16363       if (!Sub.isUsable())
16364         return Sub;
16365       CXXCastPath Path(ICE->path());
16366       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16367                                  ICE->getValueKind(), &Path);
16368     }
16369 
16370     default:
16371       break;
16372     }
16373     break;
16374   }
16375 
16376   default:
16377     break;
16378   }
16379 
16380   // Can't traverse through this node. Nothing to do.
16381   return ExprEmpty();
16382 }
16383 
16384 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16385   // C++2a [basic.def.odr]p4:
16386   //   [...] an expression of non-volatile-qualified non-class type to which
16387   //   the lvalue-to-rvalue conversion is applied [...]
16388   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16389     return E;
16390 
16391   ExprResult Result =
16392       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16393   if (Result.isInvalid())
16394     return ExprError();
16395   return Result.get() ? Result : E;
16396 }
16397 
16398 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16399   Res = CorrectDelayedTyposInExpr(Res);
16400 
16401   if (!Res.isUsable())
16402     return Res;
16403 
16404   // If a constant-expression is a reference to a variable where we delay
16405   // deciding whether it is an odr-use, just assume we will apply the
16406   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16407   // (a non-type template argument), we have special handling anyway.
16408   return CheckLValueToRValueConversionOperand(Res.get());
16409 }
16410 
16411 void Sema::CleanupVarDeclMarking() {
16412   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16413   // call.
16414   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16415   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16416 
16417   for (Expr *E : LocalMaybeODRUseExprs) {
16418     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16419       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16420                          DRE->getLocation(), *this);
16421     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16422       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16423                          *this);
16424     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16425       for (VarDecl *VD : *FP)
16426         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16427     } else {
16428       llvm_unreachable("Unexpected expression");
16429     }
16430   }
16431 
16432   assert(MaybeODRUseExprs.empty() &&
16433          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16434 }
16435 
16436 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16437                                     VarDecl *Var, Expr *E) {
16438   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16439           isa<FunctionParmPackExpr>(E)) &&
16440          "Invalid Expr argument to DoMarkVarDeclReferenced");
16441   Var->setReferenced();
16442 
16443   if (Var->isInvalidDecl())
16444     return;
16445 
16446   auto *MSI = Var->getMemberSpecializationInfo();
16447   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16448                                        : Var->getTemplateSpecializationKind();
16449 
16450   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16451   bool UsableInConstantExpr =
16452       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16453 
16454   // C++20 [expr.const]p12:
16455   //   A variable [...] is needed for constant evaluation if it is [...] a
16456   //   variable whose name appears as a potentially constant evaluated
16457   //   expression that is either a contexpr variable or is of non-volatile
16458   //   const-qualified integral type or of reference type
16459   bool NeededForConstantEvaluation =
16460       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16461 
16462   bool NeedDefinition =
16463       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16464 
16465   VarTemplateSpecializationDecl *VarSpec =
16466       dyn_cast<VarTemplateSpecializationDecl>(Var);
16467   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16468          "Can't instantiate a partial template specialization.");
16469 
16470   // If this might be a member specialization of a static data member, check
16471   // the specialization is visible. We already did the checks for variable
16472   // template specializations when we created them.
16473   if (NeedDefinition && TSK != TSK_Undeclared &&
16474       !isa<VarTemplateSpecializationDecl>(Var))
16475     SemaRef.checkSpecializationVisibility(Loc, Var);
16476 
16477   // Perform implicit instantiation of static data members, static data member
16478   // templates of class templates, and variable template specializations. Delay
16479   // instantiations of variable templates, except for those that could be used
16480   // in a constant expression.
16481   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16482     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16483     // instantiation declaration if a variable is usable in a constant
16484     // expression (among other cases).
16485     bool TryInstantiating =
16486         TSK == TSK_ImplicitInstantiation ||
16487         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16488 
16489     if (TryInstantiating) {
16490       SourceLocation PointOfInstantiation =
16491           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16492       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16493       if (FirstInstantiation) {
16494         PointOfInstantiation = Loc;
16495         if (MSI)
16496           MSI->setPointOfInstantiation(PointOfInstantiation);
16497         else
16498           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16499       }
16500 
16501       bool InstantiationDependent = false;
16502       bool IsNonDependent =
16503           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16504                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16505                   : true;
16506 
16507       // Do not instantiate specializations that are still type-dependent.
16508       if (IsNonDependent) {
16509         if (UsableInConstantExpr) {
16510           // Do not defer instantiations of variables that could be used in a
16511           // constant expression.
16512           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16513             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16514           });
16515         } else if (FirstInstantiation ||
16516                    isa<VarTemplateSpecializationDecl>(Var)) {
16517           // FIXME: For a specialization of a variable template, we don't
16518           // distinguish between "declaration and type implicitly instantiated"
16519           // and "implicit instantiation of definition requested", so we have
16520           // no direct way to avoid enqueueing the pending instantiation
16521           // multiple times.
16522           SemaRef.PendingInstantiations
16523               .push_back(std::make_pair(Var, PointOfInstantiation));
16524         }
16525       }
16526     }
16527   }
16528 
16529   // C++2a [basic.def.odr]p4:
16530   //   A variable x whose name appears as a potentially-evaluated expression e
16531   //   is odr-used by e unless
16532   //   -- x is a reference that is usable in constant expressions
16533   //   -- x is a variable of non-reference type that is usable in constant
16534   //      expressions and has no mutable subobjects [FIXME], and e is an
16535   //      element of the set of potential results of an expression of
16536   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16537   //      conversion is applied
16538   //   -- x is a variable of non-reference type, and e is an element of the set
16539   //      of potential results of a discarded-value expression to which the
16540   //      lvalue-to-rvalue conversion is not applied [FIXME]
16541   //
16542   // We check the first part of the second bullet here, and
16543   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16544   // FIXME: To get the third bullet right, we need to delay this even for
16545   // variables that are not usable in constant expressions.
16546 
16547   // If we already know this isn't an odr-use, there's nothing more to do.
16548   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16549     if (DRE->isNonOdrUse())
16550       return;
16551   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16552     if (ME->isNonOdrUse())
16553       return;
16554 
16555   switch (OdrUse) {
16556   case OdrUseContext::None:
16557     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16558            "missing non-odr-use marking for unevaluated decl ref");
16559     break;
16560 
16561   case OdrUseContext::FormallyOdrUsed:
16562     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16563     // behavior.
16564     break;
16565 
16566   case OdrUseContext::Used:
16567     // If we might later find that this expression isn't actually an odr-use,
16568     // delay the marking.
16569     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16570       SemaRef.MaybeODRUseExprs.insert(E);
16571     else
16572       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16573     break;
16574 
16575   case OdrUseContext::Dependent:
16576     // If this is a dependent context, we don't need to mark variables as
16577     // odr-used, but we may still need to track them for lambda capture.
16578     // FIXME: Do we also need to do this inside dependent typeid expressions
16579     // (which are modeled as unevaluated at this point)?
16580     const bool RefersToEnclosingScope =
16581         (SemaRef.CurContext != Var->getDeclContext() &&
16582          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16583     if (RefersToEnclosingScope) {
16584       LambdaScopeInfo *const LSI =
16585           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16586       if (LSI && (!LSI->CallOperator ||
16587                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16588         // If a variable could potentially be odr-used, defer marking it so
16589         // until we finish analyzing the full expression for any
16590         // lvalue-to-rvalue
16591         // or discarded value conversions that would obviate odr-use.
16592         // Add it to the list of potential captures that will be analyzed
16593         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16594         // unless the variable is a reference that was initialized by a constant
16595         // expression (this will never need to be captured or odr-used).
16596         //
16597         // FIXME: We can simplify this a lot after implementing P0588R1.
16598         assert(E && "Capture variable should be used in an expression.");
16599         if (!Var->getType()->isReferenceType() ||
16600             !Var->isUsableInConstantExpressions(SemaRef.Context))
16601           LSI->addPotentialCapture(E->IgnoreParens());
16602       }
16603     }
16604     break;
16605   }
16606 }
16607 
16608 /// Mark a variable referenced, and check whether it is odr-used
16609 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16610 /// used directly for normal expressions referring to VarDecl.
16611 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16612   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16613 }
16614 
16615 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16616                                Decl *D, Expr *E, bool MightBeOdrUse) {
16617   if (SemaRef.isInOpenMPDeclareTargetContext())
16618     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16619 
16620   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16621     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16622     return;
16623   }
16624 
16625   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16626 
16627   // If this is a call to a method via a cast, also mark the method in the
16628   // derived class used in case codegen can devirtualize the call.
16629   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16630   if (!ME)
16631     return;
16632   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16633   if (!MD)
16634     return;
16635   // Only attempt to devirtualize if this is truly a virtual call.
16636   bool IsVirtualCall = MD->isVirtual() &&
16637                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16638   if (!IsVirtualCall)
16639     return;
16640 
16641   // If it's possible to devirtualize the call, mark the called function
16642   // referenced.
16643   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16644       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16645   if (DM)
16646     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16647 }
16648 
16649 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16650 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16651   // TODO: update this with DR# once a defect report is filed.
16652   // C++11 defect. The address of a pure member should not be an ODR use, even
16653   // if it's a qualified reference.
16654   bool OdrUse = true;
16655   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16656     if (Method->isVirtual() &&
16657         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16658       OdrUse = false;
16659   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16660 }
16661 
16662 /// Perform reference-marking and odr-use handling for a MemberExpr.
16663 void Sema::MarkMemberReferenced(MemberExpr *E) {
16664   // C++11 [basic.def.odr]p2:
16665   //   A non-overloaded function whose name appears as a potentially-evaluated
16666   //   expression or a member of a set of candidate functions, if selected by
16667   //   overload resolution when referred to from a potentially-evaluated
16668   //   expression, is odr-used, unless it is a pure virtual function and its
16669   //   name is not explicitly qualified.
16670   bool MightBeOdrUse = true;
16671   if (E->performsVirtualDispatch(getLangOpts())) {
16672     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16673       if (Method->isPure())
16674         MightBeOdrUse = false;
16675   }
16676   SourceLocation Loc =
16677       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16678   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16679 }
16680 
16681 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16682 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16683   for (VarDecl *VD : *E)
16684     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16685 }
16686 
16687 /// Perform marking for a reference to an arbitrary declaration.  It
16688 /// marks the declaration referenced, and performs odr-use checking for
16689 /// functions and variables. This method should not be used when building a
16690 /// normal expression which refers to a variable.
16691 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16692                                  bool MightBeOdrUse) {
16693   if (MightBeOdrUse) {
16694     if (auto *VD = dyn_cast<VarDecl>(D)) {
16695       MarkVariableReferenced(Loc, VD);
16696       return;
16697     }
16698   }
16699   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16700     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16701     return;
16702   }
16703   D->setReferenced();
16704 }
16705 
16706 namespace {
16707   // Mark all of the declarations used by a type as referenced.
16708   // FIXME: Not fully implemented yet! We need to have a better understanding
16709   // of when we're entering a context we should not recurse into.
16710   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16711   // TreeTransforms rebuilding the type in a new context. Rather than
16712   // duplicating the TreeTransform logic, we should consider reusing it here.
16713   // Currently that causes problems when rebuilding LambdaExprs.
16714   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16715     Sema &S;
16716     SourceLocation Loc;
16717 
16718   public:
16719     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16720 
16721     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16722 
16723     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16724   };
16725 }
16726 
16727 bool MarkReferencedDecls::TraverseTemplateArgument(
16728     const TemplateArgument &Arg) {
16729   {
16730     // A non-type template argument is a constant-evaluated context.
16731     EnterExpressionEvaluationContext Evaluated(
16732         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16733     if (Arg.getKind() == TemplateArgument::Declaration) {
16734       if (Decl *D = Arg.getAsDecl())
16735         S.MarkAnyDeclReferenced(Loc, D, true);
16736     } else if (Arg.getKind() == TemplateArgument::Expression) {
16737       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16738     }
16739   }
16740 
16741   return Inherited::TraverseTemplateArgument(Arg);
16742 }
16743 
16744 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16745   MarkReferencedDecls Marker(*this, Loc);
16746   Marker.TraverseType(T);
16747 }
16748 
16749 namespace {
16750   /// Helper class that marks all of the declarations referenced by
16751   /// potentially-evaluated subexpressions as "referenced".
16752   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16753     Sema &S;
16754     bool SkipLocalVariables;
16755 
16756   public:
16757     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16758 
16759     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16760       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16761 
16762     void VisitDeclRefExpr(DeclRefExpr *E) {
16763       // If we were asked not to visit local variables, don't.
16764       if (SkipLocalVariables) {
16765         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16766           if (VD->hasLocalStorage())
16767             return;
16768       }
16769 
16770       S.MarkDeclRefReferenced(E);
16771     }
16772 
16773     void VisitMemberExpr(MemberExpr *E) {
16774       S.MarkMemberReferenced(E);
16775       Inherited::VisitMemberExpr(E);
16776     }
16777 
16778     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16779       S.MarkFunctionReferenced(
16780           E->getBeginLoc(),
16781           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16782       Visit(E->getSubExpr());
16783     }
16784 
16785     void VisitCXXNewExpr(CXXNewExpr *E) {
16786       if (E->getOperatorNew())
16787         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16788       if (E->getOperatorDelete())
16789         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16790       Inherited::VisitCXXNewExpr(E);
16791     }
16792 
16793     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16794       if (E->getOperatorDelete())
16795         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16796       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16797       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16798         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16799         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16800       }
16801 
16802       Inherited::VisitCXXDeleteExpr(E);
16803     }
16804 
16805     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16806       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16807       Inherited::VisitCXXConstructExpr(E);
16808     }
16809 
16810     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16811       Visit(E->getExpr());
16812     }
16813   };
16814 }
16815 
16816 /// Mark any declarations that appear within this expression or any
16817 /// potentially-evaluated subexpressions as "referenced".
16818 ///
16819 /// \param SkipLocalVariables If true, don't mark local variables as
16820 /// 'referenced'.
16821 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16822                                             bool SkipLocalVariables) {
16823   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16824 }
16825 
16826 /// Emit a diagnostic that describes an effect on the run-time behavior
16827 /// of the program being compiled.
16828 ///
16829 /// This routine emits the given diagnostic when the code currently being
16830 /// type-checked is "potentially evaluated", meaning that there is a
16831 /// possibility that the code will actually be executable. Code in sizeof()
16832 /// expressions, code used only during overload resolution, etc., are not
16833 /// potentially evaluated. This routine will suppress such diagnostics or,
16834 /// in the absolutely nutty case of potentially potentially evaluated
16835 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16836 /// later.
16837 ///
16838 /// This routine should be used for all diagnostics that describe the run-time
16839 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16840 /// Failure to do so will likely result in spurious diagnostics or failures
16841 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16842 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
16843                                const PartialDiagnostic &PD) {
16844   switch (ExprEvalContexts.back().Context) {
16845   case ExpressionEvaluationContext::Unevaluated:
16846   case ExpressionEvaluationContext::UnevaluatedList:
16847   case ExpressionEvaluationContext::UnevaluatedAbstract:
16848   case ExpressionEvaluationContext::DiscardedStatement:
16849     // The argument will never be evaluated, so don't complain.
16850     break;
16851 
16852   case ExpressionEvaluationContext::ConstantEvaluated:
16853     // Relevant diagnostics should be produced by constant evaluation.
16854     break;
16855 
16856   case ExpressionEvaluationContext::PotentiallyEvaluated:
16857   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16858     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
16859       FunctionScopes.back()->PossiblyUnreachableDiags.
16860         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
16861       return true;
16862     }
16863 
16864     // The initializer of a constexpr variable or of the first declaration of a
16865     // static data member is not syntactically a constant evaluated constant,
16866     // but nonetheless is always required to be a constant expression, so we
16867     // can skip diagnosing.
16868     // FIXME: Using the mangling context here is a hack.
16869     if (auto *VD = dyn_cast_or_null<VarDecl>(
16870             ExprEvalContexts.back().ManglingContextDecl)) {
16871       if (VD->isConstexpr() ||
16872           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16873         break;
16874       // FIXME: For any other kind of variable, we should build a CFG for its
16875       // initializer and check whether the context in question is reachable.
16876     }
16877 
16878     Diag(Loc, PD);
16879     return true;
16880   }
16881 
16882   return false;
16883 }
16884 
16885 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16886                                const PartialDiagnostic &PD) {
16887   return DiagRuntimeBehavior(
16888       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
16889 }
16890 
16891 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16892                                CallExpr *CE, FunctionDecl *FD) {
16893   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16894     return false;
16895 
16896   // If we're inside a decltype's expression, don't check for a valid return
16897   // type or construct temporaries until we know whether this is the last call.
16898   if (ExprEvalContexts.back().ExprContext ==
16899       ExpressionEvaluationContextRecord::EK_Decltype) {
16900     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16901     return false;
16902   }
16903 
16904   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16905     FunctionDecl *FD;
16906     CallExpr *CE;
16907 
16908   public:
16909     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16910       : FD(FD), CE(CE) { }
16911 
16912     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16913       if (!FD) {
16914         S.Diag(Loc, diag::err_call_incomplete_return)
16915           << T << CE->getSourceRange();
16916         return;
16917       }
16918 
16919       S.Diag(Loc, diag::err_call_function_incomplete_return)
16920         << CE->getSourceRange() << FD->getDeclName() << T;
16921       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16922           << FD->getDeclName();
16923     }
16924   } Diagnoser(FD, CE);
16925 
16926   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16927     return true;
16928 
16929   return false;
16930 }
16931 
16932 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16933 // will prevent this condition from triggering, which is what we want.
16934 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16935   SourceLocation Loc;
16936 
16937   unsigned diagnostic = diag::warn_condition_is_assignment;
16938   bool IsOrAssign = false;
16939 
16940   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16941     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16942       return;
16943 
16944     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16945 
16946     // Greylist some idioms by putting them into a warning subcategory.
16947     if (ObjCMessageExpr *ME
16948           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16949       Selector Sel = ME->getSelector();
16950 
16951       // self = [<foo> init...]
16952       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16953         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16954 
16955       // <foo> = [<bar> nextObject]
16956       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16957         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16958     }
16959 
16960     Loc = Op->getOperatorLoc();
16961   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16962     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16963       return;
16964 
16965     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16966     Loc = Op->getOperatorLoc();
16967   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16968     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16969   else {
16970     // Not an assignment.
16971     return;
16972   }
16973 
16974   Diag(Loc, diagnostic) << E->getSourceRange();
16975 
16976   SourceLocation Open = E->getBeginLoc();
16977   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16978   Diag(Loc, diag::note_condition_assign_silence)
16979         << FixItHint::CreateInsertion(Open, "(")
16980         << FixItHint::CreateInsertion(Close, ")");
16981 
16982   if (IsOrAssign)
16983     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16984       << FixItHint::CreateReplacement(Loc, "!=");
16985   else
16986     Diag(Loc, diag::note_condition_assign_to_comparison)
16987       << FixItHint::CreateReplacement(Loc, "==");
16988 }
16989 
16990 /// Redundant parentheses over an equality comparison can indicate
16991 /// that the user intended an assignment used as condition.
16992 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16993   // Don't warn if the parens came from a macro.
16994   SourceLocation parenLoc = ParenE->getBeginLoc();
16995   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16996     return;
16997   // Don't warn for dependent expressions.
16998   if (ParenE->isTypeDependent())
16999     return;
17000 
17001   Expr *E = ParenE->IgnoreParens();
17002 
17003   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17004     if (opE->getOpcode() == BO_EQ &&
17005         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17006                                                            == Expr::MLV_Valid) {
17007       SourceLocation Loc = opE->getOperatorLoc();
17008 
17009       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17010       SourceRange ParenERange = ParenE->getSourceRange();
17011       Diag(Loc, diag::note_equality_comparison_silence)
17012         << FixItHint::CreateRemoval(ParenERange.getBegin())
17013         << FixItHint::CreateRemoval(ParenERange.getEnd());
17014       Diag(Loc, diag::note_equality_comparison_to_assign)
17015         << FixItHint::CreateReplacement(Loc, "=");
17016     }
17017 }
17018 
17019 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17020                                        bool IsConstexpr) {
17021   DiagnoseAssignmentAsCondition(E);
17022   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17023     DiagnoseEqualityWithExtraParens(parenE);
17024 
17025   ExprResult result = CheckPlaceholderExpr(E);
17026   if (result.isInvalid()) return ExprError();
17027   E = result.get();
17028 
17029   if (!E->isTypeDependent()) {
17030     if (getLangOpts().CPlusPlus)
17031       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17032 
17033     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17034     if (ERes.isInvalid())
17035       return ExprError();
17036     E = ERes.get();
17037 
17038     QualType T = E->getType();
17039     if (!T->isScalarType()) { // C99 6.8.4.1p1
17040       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17041         << T << E->getSourceRange();
17042       return ExprError();
17043     }
17044     CheckBoolLikeConversion(E, Loc);
17045   }
17046 
17047   return E;
17048 }
17049 
17050 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17051                                            Expr *SubExpr, ConditionKind CK) {
17052   // Empty conditions are valid in for-statements.
17053   if (!SubExpr)
17054     return ConditionResult();
17055 
17056   ExprResult Cond;
17057   switch (CK) {
17058   case ConditionKind::Boolean:
17059     Cond = CheckBooleanCondition(Loc, SubExpr);
17060     break;
17061 
17062   case ConditionKind::ConstexprIf:
17063     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17064     break;
17065 
17066   case ConditionKind::Switch:
17067     Cond = CheckSwitchCondition(Loc, SubExpr);
17068     break;
17069   }
17070   if (Cond.isInvalid())
17071     return ConditionError();
17072 
17073   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17074   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17075   if (!FullExpr.get())
17076     return ConditionError();
17077 
17078   return ConditionResult(*this, nullptr, FullExpr,
17079                          CK == ConditionKind::ConstexprIf);
17080 }
17081 
17082 namespace {
17083   /// A visitor for rebuilding a call to an __unknown_any expression
17084   /// to have an appropriate type.
17085   struct RebuildUnknownAnyFunction
17086     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17087 
17088     Sema &S;
17089 
17090     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17091 
17092     ExprResult VisitStmt(Stmt *S) {
17093       llvm_unreachable("unexpected statement!");
17094     }
17095 
17096     ExprResult VisitExpr(Expr *E) {
17097       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17098         << E->getSourceRange();
17099       return ExprError();
17100     }
17101 
17102     /// Rebuild an expression which simply semantically wraps another
17103     /// expression which it shares the type and value kind of.
17104     template <class T> ExprResult rebuildSugarExpr(T *E) {
17105       ExprResult SubResult = Visit(E->getSubExpr());
17106       if (SubResult.isInvalid()) return ExprError();
17107 
17108       Expr *SubExpr = SubResult.get();
17109       E->setSubExpr(SubExpr);
17110       E->setType(SubExpr->getType());
17111       E->setValueKind(SubExpr->getValueKind());
17112       assert(E->getObjectKind() == OK_Ordinary);
17113       return E;
17114     }
17115 
17116     ExprResult VisitParenExpr(ParenExpr *E) {
17117       return rebuildSugarExpr(E);
17118     }
17119 
17120     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17121       return rebuildSugarExpr(E);
17122     }
17123 
17124     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17125       ExprResult SubResult = Visit(E->getSubExpr());
17126       if (SubResult.isInvalid()) return ExprError();
17127 
17128       Expr *SubExpr = SubResult.get();
17129       E->setSubExpr(SubExpr);
17130       E->setType(S.Context.getPointerType(SubExpr->getType()));
17131       assert(E->getValueKind() == VK_RValue);
17132       assert(E->getObjectKind() == OK_Ordinary);
17133       return E;
17134     }
17135 
17136     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17137       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17138 
17139       E->setType(VD->getType());
17140 
17141       assert(E->getValueKind() == VK_RValue);
17142       if (S.getLangOpts().CPlusPlus &&
17143           !(isa<CXXMethodDecl>(VD) &&
17144             cast<CXXMethodDecl>(VD)->isInstance()))
17145         E->setValueKind(VK_LValue);
17146 
17147       return E;
17148     }
17149 
17150     ExprResult VisitMemberExpr(MemberExpr *E) {
17151       return resolveDecl(E, E->getMemberDecl());
17152     }
17153 
17154     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17155       return resolveDecl(E, E->getDecl());
17156     }
17157   };
17158 }
17159 
17160 /// Given a function expression of unknown-any type, try to rebuild it
17161 /// to have a function type.
17162 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17163   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17164   if (Result.isInvalid()) return ExprError();
17165   return S.DefaultFunctionArrayConversion(Result.get());
17166 }
17167 
17168 namespace {
17169   /// A visitor for rebuilding an expression of type __unknown_anytype
17170   /// into one which resolves the type directly on the referring
17171   /// expression.  Strict preservation of the original source
17172   /// structure is not a goal.
17173   struct RebuildUnknownAnyExpr
17174     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17175 
17176     Sema &S;
17177 
17178     /// The current destination type.
17179     QualType DestType;
17180 
17181     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17182       : S(S), DestType(CastType) {}
17183 
17184     ExprResult VisitStmt(Stmt *S) {
17185       llvm_unreachable("unexpected statement!");
17186     }
17187 
17188     ExprResult VisitExpr(Expr *E) {
17189       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17190         << E->getSourceRange();
17191       return ExprError();
17192     }
17193 
17194     ExprResult VisitCallExpr(CallExpr *E);
17195     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17196 
17197     /// Rebuild an expression which simply semantically wraps another
17198     /// expression which it shares the type and value kind of.
17199     template <class T> ExprResult rebuildSugarExpr(T *E) {
17200       ExprResult SubResult = Visit(E->getSubExpr());
17201       if (SubResult.isInvalid()) return ExprError();
17202       Expr *SubExpr = SubResult.get();
17203       E->setSubExpr(SubExpr);
17204       E->setType(SubExpr->getType());
17205       E->setValueKind(SubExpr->getValueKind());
17206       assert(E->getObjectKind() == OK_Ordinary);
17207       return E;
17208     }
17209 
17210     ExprResult VisitParenExpr(ParenExpr *E) {
17211       return rebuildSugarExpr(E);
17212     }
17213 
17214     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17215       return rebuildSugarExpr(E);
17216     }
17217 
17218     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17219       const PointerType *Ptr = DestType->getAs<PointerType>();
17220       if (!Ptr) {
17221         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17222           << E->getSourceRange();
17223         return ExprError();
17224       }
17225 
17226       if (isa<CallExpr>(E->getSubExpr())) {
17227         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17228           << E->getSourceRange();
17229         return ExprError();
17230       }
17231 
17232       assert(E->getValueKind() == VK_RValue);
17233       assert(E->getObjectKind() == OK_Ordinary);
17234       E->setType(DestType);
17235 
17236       // Build the sub-expression as if it were an object of the pointee type.
17237       DestType = Ptr->getPointeeType();
17238       ExprResult SubResult = Visit(E->getSubExpr());
17239       if (SubResult.isInvalid()) return ExprError();
17240       E->setSubExpr(SubResult.get());
17241       return E;
17242     }
17243 
17244     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17245 
17246     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17247 
17248     ExprResult VisitMemberExpr(MemberExpr *E) {
17249       return resolveDecl(E, E->getMemberDecl());
17250     }
17251 
17252     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17253       return resolveDecl(E, E->getDecl());
17254     }
17255   };
17256 }
17257 
17258 /// Rebuilds a call expression which yielded __unknown_anytype.
17259 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17260   Expr *CalleeExpr = E->getCallee();
17261 
17262   enum FnKind {
17263     FK_MemberFunction,
17264     FK_FunctionPointer,
17265     FK_BlockPointer
17266   };
17267 
17268   FnKind Kind;
17269   QualType CalleeType = CalleeExpr->getType();
17270   if (CalleeType == S.Context.BoundMemberTy) {
17271     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17272     Kind = FK_MemberFunction;
17273     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17274   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17275     CalleeType = Ptr->getPointeeType();
17276     Kind = FK_FunctionPointer;
17277   } else {
17278     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17279     Kind = FK_BlockPointer;
17280   }
17281   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17282 
17283   // Verify that this is a legal result type of a function.
17284   if (DestType->isArrayType() || DestType->isFunctionType()) {
17285     unsigned diagID = diag::err_func_returning_array_function;
17286     if (Kind == FK_BlockPointer)
17287       diagID = diag::err_block_returning_array_function;
17288 
17289     S.Diag(E->getExprLoc(), diagID)
17290       << DestType->isFunctionType() << DestType;
17291     return ExprError();
17292   }
17293 
17294   // Otherwise, go ahead and set DestType as the call's result.
17295   E->setType(DestType.getNonLValueExprType(S.Context));
17296   E->setValueKind(Expr::getValueKindForType(DestType));
17297   assert(E->getObjectKind() == OK_Ordinary);
17298 
17299   // Rebuild the function type, replacing the result type with DestType.
17300   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17301   if (Proto) {
17302     // __unknown_anytype(...) is a special case used by the debugger when
17303     // it has no idea what a function's signature is.
17304     //
17305     // We want to build this call essentially under the K&R
17306     // unprototyped rules, but making a FunctionNoProtoType in C++
17307     // would foul up all sorts of assumptions.  However, we cannot
17308     // simply pass all arguments as variadic arguments, nor can we
17309     // portably just call the function under a non-variadic type; see
17310     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17311     // However, it turns out that in practice it is generally safe to
17312     // call a function declared as "A foo(B,C,D);" under the prototype
17313     // "A foo(B,C,D,...);".  The only known exception is with the
17314     // Windows ABI, where any variadic function is implicitly cdecl
17315     // regardless of its normal CC.  Therefore we change the parameter
17316     // types to match the types of the arguments.
17317     //
17318     // This is a hack, but it is far superior to moving the
17319     // corresponding target-specific code from IR-gen to Sema/AST.
17320 
17321     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17322     SmallVector<QualType, 8> ArgTypes;
17323     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17324       ArgTypes.reserve(E->getNumArgs());
17325       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17326         Expr *Arg = E->getArg(i);
17327         QualType ArgType = Arg->getType();
17328         if (E->isLValue()) {
17329           ArgType = S.Context.getLValueReferenceType(ArgType);
17330         } else if (E->isXValue()) {
17331           ArgType = S.Context.getRValueReferenceType(ArgType);
17332         }
17333         ArgTypes.push_back(ArgType);
17334       }
17335       ParamTypes = ArgTypes;
17336     }
17337     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17338                                          Proto->getExtProtoInfo());
17339   } else {
17340     DestType = S.Context.getFunctionNoProtoType(DestType,
17341                                                 FnType->getExtInfo());
17342   }
17343 
17344   // Rebuild the appropriate pointer-to-function type.
17345   switch (Kind) {
17346   case FK_MemberFunction:
17347     // Nothing to do.
17348     break;
17349 
17350   case FK_FunctionPointer:
17351     DestType = S.Context.getPointerType(DestType);
17352     break;
17353 
17354   case FK_BlockPointer:
17355     DestType = S.Context.getBlockPointerType(DestType);
17356     break;
17357   }
17358 
17359   // Finally, we can recurse.
17360   ExprResult CalleeResult = Visit(CalleeExpr);
17361   if (!CalleeResult.isUsable()) return ExprError();
17362   E->setCallee(CalleeResult.get());
17363 
17364   // Bind a temporary if necessary.
17365   return S.MaybeBindToTemporary(E);
17366 }
17367 
17368 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17369   // Verify that this is a legal result type of a call.
17370   if (DestType->isArrayType() || DestType->isFunctionType()) {
17371     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17372       << DestType->isFunctionType() << DestType;
17373     return ExprError();
17374   }
17375 
17376   // Rewrite the method result type if available.
17377   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17378     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17379     Method->setReturnType(DestType);
17380   }
17381 
17382   // Change the type of the message.
17383   E->setType(DestType.getNonReferenceType());
17384   E->setValueKind(Expr::getValueKindForType(DestType));
17385 
17386   return S.MaybeBindToTemporary(E);
17387 }
17388 
17389 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17390   // The only case we should ever see here is a function-to-pointer decay.
17391   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17392     assert(E->getValueKind() == VK_RValue);
17393     assert(E->getObjectKind() == OK_Ordinary);
17394 
17395     E->setType(DestType);
17396 
17397     // Rebuild the sub-expression as the pointee (function) type.
17398     DestType = DestType->castAs<PointerType>()->getPointeeType();
17399 
17400     ExprResult Result = Visit(E->getSubExpr());
17401     if (!Result.isUsable()) return ExprError();
17402 
17403     E->setSubExpr(Result.get());
17404     return E;
17405   } else if (E->getCastKind() == CK_LValueToRValue) {
17406     assert(E->getValueKind() == VK_RValue);
17407     assert(E->getObjectKind() == OK_Ordinary);
17408 
17409     assert(isa<BlockPointerType>(E->getType()));
17410 
17411     E->setType(DestType);
17412 
17413     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17414     DestType = S.Context.getLValueReferenceType(DestType);
17415 
17416     ExprResult Result = Visit(E->getSubExpr());
17417     if (!Result.isUsable()) return ExprError();
17418 
17419     E->setSubExpr(Result.get());
17420     return E;
17421   } else {
17422     llvm_unreachable("Unhandled cast type!");
17423   }
17424 }
17425 
17426 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17427   ExprValueKind ValueKind = VK_LValue;
17428   QualType Type = DestType;
17429 
17430   // We know how to make this work for certain kinds of decls:
17431 
17432   //  - functions
17433   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17434     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17435       DestType = Ptr->getPointeeType();
17436       ExprResult Result = resolveDecl(E, VD);
17437       if (Result.isInvalid()) return ExprError();
17438       return S.ImpCastExprToType(Result.get(), Type,
17439                                  CK_FunctionToPointerDecay, VK_RValue);
17440     }
17441 
17442     if (!Type->isFunctionType()) {
17443       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17444         << VD << E->getSourceRange();
17445       return ExprError();
17446     }
17447     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17448       // We must match the FunctionDecl's type to the hack introduced in
17449       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17450       // type. See the lengthy commentary in that routine.
17451       QualType FDT = FD->getType();
17452       const FunctionType *FnType = FDT->castAs<FunctionType>();
17453       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17454       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17455       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17456         SourceLocation Loc = FD->getLocation();
17457         FunctionDecl *NewFD = FunctionDecl::Create(
17458             S.Context, FD->getDeclContext(), Loc, Loc,
17459             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17460             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17461             /*ConstexprKind*/ CSK_unspecified);
17462 
17463         if (FD->getQualifier())
17464           NewFD->setQualifierInfo(FD->getQualifierLoc());
17465 
17466         SmallVector<ParmVarDecl*, 16> Params;
17467         for (const auto &AI : FT->param_types()) {
17468           ParmVarDecl *Param =
17469             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17470           Param->setScopeInfo(0, Params.size());
17471           Params.push_back(Param);
17472         }
17473         NewFD->setParams(Params);
17474         DRE->setDecl(NewFD);
17475         VD = DRE->getDecl();
17476       }
17477     }
17478 
17479     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17480       if (MD->isInstance()) {
17481         ValueKind = VK_RValue;
17482         Type = S.Context.BoundMemberTy;
17483       }
17484 
17485     // Function references aren't l-values in C.
17486     if (!S.getLangOpts().CPlusPlus)
17487       ValueKind = VK_RValue;
17488 
17489   //  - variables
17490   } else if (isa<VarDecl>(VD)) {
17491     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17492       Type = RefTy->getPointeeType();
17493     } else if (Type->isFunctionType()) {
17494       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17495         << VD << E->getSourceRange();
17496       return ExprError();
17497     }
17498 
17499   //  - nothing else
17500   } else {
17501     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17502       << VD << E->getSourceRange();
17503     return ExprError();
17504   }
17505 
17506   // Modifying the declaration like this is friendly to IR-gen but
17507   // also really dangerous.
17508   VD->setType(DestType);
17509   E->setType(Type);
17510   E->setValueKind(ValueKind);
17511   return E;
17512 }
17513 
17514 /// Check a cast of an unknown-any type.  We intentionally only
17515 /// trigger this for C-style casts.
17516 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17517                                      Expr *CastExpr, CastKind &CastKind,
17518                                      ExprValueKind &VK, CXXCastPath &Path) {
17519   // The type we're casting to must be either void or complete.
17520   if (!CastType->isVoidType() &&
17521       RequireCompleteType(TypeRange.getBegin(), CastType,
17522                           diag::err_typecheck_cast_to_incomplete))
17523     return ExprError();
17524 
17525   // Rewrite the casted expression from scratch.
17526   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17527   if (!result.isUsable()) return ExprError();
17528 
17529   CastExpr = result.get();
17530   VK = CastExpr->getValueKind();
17531   CastKind = CK_NoOp;
17532 
17533   return CastExpr;
17534 }
17535 
17536 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17537   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17538 }
17539 
17540 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17541                                     Expr *arg, QualType &paramType) {
17542   // If the syntactic form of the argument is not an explicit cast of
17543   // any sort, just do default argument promotion.
17544   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17545   if (!castArg) {
17546     ExprResult result = DefaultArgumentPromotion(arg);
17547     if (result.isInvalid()) return ExprError();
17548     paramType = result.get()->getType();
17549     return result;
17550   }
17551 
17552   // Otherwise, use the type that was written in the explicit cast.
17553   assert(!arg->hasPlaceholderType());
17554   paramType = castArg->getTypeAsWritten();
17555 
17556   // Copy-initialize a parameter of that type.
17557   InitializedEntity entity =
17558     InitializedEntity::InitializeParameter(Context, paramType,
17559                                            /*consumed*/ false);
17560   return PerformCopyInitialization(entity, callLoc, arg);
17561 }
17562 
17563 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17564   Expr *orig = E;
17565   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17566   while (true) {
17567     E = E->IgnoreParenImpCasts();
17568     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17569       E = call->getCallee();
17570       diagID = diag::err_uncasted_call_of_unknown_any;
17571     } else {
17572       break;
17573     }
17574   }
17575 
17576   SourceLocation loc;
17577   NamedDecl *d;
17578   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17579     loc = ref->getLocation();
17580     d = ref->getDecl();
17581   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17582     loc = mem->getMemberLoc();
17583     d = mem->getMemberDecl();
17584   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17585     diagID = diag::err_uncasted_call_of_unknown_any;
17586     loc = msg->getSelectorStartLoc();
17587     d = msg->getMethodDecl();
17588     if (!d) {
17589       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17590         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17591         << orig->getSourceRange();
17592       return ExprError();
17593     }
17594   } else {
17595     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17596       << E->getSourceRange();
17597     return ExprError();
17598   }
17599 
17600   S.Diag(loc, diagID) << d << orig->getSourceRange();
17601 
17602   // Never recoverable.
17603   return ExprError();
17604 }
17605 
17606 /// Check for operands with placeholder types and complain if found.
17607 /// Returns ExprError() if there was an error and no recovery was possible.
17608 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17609   if (!getLangOpts().CPlusPlus) {
17610     // C cannot handle TypoExpr nodes on either side of a binop because it
17611     // doesn't handle dependent types properly, so make sure any TypoExprs have
17612     // been dealt with before checking the operands.
17613     ExprResult Result = CorrectDelayedTyposInExpr(E);
17614     if (!Result.isUsable()) return ExprError();
17615     E = Result.get();
17616   }
17617 
17618   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17619   if (!placeholderType) return E;
17620 
17621   switch (placeholderType->getKind()) {
17622 
17623   // Overloaded expressions.
17624   case BuiltinType::Overload: {
17625     // Try to resolve a single function template specialization.
17626     // This is obligatory.
17627     ExprResult Result = E;
17628     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17629       return Result;
17630 
17631     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17632     // leaves Result unchanged on failure.
17633     Result = E;
17634     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17635       return Result;
17636 
17637     // If that failed, try to recover with a call.
17638     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17639                          /*complain*/ true);
17640     return Result;
17641   }
17642 
17643   // Bound member functions.
17644   case BuiltinType::BoundMember: {
17645     ExprResult result = E;
17646     const Expr *BME = E->IgnoreParens();
17647     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17648     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17649     if (isa<CXXPseudoDestructorExpr>(BME)) {
17650       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17651     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17652       if (ME->getMemberNameInfo().getName().getNameKind() ==
17653           DeclarationName::CXXDestructorName)
17654         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17655     }
17656     tryToRecoverWithCall(result, PD,
17657                          /*complain*/ true);
17658     return result;
17659   }
17660 
17661   // ARC unbridged casts.
17662   case BuiltinType::ARCUnbridgedCast: {
17663     Expr *realCast = stripARCUnbridgedCast(E);
17664     diagnoseARCUnbridgedCast(realCast);
17665     return realCast;
17666   }
17667 
17668   // Expressions of unknown type.
17669   case BuiltinType::UnknownAny:
17670     return diagnoseUnknownAnyExpr(*this, E);
17671 
17672   // Pseudo-objects.
17673   case BuiltinType::PseudoObject:
17674     return checkPseudoObjectRValue(E);
17675 
17676   case BuiltinType::BuiltinFn: {
17677     // Accept __noop without parens by implicitly converting it to a call expr.
17678     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17679     if (DRE) {
17680       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17681       if (FD->getBuiltinID() == Builtin::BI__noop) {
17682         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17683                               CK_BuiltinFnToFnPtr)
17684                 .get();
17685         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17686                                 VK_RValue, SourceLocation());
17687       }
17688     }
17689 
17690     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17691     return ExprError();
17692   }
17693 
17694   // Expressions of unknown type.
17695   case BuiltinType::OMPArraySection:
17696     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17697     return ExprError();
17698 
17699   // Everything else should be impossible.
17700 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17701   case BuiltinType::Id:
17702 #include "clang/Basic/OpenCLImageTypes.def"
17703 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17704   case BuiltinType::Id:
17705 #include "clang/Basic/OpenCLExtensionTypes.def"
17706 #define SVE_TYPE(Name, Id, SingletonId) \
17707   case BuiltinType::Id:
17708 #include "clang/Basic/AArch64SVEACLETypes.def"
17709 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17710 #define PLACEHOLDER_TYPE(Id, SingletonId)
17711 #include "clang/AST/BuiltinTypes.def"
17712     break;
17713   }
17714 
17715   llvm_unreachable("invalid placeholder type!");
17716 }
17717 
17718 bool Sema::CheckCaseExpression(Expr *E) {
17719   if (E->isTypeDependent())
17720     return true;
17721   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17722     return E->getType()->isIntegralOrEnumerationType();
17723   return false;
17724 }
17725 
17726 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17727 ExprResult
17728 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17729   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17730          "Unknown Objective-C Boolean value!");
17731   QualType BoolT = Context.ObjCBuiltinBoolTy;
17732   if (!Context.getBOOLDecl()) {
17733     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17734                         Sema::LookupOrdinaryName);
17735     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17736       NamedDecl *ND = Result.getFoundDecl();
17737       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17738         Context.setBOOLDecl(TD);
17739     }
17740   }
17741   if (Context.getBOOLDecl())
17742     BoolT = Context.getBOOLType();
17743   return new (Context)
17744       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17745 }
17746 
17747 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17748     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17749     SourceLocation RParen) {
17750 
17751   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17752 
17753   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17754     return Spec.getPlatform() == Platform;
17755   });
17756 
17757   VersionTuple Version;
17758   if (Spec != AvailSpecs.end())
17759     Version = Spec->getVersion();
17760 
17761   // The use of `@available` in the enclosing function should be analyzed to
17762   // warn when it's used inappropriately (i.e. not if(@available)).
17763   if (getCurFunctionOrMethodDecl())
17764     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17765   else if (getCurBlock() || getCurLambda())
17766     getCurFunction()->HasPotentialAvailabilityViolations = true;
17767 
17768   return new (Context)
17769       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
17770 }
17771