1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/FixedPoint.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68 
69     // See if this is an aligned allocation/deallocation function that is
70     // unavailable.
71     if (TreatUnavailableAsInvalid &&
72         isUnavailableAlignedAllocationFunction(*FD))
73       return false;
74   }
75 
76   // See if this function is unavailable.
77   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
78       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
79     return false;
80 
81   return true;
82 }
83 
84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
85   // Warn if this is used but marked unused.
86   if (const auto *A = D->getAttr<UnusedAttr>()) {
87     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
88     // should diagnose them.
89     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
90         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
91       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
92       if (DC && !DC->hasAttr<UnusedAttr>())
93         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
94     }
95   }
96 }
97 
98 /// Emit a note explaining that this function is deleted.
99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
100   assert(Decl->isDeleted());
101 
102   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
103 
104   if (Method && Method->isDeleted() && Method->isDefaulted()) {
105     // If the method was explicitly defaulted, point at that declaration.
106     if (!Method->isImplicit())
107       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108 
109     // Try to diagnose why this special member function was implicitly
110     // deleted. This might fail, if that reason no longer applies.
111     CXXSpecialMember CSM = getSpecialMember(Method);
112     if (CSM != CXXInvalid)
113       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
114 
115     return;
116   }
117 
118   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119   if (Ctor && Ctor->isInheritingConstructor())
120     return NoteDeletedInheritingConstructor(Ctor);
121 
122   Diag(Decl->getLocation(), diag::note_availability_specified_here)
123     << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129   for (auto I : D->redecls()) {
130     if (I->getStorageClass() != SC_None)
131       return true;
132   }
133   return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145                                                       const NamedDecl *D,
146                                                       SourceLocation Loc) {
147   // This is disabled under C++; there are too many ways for this to fire in
148   // contexts where the warning is a false positive, or where it is technically
149   // correct but benign.
150   if (S.getLangOpts().CPlusPlus)
151     return;
152 
153   // Check if this is an inlined function or method.
154   FunctionDecl *Current = S.getCurFunctionDecl();
155   if (!Current)
156     return;
157   if (!Current->isInlined())
158     return;
159   if (!Current->isExternallyVisible())
160     return;
161 
162   // Check if the decl has internal linkage.
163   if (D->getFormalLinkage() != InternalLinkage)
164     return;
165 
166   // Downgrade from ExtWarn to Extension if
167   //  (1) the supposedly external inline function is in the main file,
168   //      and probably won't be included anywhere else.
169   //  (2) the thing we're referencing is a pure function.
170   //  (3) the thing we're referencing is another inline function.
171   // This last can give us false negatives, but it's better than warning on
172   // wrappers for simple C library functions.
173   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175   if (!DowngradeWarning && UsedFn)
176     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179                                : diag::ext_internal_in_extern_inline)
180     << /*IsVar=*/!UsedFn << D;
181 
182   S.MaybeSuggestAddingStaticToDecl(Current);
183 
184   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185       << D;
186 }
187 
188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189   const FunctionDecl *First = Cur->getFirstDecl();
190 
191   // Suggest "static" on the function, if possible.
192   if (!hasAnyExplicitStorageClass(First)) {
193     SourceLocation DeclBegin = First->getSourceRange().getBegin();
194     Diag(DeclBegin, diag::note_convert_inline_to_static)
195       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196   }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212                              const ObjCInterfaceDecl *UnknownObjCClass,
213                              bool ObjCPropertyAccess,
214                              bool AvoidPartialAvailabilityChecks,
215                              ObjCInterfaceDecl *ClassReceiver) {
216   SourceLocation Loc = Locs.front();
217   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218     // If there were any diagnostics suppressed by template argument deduction,
219     // emit them now.
220     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221     if (Pos != SuppressedDiagnostics.end()) {
222       for (const PartialDiagnosticAt &Suppressed : Pos->second)
223         Diag(Suppressed.first, Suppressed.second);
224 
225       // Clear out the list of suppressed diagnostics, so that we don't emit
226       // them again for this specialization. However, we don't obsolete this
227       // entry from the table, because we want to avoid ever emitting these
228       // diagnostics again.
229       Pos->second.clear();
230     }
231 
232     // C++ [basic.start.main]p3:
233     //   The function 'main' shall not be used within a program.
234     if (cast<FunctionDecl>(D)->isMain())
235       Diag(Loc, diag::ext_main_used);
236 
237     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238   }
239 
240   // See if this is an auto-typed variable whose initializer we are parsing.
241   if (ParsingInitForAutoVars.count(D)) {
242     if (isa<BindingDecl>(D)) {
243       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244         << D->getDeclName();
245     } else {
246       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247         << D->getDeclName() << cast<VarDecl>(D)->getType();
248     }
249     return true;
250   }
251 
252   // See if this is a deleted function.
253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254     if (FD->isDeleted()) {
255       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256       if (Ctor && Ctor->isInheritingConstructor())
257         Diag(Loc, diag::err_deleted_inherited_ctor_use)
258             << Ctor->getParent()
259             << Ctor->getInheritedConstructor().getConstructor()->getParent();
260       else
261         Diag(Loc, diag::err_deleted_function_use);
262       NoteDeletedFunction(FD);
263       return true;
264     }
265 
266     // If the function has a deduced return type, and we can't deduce it,
267     // then we can't use it either.
268     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
269         DeduceReturnType(FD, Loc))
270       return true;
271 
272     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
273       return true;
274   }
275 
276   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
277     // Lambdas are only default-constructible or assignable in C++2a onwards.
278     if (MD->getParent()->isLambda() &&
279         ((isa<CXXConstructorDecl>(MD) &&
280           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
281          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
282       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
283         << !isa<CXXConstructorDecl>(MD);
284     }
285   }
286 
287   auto getReferencedObjCProp = [](const NamedDecl *D) ->
288                                       const ObjCPropertyDecl * {
289     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
290       return MD->findPropertyDecl();
291     return nullptr;
292   };
293   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
294     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
295       return true;
296   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
297       return true;
298   }
299 
300   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
301   // Only the variables omp_in and omp_out are allowed in the combiner.
302   // Only the variables omp_priv and omp_orig are allowed in the
303   // initializer-clause.
304   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
305   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
306       isa<VarDecl>(D)) {
307     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
308         << getCurFunction()->HasOMPDeclareReductionCombiner;
309     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
310     return true;
311   }
312 
313   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
314   //  List-items in map clauses on this construct may only refer to the declared
315   //  variable var and entities that could be referenced by a procedure defined
316   //  at the same location
317   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
318   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
319       isa<VarDecl>(D)) {
320     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
321         << DMD->getVarName().getAsString();
322     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
323     return true;
324   }
325 
326   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
327                              AvoidPartialAvailabilityChecks, ClassReceiver);
328 
329   DiagnoseUnusedOfDecl(*this, D, Loc);
330 
331   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
332 
333   return false;
334 }
335 
336 /// DiagnoseSentinelCalls - This routine checks whether a call or
337 /// message-send is to a declaration with the sentinel attribute, and
338 /// if so, it checks that the requirements of the sentinel are
339 /// satisfied.
340 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
341                                  ArrayRef<Expr *> Args) {
342   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
343   if (!attr)
344     return;
345 
346   // The number of formal parameters of the declaration.
347   unsigned numFormalParams;
348 
349   // The kind of declaration.  This is also an index into a %select in
350   // the diagnostic.
351   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
352 
353   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
354     numFormalParams = MD->param_size();
355     calleeType = CT_Method;
356   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
357     numFormalParams = FD->param_size();
358     calleeType = CT_Function;
359   } else if (isa<VarDecl>(D)) {
360     QualType type = cast<ValueDecl>(D)->getType();
361     const FunctionType *fn = nullptr;
362     if (const PointerType *ptr = type->getAs<PointerType>()) {
363       fn = ptr->getPointeeType()->getAs<FunctionType>();
364       if (!fn) return;
365       calleeType = CT_Function;
366     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
367       fn = ptr->getPointeeType()->castAs<FunctionType>();
368       calleeType = CT_Block;
369     } else {
370       return;
371     }
372 
373     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
374       numFormalParams = proto->getNumParams();
375     } else {
376       numFormalParams = 0;
377     }
378   } else {
379     return;
380   }
381 
382   // "nullPos" is the number of formal parameters at the end which
383   // effectively count as part of the variadic arguments.  This is
384   // useful if you would prefer to not have *any* formal parameters,
385   // but the language forces you to have at least one.
386   unsigned nullPos = attr->getNullPos();
387   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
388   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
389 
390   // The number of arguments which should follow the sentinel.
391   unsigned numArgsAfterSentinel = attr->getSentinel();
392 
393   // If there aren't enough arguments for all the formal parameters,
394   // the sentinel, and the args after the sentinel, complain.
395   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
396     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
397     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
398     return;
399   }
400 
401   // Otherwise, find the sentinel expression.
402   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
403   if (!sentinelExpr) return;
404   if (sentinelExpr->isValueDependent()) return;
405   if (Context.isSentinelNullExpr(sentinelExpr)) return;
406 
407   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
408   // or 'NULL' if those are actually defined in the context.  Only use
409   // 'nil' for ObjC methods, where it's much more likely that the
410   // variadic arguments form a list of object pointers.
411   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
412   std::string NullValue;
413   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
414     NullValue = "nil";
415   else if (getLangOpts().CPlusPlus11)
416     NullValue = "nullptr";
417   else if (PP.isMacroDefined("NULL"))
418     NullValue = "NULL";
419   else
420     NullValue = "(void*) 0";
421 
422   if (MissingNilLoc.isInvalid())
423     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
424   else
425     Diag(MissingNilLoc, diag::warn_missing_sentinel)
426       << int(calleeType)
427       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
428   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429 }
430 
431 SourceRange Sema::getExprRange(Expr *E) const {
432   return E ? E->getSourceRange() : SourceRange();
433 }
434 
435 //===----------------------------------------------------------------------===//
436 //  Standard Promotions and Conversions
437 //===----------------------------------------------------------------------===//
438 
439 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
440 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
441   // Handle any placeholder expressions which made it here.
442   if (E->getType()->isPlaceholderType()) {
443     ExprResult result = CheckPlaceholderExpr(E);
444     if (result.isInvalid()) return ExprError();
445     E = result.get();
446   }
447 
448   QualType Ty = E->getType();
449   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
450 
451   if (Ty->isFunctionType()) {
452     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
453       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
454         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
455           return ExprError();
456 
457     E = ImpCastExprToType(E, Context.getPointerType(Ty),
458                           CK_FunctionToPointerDecay).get();
459   } else if (Ty->isArrayType()) {
460     // In C90 mode, arrays only promote to pointers if the array expression is
461     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
462     // type 'array of type' is converted to an expression that has type 'pointer
463     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
464     // that has type 'array of type' ...".  The relevant change is "an lvalue"
465     // (C90) to "an expression" (C99).
466     //
467     // C++ 4.2p1:
468     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
469     // T" can be converted to an rvalue of type "pointer to T".
470     //
471     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
472       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
473                             CK_ArrayToPointerDecay).get();
474   }
475   return E;
476 }
477 
478 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
479   // Check to see if we are dereferencing a null pointer.  If so,
480   // and if not volatile-qualified, this is undefined behavior that the
481   // optimizer will delete, so warn about it.  People sometimes try to use this
482   // to get a deterministic trap and are surprised by clang's behavior.  This
483   // only handles the pattern "*null", which is a very syntactic check.
484   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
485     if (UO->getOpcode() == UO_Deref &&
486         UO->getSubExpr()->IgnoreParenCasts()->
487           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
488         !UO->getType().isVolatileQualified()) {
489     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
490                           S.PDiag(diag::warn_indirection_through_null)
491                             << UO->getSubExpr()->getSourceRange());
492     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
493                         S.PDiag(diag::note_indirection_through_null));
494   }
495 }
496 
497 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
498                                     SourceLocation AssignLoc,
499                                     const Expr* RHS) {
500   const ObjCIvarDecl *IV = OIRE->getDecl();
501   if (!IV)
502     return;
503 
504   DeclarationName MemberName = IV->getDeclName();
505   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
506   if (!Member || !Member->isStr("isa"))
507     return;
508 
509   const Expr *Base = OIRE->getBase();
510   QualType BaseType = Base->getType();
511   if (OIRE->isArrow())
512     BaseType = BaseType->getPointeeType();
513   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
514     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
515       ObjCInterfaceDecl *ClassDeclared = nullptr;
516       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
517       if (!ClassDeclared->getSuperClass()
518           && (*ClassDeclared->ivar_begin()) == IV) {
519         if (RHS) {
520           NamedDecl *ObjectSetClass =
521             S.LookupSingleName(S.TUScope,
522                                &S.Context.Idents.get("object_setClass"),
523                                SourceLocation(), S.LookupOrdinaryName);
524           if (ObjectSetClass) {
525             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
526             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
527                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
528                                               "object_setClass(")
529                 << FixItHint::CreateReplacement(
530                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
531                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
532           }
533           else
534             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
535         } else {
536           NamedDecl *ObjectGetClass =
537             S.LookupSingleName(S.TUScope,
538                                &S.Context.Idents.get("object_getClass"),
539                                SourceLocation(), S.LookupOrdinaryName);
540           if (ObjectGetClass)
541             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
542                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
543                                               "object_getClass(")
544                 << FixItHint::CreateReplacement(
545                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
546           else
547             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
548         }
549         S.Diag(IV->getLocation(), diag::note_ivar_decl);
550       }
551     }
552 }
553 
554 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
555   // Handle any placeholder expressions which made it here.
556   if (E->getType()->isPlaceholderType()) {
557     ExprResult result = CheckPlaceholderExpr(E);
558     if (result.isInvalid()) return ExprError();
559     E = result.get();
560   }
561 
562   // C++ [conv.lval]p1:
563   //   A glvalue of a non-function, non-array type T can be
564   //   converted to a prvalue.
565   if (!E->isGLValue()) return E;
566 
567   QualType T = E->getType();
568   assert(!T.isNull() && "r-value conversion on typeless expression?");
569 
570   // We don't want to throw lvalue-to-rvalue casts on top of
571   // expressions of certain types in C++.
572   if (getLangOpts().CPlusPlus &&
573       (E->getType() == Context.OverloadTy ||
574        T->isDependentType() ||
575        T->isRecordType()))
576     return E;
577 
578   // The C standard is actually really unclear on this point, and
579   // DR106 tells us what the result should be but not why.  It's
580   // generally best to say that void types just doesn't undergo
581   // lvalue-to-rvalue at all.  Note that expressions of unqualified
582   // 'void' type are never l-values, but qualified void can be.
583   if (T->isVoidType())
584     return E;
585 
586   // OpenCL usually rejects direct accesses to values of 'half' type.
587   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
588       T->isHalfType()) {
589     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
590       << 0 << T;
591     return ExprError();
592   }
593 
594   CheckForNullPointerDereference(*this, E);
595   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
596     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
597                                      &Context.Idents.get("object_getClass"),
598                                      SourceLocation(), LookupOrdinaryName);
599     if (ObjectGetClass)
600       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
601           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
602           << FixItHint::CreateReplacement(
603                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
604     else
605       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
606   }
607   else if (const ObjCIvarRefExpr *OIRE =
608             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
609     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
610 
611   // C++ [conv.lval]p1:
612   //   [...] If T is a non-class type, the type of the prvalue is the
613   //   cv-unqualified version of T. Otherwise, the type of the
614   //   rvalue is T.
615   //
616   // C99 6.3.2.1p2:
617   //   If the lvalue has qualified type, the value has the unqualified
618   //   version of the type of the lvalue; otherwise, the value has the
619   //   type of the lvalue.
620   if (T.hasQualifiers())
621     T = T.getUnqualifiedType();
622 
623   // Under the MS ABI, lock down the inheritance model now.
624   if (T->isMemberPointerType() &&
625       Context.getTargetInfo().getCXXABI().isMicrosoft())
626     (void)isCompleteType(E->getExprLoc(), T);
627 
628   ExprResult Res = CheckLValueToRValueConversionOperand(E);
629   if (Res.isInvalid())
630     return Res;
631   E = Res.get();
632 
633   // Loading a __weak object implicitly retains the value, so we need a cleanup to
634   // balance that.
635   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
636     Cleanup.setExprNeedsCleanups(true);
637 
638   // C++ [conv.lval]p3:
639   //   If T is cv std::nullptr_t, the result is a null pointer constant.
640   CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
641   Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
642 
643   // C11 6.3.2.1p2:
644   //   ... if the lvalue has atomic type, the value has the non-atomic version
645   //   of the type of the lvalue ...
646   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
647     T = Atomic->getValueType().getUnqualifiedType();
648     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
649                                    nullptr, VK_RValue);
650   }
651 
652   return Res;
653 }
654 
655 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
656   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
657   if (Res.isInvalid())
658     return ExprError();
659   Res = DefaultLvalueConversion(Res.get());
660   if (Res.isInvalid())
661     return ExprError();
662   return Res;
663 }
664 
665 /// CallExprUnaryConversions - a special case of an unary conversion
666 /// performed on a function designator of a call expression.
667 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
668   QualType Ty = E->getType();
669   ExprResult Res = E;
670   // Only do implicit cast for a function type, but not for a pointer
671   // to function type.
672   if (Ty->isFunctionType()) {
673     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
674                             CK_FunctionToPointerDecay).get();
675     if (Res.isInvalid())
676       return ExprError();
677   }
678   Res = DefaultLvalueConversion(Res.get());
679   if (Res.isInvalid())
680     return ExprError();
681   return Res.get();
682 }
683 
684 /// UsualUnaryConversions - Performs various conversions that are common to most
685 /// operators (C99 6.3). The conversions of array and function types are
686 /// sometimes suppressed. For example, the array->pointer conversion doesn't
687 /// apply if the array is an argument to the sizeof or address (&) operators.
688 /// In these instances, this routine should *not* be called.
689 ExprResult Sema::UsualUnaryConversions(Expr *E) {
690   // First, convert to an r-value.
691   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
692   if (Res.isInvalid())
693     return ExprError();
694   E = Res.get();
695 
696   QualType Ty = E->getType();
697   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
698 
699   // Half FP have to be promoted to float unless it is natively supported
700   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
701     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
702 
703   // Try to perform integral promotions if the object has a theoretically
704   // promotable type.
705   if (Ty->isIntegralOrUnscopedEnumerationType()) {
706     // C99 6.3.1.1p2:
707     //
708     //   The following may be used in an expression wherever an int or
709     //   unsigned int may be used:
710     //     - an object or expression with an integer type whose integer
711     //       conversion rank is less than or equal to the rank of int
712     //       and unsigned int.
713     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
714     //
715     //   If an int can represent all values of the original type, the
716     //   value is converted to an int; otherwise, it is converted to an
717     //   unsigned int. These are called the integer promotions. All
718     //   other types are unchanged by the integer promotions.
719 
720     QualType PTy = Context.isPromotableBitField(E);
721     if (!PTy.isNull()) {
722       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
723       return E;
724     }
725     if (Ty->isPromotableIntegerType()) {
726       QualType PT = Context.getPromotedIntegerType(Ty);
727       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
728       return E;
729     }
730   }
731   return E;
732 }
733 
734 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
735 /// do not have a prototype. Arguments that have type float or __fp16
736 /// are promoted to double. All other argument types are converted by
737 /// UsualUnaryConversions().
738 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
739   QualType Ty = E->getType();
740   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
741 
742   ExprResult Res = UsualUnaryConversions(E);
743   if (Res.isInvalid())
744     return ExprError();
745   E = Res.get();
746 
747   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
748   // promote to double.
749   // Note that default argument promotion applies only to float (and
750   // half/fp16); it does not apply to _Float16.
751   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
752   if (BTy && (BTy->getKind() == BuiltinType::Half ||
753               BTy->getKind() == BuiltinType::Float)) {
754     if (getLangOpts().OpenCL &&
755         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
756         if (BTy->getKind() == BuiltinType::Half) {
757             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
758         }
759     } else {
760       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
761     }
762   }
763 
764   // C++ performs lvalue-to-rvalue conversion as a default argument
765   // promotion, even on class types, but note:
766   //   C++11 [conv.lval]p2:
767   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
768   //     operand or a subexpression thereof the value contained in the
769   //     referenced object is not accessed. Otherwise, if the glvalue
770   //     has a class type, the conversion copy-initializes a temporary
771   //     of type T from the glvalue and the result of the conversion
772   //     is a prvalue for the temporary.
773   // FIXME: add some way to gate this entire thing for correctness in
774   // potentially potentially evaluated contexts.
775   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
776     ExprResult Temp = PerformCopyInitialization(
777                        InitializedEntity::InitializeTemporary(E->getType()),
778                                                 E->getExprLoc(), E);
779     if (Temp.isInvalid())
780       return ExprError();
781     E = Temp.get();
782   }
783 
784   return E;
785 }
786 
787 /// Determine the degree of POD-ness for an expression.
788 /// Incomplete types are considered POD, since this check can be performed
789 /// when we're in an unevaluated context.
790 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
791   if (Ty->isIncompleteType()) {
792     // C++11 [expr.call]p7:
793     //   After these conversions, if the argument does not have arithmetic,
794     //   enumeration, pointer, pointer to member, or class type, the program
795     //   is ill-formed.
796     //
797     // Since we've already performed array-to-pointer and function-to-pointer
798     // decay, the only such type in C++ is cv void. This also handles
799     // initializer lists as variadic arguments.
800     if (Ty->isVoidType())
801       return VAK_Invalid;
802 
803     if (Ty->isObjCObjectType())
804       return VAK_Invalid;
805     return VAK_Valid;
806   }
807 
808   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
809     return VAK_Invalid;
810 
811   if (Ty.isCXX98PODType(Context))
812     return VAK_Valid;
813 
814   // C++11 [expr.call]p7:
815   //   Passing a potentially-evaluated argument of class type (Clause 9)
816   //   having a non-trivial copy constructor, a non-trivial move constructor,
817   //   or a non-trivial destructor, with no corresponding parameter,
818   //   is conditionally-supported with implementation-defined semantics.
819   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
820     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
821       if (!Record->hasNonTrivialCopyConstructor() &&
822           !Record->hasNonTrivialMoveConstructor() &&
823           !Record->hasNonTrivialDestructor())
824         return VAK_ValidInCXX11;
825 
826   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
827     return VAK_Valid;
828 
829   if (Ty->isObjCObjectType())
830     return VAK_Invalid;
831 
832   if (getLangOpts().MSVCCompat)
833     return VAK_MSVCUndefined;
834 
835   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
836   // permitted to reject them. We should consider doing so.
837   return VAK_Undefined;
838 }
839 
840 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
841   // Don't allow one to pass an Objective-C interface to a vararg.
842   const QualType &Ty = E->getType();
843   VarArgKind VAK = isValidVarArgType(Ty);
844 
845   // Complain about passing non-POD types through varargs.
846   switch (VAK) {
847   case VAK_ValidInCXX11:
848     DiagRuntimeBehavior(
849         E->getBeginLoc(), nullptr,
850         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
851     LLVM_FALLTHROUGH;
852   case VAK_Valid:
853     if (Ty->isRecordType()) {
854       // This is unlikely to be what the user intended. If the class has a
855       // 'c_str' member function, the user probably meant to call that.
856       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
857                           PDiag(diag::warn_pass_class_arg_to_vararg)
858                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
859     }
860     break;
861 
862   case VAK_Undefined:
863   case VAK_MSVCUndefined:
864     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
865                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
866                             << getLangOpts().CPlusPlus11 << Ty << CT);
867     break;
868 
869   case VAK_Invalid:
870     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
871       Diag(E->getBeginLoc(),
872            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
873           << Ty << CT;
874     else if (Ty->isObjCObjectType())
875       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
876                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
877                               << Ty << CT);
878     else
879       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
880           << isa<InitListExpr>(E) << Ty << CT;
881     break;
882   }
883 }
884 
885 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
886 /// will create a trap if the resulting type is not a POD type.
887 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
888                                                   FunctionDecl *FDecl) {
889   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
890     // Strip the unbridged-cast placeholder expression off, if applicable.
891     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
892         (CT == VariadicMethod ||
893          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
894       E = stripARCUnbridgedCast(E);
895 
896     // Otherwise, do normal placeholder checking.
897     } else {
898       ExprResult ExprRes = CheckPlaceholderExpr(E);
899       if (ExprRes.isInvalid())
900         return ExprError();
901       E = ExprRes.get();
902     }
903   }
904 
905   ExprResult ExprRes = DefaultArgumentPromotion(E);
906   if (ExprRes.isInvalid())
907     return ExprError();
908   E = ExprRes.get();
909 
910   // Diagnostics regarding non-POD argument types are
911   // emitted along with format string checking in Sema::CheckFunctionCall().
912   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
913     // Turn this into a trap.
914     CXXScopeSpec SS;
915     SourceLocation TemplateKWLoc;
916     UnqualifiedId Name;
917     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
918                        E->getBeginLoc());
919     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
920                                           /*HasTrailingLParen=*/true,
921                                           /*IsAddressOfOperand=*/false);
922     if (TrapFn.isInvalid())
923       return ExprError();
924 
925     ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
926                                     None, E->getEndLoc());
927     if (Call.isInvalid())
928       return ExprError();
929 
930     ExprResult Comma =
931         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
932     if (Comma.isInvalid())
933       return ExprError();
934     return Comma.get();
935   }
936 
937   if (!getLangOpts().CPlusPlus &&
938       RequireCompleteType(E->getExprLoc(), E->getType(),
939                           diag::err_call_incomplete_argument))
940     return ExprError();
941 
942   return E;
943 }
944 
945 /// Converts an integer to complex float type.  Helper function of
946 /// UsualArithmeticConversions()
947 ///
948 /// \return false if the integer expression is an integer type and is
949 /// successfully converted to the complex type.
950 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
951                                                   ExprResult &ComplexExpr,
952                                                   QualType IntTy,
953                                                   QualType ComplexTy,
954                                                   bool SkipCast) {
955   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
956   if (SkipCast) return false;
957   if (IntTy->isIntegerType()) {
958     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
959     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
960     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
961                                   CK_FloatingRealToComplex);
962   } else {
963     assert(IntTy->isComplexIntegerType());
964     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
965                                   CK_IntegralComplexToFloatingComplex);
966   }
967   return false;
968 }
969 
970 /// Handle arithmetic conversion with complex types.  Helper function of
971 /// UsualArithmeticConversions()
972 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
973                                              ExprResult &RHS, QualType LHSType,
974                                              QualType RHSType,
975                                              bool IsCompAssign) {
976   // if we have an integer operand, the result is the complex type.
977   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
978                                              /*skipCast*/false))
979     return LHSType;
980   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
981                                              /*skipCast*/IsCompAssign))
982     return RHSType;
983 
984   // This handles complex/complex, complex/float, or float/complex.
985   // When both operands are complex, the shorter operand is converted to the
986   // type of the longer, and that is the type of the result. This corresponds
987   // to what is done when combining two real floating-point operands.
988   // The fun begins when size promotion occur across type domains.
989   // From H&S 6.3.4: When one operand is complex and the other is a real
990   // floating-point type, the less precise type is converted, within it's
991   // real or complex domain, to the precision of the other type. For example,
992   // when combining a "long double" with a "double _Complex", the
993   // "double _Complex" is promoted to "long double _Complex".
994 
995   // Compute the rank of the two types, regardless of whether they are complex.
996   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
997 
998   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
999   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1000   QualType LHSElementType =
1001       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1002   QualType RHSElementType =
1003       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1004 
1005   QualType ResultType = S.Context.getComplexType(LHSElementType);
1006   if (Order < 0) {
1007     // Promote the precision of the LHS if not an assignment.
1008     ResultType = S.Context.getComplexType(RHSElementType);
1009     if (!IsCompAssign) {
1010       if (LHSComplexType)
1011         LHS =
1012             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1013       else
1014         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1015     }
1016   } else if (Order > 0) {
1017     // Promote the precision of the RHS.
1018     if (RHSComplexType)
1019       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1020     else
1021       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1022   }
1023   return ResultType;
1024 }
1025 
1026 /// Handle arithmetic conversion from integer to float.  Helper function
1027 /// of UsualArithmeticConversions()
1028 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1029                                            ExprResult &IntExpr,
1030                                            QualType FloatTy, QualType IntTy,
1031                                            bool ConvertFloat, bool ConvertInt) {
1032   if (IntTy->isIntegerType()) {
1033     if (ConvertInt)
1034       // Convert intExpr to the lhs floating point type.
1035       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1036                                     CK_IntegralToFloating);
1037     return FloatTy;
1038   }
1039 
1040   // Convert both sides to the appropriate complex float.
1041   assert(IntTy->isComplexIntegerType());
1042   QualType result = S.Context.getComplexType(FloatTy);
1043 
1044   // _Complex int -> _Complex float
1045   if (ConvertInt)
1046     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1047                                   CK_IntegralComplexToFloatingComplex);
1048 
1049   // float -> _Complex float
1050   if (ConvertFloat)
1051     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1052                                     CK_FloatingRealToComplex);
1053 
1054   return result;
1055 }
1056 
1057 /// Handle arithmethic conversion with floating point types.  Helper
1058 /// function of UsualArithmeticConversions()
1059 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1060                                       ExprResult &RHS, QualType LHSType,
1061                                       QualType RHSType, bool IsCompAssign) {
1062   bool LHSFloat = LHSType->isRealFloatingType();
1063   bool RHSFloat = RHSType->isRealFloatingType();
1064 
1065   // If we have two real floating types, convert the smaller operand
1066   // to the bigger result.
1067   if (LHSFloat && RHSFloat) {
1068     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1069     if (order > 0) {
1070       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1071       return LHSType;
1072     }
1073 
1074     assert(order < 0 && "illegal float comparison");
1075     if (!IsCompAssign)
1076       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1077     return RHSType;
1078   }
1079 
1080   if (LHSFloat) {
1081     // Half FP has to be promoted to float unless it is natively supported
1082     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1083       LHSType = S.Context.FloatTy;
1084 
1085     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1086                                       /*ConvertFloat=*/!IsCompAssign,
1087                                       /*ConvertInt=*/ true);
1088   }
1089   assert(RHSFloat);
1090   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1091                                     /*convertInt=*/ true,
1092                                     /*convertFloat=*/!IsCompAssign);
1093 }
1094 
1095 /// Diagnose attempts to convert between __float128 and long double if
1096 /// there is no support for such conversion. Helper function of
1097 /// UsualArithmeticConversions().
1098 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1099                                       QualType RHSType) {
1100   /*  No issue converting if at least one of the types is not a floating point
1101       type or the two types have the same rank.
1102   */
1103   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1104       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1105     return false;
1106 
1107   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1108          "The remaining types must be floating point types.");
1109 
1110   auto *LHSComplex = LHSType->getAs<ComplexType>();
1111   auto *RHSComplex = RHSType->getAs<ComplexType>();
1112 
1113   QualType LHSElemType = LHSComplex ?
1114     LHSComplex->getElementType() : LHSType;
1115   QualType RHSElemType = RHSComplex ?
1116     RHSComplex->getElementType() : RHSType;
1117 
1118   // No issue if the two types have the same representation
1119   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1120       &S.Context.getFloatTypeSemantics(RHSElemType))
1121     return false;
1122 
1123   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1124                                 RHSElemType == S.Context.LongDoubleTy);
1125   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1126                             RHSElemType == S.Context.Float128Ty);
1127 
1128   // We've handled the situation where __float128 and long double have the same
1129   // representation. We allow all conversions for all possible long double types
1130   // except PPC's double double.
1131   return Float128AndLongDouble &&
1132     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1133      &llvm::APFloat::PPCDoubleDouble());
1134 }
1135 
1136 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1137 
1138 namespace {
1139 /// These helper callbacks are placed in an anonymous namespace to
1140 /// permit their use as function template parameters.
1141 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1142   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1143 }
1144 
1145 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1146   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1147                              CK_IntegralComplexCast);
1148 }
1149 }
1150 
1151 /// Handle integer arithmetic conversions.  Helper function of
1152 /// UsualArithmeticConversions()
1153 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1154 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1155                                         ExprResult &RHS, QualType LHSType,
1156                                         QualType RHSType, bool IsCompAssign) {
1157   // The rules for this case are in C99 6.3.1.8
1158   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1159   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1160   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1161   if (LHSSigned == RHSSigned) {
1162     // Same signedness; use the higher-ranked type
1163     if (order >= 0) {
1164       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1165       return LHSType;
1166     } else if (!IsCompAssign)
1167       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1168     return RHSType;
1169   } else if (order != (LHSSigned ? 1 : -1)) {
1170     // The unsigned type has greater than or equal rank to the
1171     // signed type, so use the unsigned type
1172     if (RHSSigned) {
1173       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1174       return LHSType;
1175     } else if (!IsCompAssign)
1176       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1177     return RHSType;
1178   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1179     // The two types are different widths; if we are here, that
1180     // means the signed type is larger than the unsigned type, so
1181     // use the signed type.
1182     if (LHSSigned) {
1183       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1184       return LHSType;
1185     } else if (!IsCompAssign)
1186       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1187     return RHSType;
1188   } else {
1189     // The signed type is higher-ranked than the unsigned type,
1190     // but isn't actually any bigger (like unsigned int and long
1191     // on most 32-bit systems).  Use the unsigned type corresponding
1192     // to the signed type.
1193     QualType result =
1194       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1195     RHS = (*doRHSCast)(S, RHS.get(), result);
1196     if (!IsCompAssign)
1197       LHS = (*doLHSCast)(S, LHS.get(), result);
1198     return result;
1199   }
1200 }
1201 
1202 /// Handle conversions with GCC complex int extension.  Helper function
1203 /// of UsualArithmeticConversions()
1204 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1205                                            ExprResult &RHS, QualType LHSType,
1206                                            QualType RHSType,
1207                                            bool IsCompAssign) {
1208   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1209   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1210 
1211   if (LHSComplexInt && RHSComplexInt) {
1212     QualType LHSEltType = LHSComplexInt->getElementType();
1213     QualType RHSEltType = RHSComplexInt->getElementType();
1214     QualType ScalarType =
1215       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1216         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1217 
1218     return S.Context.getComplexType(ScalarType);
1219   }
1220 
1221   if (LHSComplexInt) {
1222     QualType LHSEltType = LHSComplexInt->getElementType();
1223     QualType ScalarType =
1224       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1225         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1226     QualType ComplexType = S.Context.getComplexType(ScalarType);
1227     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1228                               CK_IntegralRealToComplex);
1229 
1230     return ComplexType;
1231   }
1232 
1233   assert(RHSComplexInt);
1234 
1235   QualType RHSEltType = RHSComplexInt->getElementType();
1236   QualType ScalarType =
1237     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1238       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1239   QualType ComplexType = S.Context.getComplexType(ScalarType);
1240 
1241   if (!IsCompAssign)
1242     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1243                               CK_IntegralRealToComplex);
1244   return ComplexType;
1245 }
1246 
1247 /// Return the rank of a given fixed point or integer type. The value itself
1248 /// doesn't matter, but the values must be increasing with proper increasing
1249 /// rank as described in N1169 4.1.1.
1250 static unsigned GetFixedPointRank(QualType Ty) {
1251   const auto *BTy = Ty->getAs<BuiltinType>();
1252   assert(BTy && "Expected a builtin type.");
1253 
1254   switch (BTy->getKind()) {
1255   case BuiltinType::ShortFract:
1256   case BuiltinType::UShortFract:
1257   case BuiltinType::SatShortFract:
1258   case BuiltinType::SatUShortFract:
1259     return 1;
1260   case BuiltinType::Fract:
1261   case BuiltinType::UFract:
1262   case BuiltinType::SatFract:
1263   case BuiltinType::SatUFract:
1264     return 2;
1265   case BuiltinType::LongFract:
1266   case BuiltinType::ULongFract:
1267   case BuiltinType::SatLongFract:
1268   case BuiltinType::SatULongFract:
1269     return 3;
1270   case BuiltinType::ShortAccum:
1271   case BuiltinType::UShortAccum:
1272   case BuiltinType::SatShortAccum:
1273   case BuiltinType::SatUShortAccum:
1274     return 4;
1275   case BuiltinType::Accum:
1276   case BuiltinType::UAccum:
1277   case BuiltinType::SatAccum:
1278   case BuiltinType::SatUAccum:
1279     return 5;
1280   case BuiltinType::LongAccum:
1281   case BuiltinType::ULongAccum:
1282   case BuiltinType::SatLongAccum:
1283   case BuiltinType::SatULongAccum:
1284     return 6;
1285   default:
1286     if (BTy->isInteger())
1287       return 0;
1288     llvm_unreachable("Unexpected fixed point or integer type");
1289   }
1290 }
1291 
1292 /// handleFixedPointConversion - Fixed point operations between fixed
1293 /// point types and integers or other fixed point types do not fall under
1294 /// usual arithmetic conversion since these conversions could result in loss
1295 /// of precsision (N1169 4.1.4). These operations should be calculated with
1296 /// the full precision of their result type (N1169 4.1.6.2.1).
1297 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1298                                            QualType RHSTy) {
1299   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1300          "Expected at least one of the operands to be a fixed point type");
1301   assert((LHSTy->isFixedPointOrIntegerType() ||
1302           RHSTy->isFixedPointOrIntegerType()) &&
1303          "Special fixed point arithmetic operation conversions are only "
1304          "applied to ints or other fixed point types");
1305 
1306   // If one operand has signed fixed-point type and the other operand has
1307   // unsigned fixed-point type, then the unsigned fixed-point operand is
1308   // converted to its corresponding signed fixed-point type and the resulting
1309   // type is the type of the converted operand.
1310   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1311     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1312   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1313     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1314 
1315   // The result type is the type with the highest rank, whereby a fixed-point
1316   // conversion rank is always greater than an integer conversion rank; if the
1317   // type of either of the operands is a saturating fixedpoint type, the result
1318   // type shall be the saturating fixed-point type corresponding to the type
1319   // with the highest rank; the resulting value is converted (taking into
1320   // account rounding and overflow) to the precision of the resulting type.
1321   // Same ranks between signed and unsigned types are resolved earlier, so both
1322   // types are either signed or both unsigned at this point.
1323   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1324   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1325 
1326   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1327 
1328   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1329     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1330 
1331   return ResultTy;
1332 }
1333 
1334 /// UsualArithmeticConversions - Performs various conversions that are common to
1335 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1336 /// routine returns the first non-arithmetic type found. The client is
1337 /// responsible for emitting appropriate error diagnostics.
1338 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1339                                           bool IsCompAssign) {
1340   if (!IsCompAssign) {
1341     LHS = UsualUnaryConversions(LHS.get());
1342     if (LHS.isInvalid())
1343       return QualType();
1344   }
1345 
1346   RHS = UsualUnaryConversions(RHS.get());
1347   if (RHS.isInvalid())
1348     return QualType();
1349 
1350   // For conversion purposes, we ignore any qualifiers.
1351   // For example, "const float" and "float" are equivalent.
1352   QualType LHSType =
1353     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1354   QualType RHSType =
1355     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1356 
1357   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1358   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1359     LHSType = AtomicLHS->getValueType();
1360 
1361   // If both types are identical, no conversion is needed.
1362   if (LHSType == RHSType)
1363     return LHSType;
1364 
1365   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1366   // The caller can deal with this (e.g. pointer + int).
1367   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1368     return QualType();
1369 
1370   // Apply unary and bitfield promotions to the LHS's type.
1371   QualType LHSUnpromotedType = LHSType;
1372   if (LHSType->isPromotableIntegerType())
1373     LHSType = Context.getPromotedIntegerType(LHSType);
1374   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1375   if (!LHSBitfieldPromoteTy.isNull())
1376     LHSType = LHSBitfieldPromoteTy;
1377   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1378     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1379 
1380   // If both types are identical, no conversion is needed.
1381   if (LHSType == RHSType)
1382     return LHSType;
1383 
1384   // At this point, we have two different arithmetic types.
1385 
1386   // Diagnose attempts to convert between __float128 and long double where
1387   // such conversions currently can't be handled.
1388   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1389     return QualType();
1390 
1391   // Handle complex types first (C99 6.3.1.8p1).
1392   if (LHSType->isComplexType() || RHSType->isComplexType())
1393     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1394                                         IsCompAssign);
1395 
1396   // Now handle "real" floating types (i.e. float, double, long double).
1397   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1398     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1399                                  IsCompAssign);
1400 
1401   // Handle GCC complex int extension.
1402   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1403     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1404                                       IsCompAssign);
1405 
1406   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1407     return handleFixedPointConversion(*this, LHSType, RHSType);
1408 
1409   // Finally, we have two differing integer types.
1410   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1411            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1412 }
1413 
1414 //===----------------------------------------------------------------------===//
1415 //  Semantic Analysis for various Expression Types
1416 //===----------------------------------------------------------------------===//
1417 
1418 
1419 ExprResult
1420 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1421                                 SourceLocation DefaultLoc,
1422                                 SourceLocation RParenLoc,
1423                                 Expr *ControllingExpr,
1424                                 ArrayRef<ParsedType> ArgTypes,
1425                                 ArrayRef<Expr *> ArgExprs) {
1426   unsigned NumAssocs = ArgTypes.size();
1427   assert(NumAssocs == ArgExprs.size());
1428 
1429   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1430   for (unsigned i = 0; i < NumAssocs; ++i) {
1431     if (ArgTypes[i])
1432       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1433     else
1434       Types[i] = nullptr;
1435   }
1436 
1437   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1438                                              ControllingExpr,
1439                                              llvm::makeArrayRef(Types, NumAssocs),
1440                                              ArgExprs);
1441   delete [] Types;
1442   return ER;
1443 }
1444 
1445 ExprResult
1446 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1447                                  SourceLocation DefaultLoc,
1448                                  SourceLocation RParenLoc,
1449                                  Expr *ControllingExpr,
1450                                  ArrayRef<TypeSourceInfo *> Types,
1451                                  ArrayRef<Expr *> Exprs) {
1452   unsigned NumAssocs = Types.size();
1453   assert(NumAssocs == Exprs.size());
1454 
1455   // Decay and strip qualifiers for the controlling expression type, and handle
1456   // placeholder type replacement. See committee discussion from WG14 DR423.
1457   {
1458     EnterExpressionEvaluationContext Unevaluated(
1459         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1460     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1461     if (R.isInvalid())
1462       return ExprError();
1463     ControllingExpr = R.get();
1464   }
1465 
1466   // The controlling expression is an unevaluated operand, so side effects are
1467   // likely unintended.
1468   if (!inTemplateInstantiation() &&
1469       ControllingExpr->HasSideEffects(Context, false))
1470     Diag(ControllingExpr->getExprLoc(),
1471          diag::warn_side_effects_unevaluated_context);
1472 
1473   bool TypeErrorFound = false,
1474        IsResultDependent = ControllingExpr->isTypeDependent(),
1475        ContainsUnexpandedParameterPack
1476          = ControllingExpr->containsUnexpandedParameterPack();
1477 
1478   for (unsigned i = 0; i < NumAssocs; ++i) {
1479     if (Exprs[i]->containsUnexpandedParameterPack())
1480       ContainsUnexpandedParameterPack = true;
1481 
1482     if (Types[i]) {
1483       if (Types[i]->getType()->containsUnexpandedParameterPack())
1484         ContainsUnexpandedParameterPack = true;
1485 
1486       if (Types[i]->getType()->isDependentType()) {
1487         IsResultDependent = true;
1488       } else {
1489         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1490         // complete object type other than a variably modified type."
1491         unsigned D = 0;
1492         if (Types[i]->getType()->isIncompleteType())
1493           D = diag::err_assoc_type_incomplete;
1494         else if (!Types[i]->getType()->isObjectType())
1495           D = diag::err_assoc_type_nonobject;
1496         else if (Types[i]->getType()->isVariablyModifiedType())
1497           D = diag::err_assoc_type_variably_modified;
1498 
1499         if (D != 0) {
1500           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1501             << Types[i]->getTypeLoc().getSourceRange()
1502             << Types[i]->getType();
1503           TypeErrorFound = true;
1504         }
1505 
1506         // C11 6.5.1.1p2 "No two generic associations in the same generic
1507         // selection shall specify compatible types."
1508         for (unsigned j = i+1; j < NumAssocs; ++j)
1509           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1510               Context.typesAreCompatible(Types[i]->getType(),
1511                                          Types[j]->getType())) {
1512             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1513                  diag::err_assoc_compatible_types)
1514               << Types[j]->getTypeLoc().getSourceRange()
1515               << Types[j]->getType()
1516               << Types[i]->getType();
1517             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1518                  diag::note_compat_assoc)
1519               << Types[i]->getTypeLoc().getSourceRange()
1520               << Types[i]->getType();
1521             TypeErrorFound = true;
1522           }
1523       }
1524     }
1525   }
1526   if (TypeErrorFound)
1527     return ExprError();
1528 
1529   // If we determined that the generic selection is result-dependent, don't
1530   // try to compute the result expression.
1531   if (IsResultDependent)
1532     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1533                                         Exprs, DefaultLoc, RParenLoc,
1534                                         ContainsUnexpandedParameterPack);
1535 
1536   SmallVector<unsigned, 1> CompatIndices;
1537   unsigned DefaultIndex = -1U;
1538   for (unsigned i = 0; i < NumAssocs; ++i) {
1539     if (!Types[i])
1540       DefaultIndex = i;
1541     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1542                                         Types[i]->getType()))
1543       CompatIndices.push_back(i);
1544   }
1545 
1546   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1547   // type compatible with at most one of the types named in its generic
1548   // association list."
1549   if (CompatIndices.size() > 1) {
1550     // We strip parens here because the controlling expression is typically
1551     // parenthesized in macro definitions.
1552     ControllingExpr = ControllingExpr->IgnoreParens();
1553     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1554         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1555         << (unsigned)CompatIndices.size();
1556     for (unsigned I : CompatIndices) {
1557       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1558            diag::note_compat_assoc)
1559         << Types[I]->getTypeLoc().getSourceRange()
1560         << Types[I]->getType();
1561     }
1562     return ExprError();
1563   }
1564 
1565   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1566   // its controlling expression shall have type compatible with exactly one of
1567   // the types named in its generic association list."
1568   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1569     // We strip parens here because the controlling expression is typically
1570     // parenthesized in macro definitions.
1571     ControllingExpr = ControllingExpr->IgnoreParens();
1572     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1573         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1574     return ExprError();
1575   }
1576 
1577   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1578   // type name that is compatible with the type of the controlling expression,
1579   // then the result expression of the generic selection is the expression
1580   // in that generic association. Otherwise, the result expression of the
1581   // generic selection is the expression in the default generic association."
1582   unsigned ResultIndex =
1583     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1584 
1585   return GenericSelectionExpr::Create(
1586       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1587       ContainsUnexpandedParameterPack, ResultIndex);
1588 }
1589 
1590 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1591 /// location of the token and the offset of the ud-suffix within it.
1592 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1593                                      unsigned Offset) {
1594   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1595                                         S.getLangOpts());
1596 }
1597 
1598 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1599 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1600 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1601                                                  IdentifierInfo *UDSuffix,
1602                                                  SourceLocation UDSuffixLoc,
1603                                                  ArrayRef<Expr*> Args,
1604                                                  SourceLocation LitEndLoc) {
1605   assert(Args.size() <= 2 && "too many arguments for literal operator");
1606 
1607   QualType ArgTy[2];
1608   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1609     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1610     if (ArgTy[ArgIdx]->isArrayType())
1611       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1612   }
1613 
1614   DeclarationName OpName =
1615     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1616   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1617   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1618 
1619   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1620   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1621                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1622                               /*AllowStringTemplate*/ false,
1623                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1624     return ExprError();
1625 
1626   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1627 }
1628 
1629 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1630 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1631 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1632 /// multiple tokens.  However, the common case is that StringToks points to one
1633 /// string.
1634 ///
1635 ExprResult
1636 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1637   assert(!StringToks.empty() && "Must have at least one string!");
1638 
1639   StringLiteralParser Literal(StringToks, PP);
1640   if (Literal.hadError)
1641     return ExprError();
1642 
1643   SmallVector<SourceLocation, 4> StringTokLocs;
1644   for (const Token &Tok : StringToks)
1645     StringTokLocs.push_back(Tok.getLocation());
1646 
1647   QualType CharTy = Context.CharTy;
1648   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1649   if (Literal.isWide()) {
1650     CharTy = Context.getWideCharType();
1651     Kind = StringLiteral::Wide;
1652   } else if (Literal.isUTF8()) {
1653     if (getLangOpts().Char8)
1654       CharTy = Context.Char8Ty;
1655     Kind = StringLiteral::UTF8;
1656   } else if (Literal.isUTF16()) {
1657     CharTy = Context.Char16Ty;
1658     Kind = StringLiteral::UTF16;
1659   } else if (Literal.isUTF32()) {
1660     CharTy = Context.Char32Ty;
1661     Kind = StringLiteral::UTF32;
1662   } else if (Literal.isPascal()) {
1663     CharTy = Context.UnsignedCharTy;
1664   }
1665 
1666   // Warn on initializing an array of char from a u8 string literal; this
1667   // becomes ill-formed in C++2a.
1668   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1669       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1670     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1671 
1672     // Create removals for all 'u8' prefixes in the string literal(s). This
1673     // ensures C++2a compatibility (but may change the program behavior when
1674     // built by non-Clang compilers for which the execution character set is
1675     // not always UTF-8).
1676     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1677     SourceLocation RemovalDiagLoc;
1678     for (const Token &Tok : StringToks) {
1679       if (Tok.getKind() == tok::utf8_string_literal) {
1680         if (RemovalDiagLoc.isInvalid())
1681           RemovalDiagLoc = Tok.getLocation();
1682         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1683             Tok.getLocation(),
1684             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1685                                            getSourceManager(), getLangOpts())));
1686       }
1687     }
1688     Diag(RemovalDiagLoc, RemovalDiag);
1689   }
1690 
1691   QualType StrTy =
1692       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1693 
1694   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1695   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1696                                              Kind, Literal.Pascal, StrTy,
1697                                              &StringTokLocs[0],
1698                                              StringTokLocs.size());
1699   if (Literal.getUDSuffix().empty())
1700     return Lit;
1701 
1702   // We're building a user-defined literal.
1703   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1704   SourceLocation UDSuffixLoc =
1705     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1706                    Literal.getUDSuffixOffset());
1707 
1708   // Make sure we're allowed user-defined literals here.
1709   if (!UDLScope)
1710     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1711 
1712   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1713   //   operator "" X (str, len)
1714   QualType SizeType = Context.getSizeType();
1715 
1716   DeclarationName OpName =
1717     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1718   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1719   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1720 
1721   QualType ArgTy[] = {
1722     Context.getArrayDecayedType(StrTy), SizeType
1723   };
1724 
1725   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1726   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1727                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1728                                 /*AllowStringTemplate*/ true,
1729                                 /*DiagnoseMissing*/ true)) {
1730 
1731   case LOLR_Cooked: {
1732     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1733     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1734                                                     StringTokLocs[0]);
1735     Expr *Args[] = { Lit, LenArg };
1736 
1737     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1738   }
1739 
1740   case LOLR_StringTemplate: {
1741     TemplateArgumentListInfo ExplicitArgs;
1742 
1743     unsigned CharBits = Context.getIntWidth(CharTy);
1744     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1745     llvm::APSInt Value(CharBits, CharIsUnsigned);
1746 
1747     TemplateArgument TypeArg(CharTy);
1748     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1749     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1750 
1751     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1752       Value = Lit->getCodeUnit(I);
1753       TemplateArgument Arg(Context, Value, CharTy);
1754       TemplateArgumentLocInfo ArgInfo;
1755       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1756     }
1757     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1758                                     &ExplicitArgs);
1759   }
1760   case LOLR_Raw:
1761   case LOLR_Template:
1762   case LOLR_ErrorNoDiagnostic:
1763     llvm_unreachable("unexpected literal operator lookup result");
1764   case LOLR_Error:
1765     return ExprError();
1766   }
1767   llvm_unreachable("unexpected literal operator lookup result");
1768 }
1769 
1770 DeclRefExpr *
1771 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1772                        SourceLocation Loc,
1773                        const CXXScopeSpec *SS) {
1774   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1775   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1776 }
1777 
1778 DeclRefExpr *
1779 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1780                        const DeclarationNameInfo &NameInfo,
1781                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1782                        SourceLocation TemplateKWLoc,
1783                        const TemplateArgumentListInfo *TemplateArgs) {
1784   NestedNameSpecifierLoc NNS =
1785       SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1786   return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1787                           TemplateArgs);
1788 }
1789 
1790 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1791   // A declaration named in an unevaluated operand never constitutes an odr-use.
1792   if (isUnevaluatedContext())
1793     return NOUR_Unevaluated;
1794 
1795   // C++2a [basic.def.odr]p4:
1796   //   A variable x whose name appears as a potentially-evaluated expression e
1797   //   is odr-used by e unless [...] x is a reference that is usable in
1798   //   constant expressions.
1799   if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800     if (VD->getType()->isReferenceType() &&
1801         !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1802         VD->isUsableInConstantExpressions(Context))
1803       return NOUR_Constant;
1804   }
1805 
1806   // All remaining non-variable cases constitute an odr-use. For variables, we
1807   // need to wait and see how the expression is used.
1808   return NOUR_None;
1809 }
1810 
1811 /// BuildDeclRefExpr - Build an expression that references a
1812 /// declaration that does not require a closure capture.
1813 DeclRefExpr *
1814 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1815                        const DeclarationNameInfo &NameInfo,
1816                        NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1817                        SourceLocation TemplateKWLoc,
1818                        const TemplateArgumentListInfo *TemplateArgs) {
1819   bool RefersToCapturedVariable =
1820       isa<VarDecl>(D) &&
1821       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1822 
1823   DeclRefExpr *E = DeclRefExpr::Create(
1824       Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1825       VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1826   MarkDeclRefReferenced(E);
1827 
1828   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1829       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1830       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1831     getCurFunction()->recordUseOfWeak(E);
1832 
1833   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1834   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1835     FD = IFD->getAnonField();
1836   if (FD) {
1837     UnusedPrivateFields.remove(FD);
1838     // Just in case we're building an illegal pointer-to-member.
1839     if (FD->isBitField())
1840       E->setObjectKind(OK_BitField);
1841   }
1842 
1843   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1844   // designates a bit-field.
1845   if (auto *BD = dyn_cast<BindingDecl>(D))
1846     if (auto *BE = BD->getBinding())
1847       E->setObjectKind(BE->getObjectKind());
1848 
1849   return E;
1850 }
1851 
1852 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1853 /// possibly a list of template arguments.
1854 ///
1855 /// If this produces template arguments, it is permitted to call
1856 /// DecomposeTemplateName.
1857 ///
1858 /// This actually loses a lot of source location information for
1859 /// non-standard name kinds; we should consider preserving that in
1860 /// some way.
1861 void
1862 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1863                              TemplateArgumentListInfo &Buffer,
1864                              DeclarationNameInfo &NameInfo,
1865                              const TemplateArgumentListInfo *&TemplateArgs) {
1866   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1867     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1868     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1869 
1870     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1871                                        Id.TemplateId->NumArgs);
1872     translateTemplateArguments(TemplateArgsPtr, Buffer);
1873 
1874     TemplateName TName = Id.TemplateId->Template.get();
1875     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1876     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1877     TemplateArgs = &Buffer;
1878   } else {
1879     NameInfo = GetNameFromUnqualifiedId(Id);
1880     TemplateArgs = nullptr;
1881   }
1882 }
1883 
1884 static void emitEmptyLookupTypoDiagnostic(
1885     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1886     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1887     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1888   DeclContext *Ctx =
1889       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1890   if (!TC) {
1891     // Emit a special diagnostic for failed member lookups.
1892     // FIXME: computing the declaration context might fail here (?)
1893     if (Ctx)
1894       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1895                                                  << SS.getRange();
1896     else
1897       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1898     return;
1899   }
1900 
1901   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1902   bool DroppedSpecifier =
1903       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1904   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1905                         ? diag::note_implicit_param_decl
1906                         : diag::note_previous_decl;
1907   if (!Ctx)
1908     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1909                          SemaRef.PDiag(NoteID));
1910   else
1911     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1912                                  << Typo << Ctx << DroppedSpecifier
1913                                  << SS.getRange(),
1914                          SemaRef.PDiag(NoteID));
1915 }
1916 
1917 /// Diagnose an empty lookup.
1918 ///
1919 /// \return false if new lookup candidates were found
1920 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1921                                CorrectionCandidateCallback &CCC,
1922                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1923                                ArrayRef<Expr *> Args, TypoExpr **Out) {
1924   DeclarationName Name = R.getLookupName();
1925 
1926   unsigned diagnostic = diag::err_undeclared_var_use;
1927   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1928   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1929       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1930       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1931     diagnostic = diag::err_undeclared_use;
1932     diagnostic_suggest = diag::err_undeclared_use_suggest;
1933   }
1934 
1935   // If the original lookup was an unqualified lookup, fake an
1936   // unqualified lookup.  This is useful when (for example) the
1937   // original lookup would not have found something because it was a
1938   // dependent name.
1939   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1940   while (DC) {
1941     if (isa<CXXRecordDecl>(DC)) {
1942       LookupQualifiedName(R, DC);
1943 
1944       if (!R.empty()) {
1945         // Don't give errors about ambiguities in this lookup.
1946         R.suppressDiagnostics();
1947 
1948         // During a default argument instantiation the CurContext points
1949         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1950         // function parameter list, hence add an explicit check.
1951         bool isDefaultArgument =
1952             !CodeSynthesisContexts.empty() &&
1953             CodeSynthesisContexts.back().Kind ==
1954                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1955         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1956         bool isInstance = CurMethod &&
1957                           CurMethod->isInstance() &&
1958                           DC == CurMethod->getParent() && !isDefaultArgument;
1959 
1960         // Give a code modification hint to insert 'this->'.
1961         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1962         // Actually quite difficult!
1963         if (getLangOpts().MSVCCompat)
1964           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1965         if (isInstance) {
1966           Diag(R.getNameLoc(), diagnostic) << Name
1967             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1968           CheckCXXThisCapture(R.getNameLoc());
1969         } else {
1970           Diag(R.getNameLoc(), diagnostic) << Name;
1971         }
1972 
1973         // Do we really want to note all of these?
1974         for (NamedDecl *D : R)
1975           Diag(D->getLocation(), diag::note_dependent_var_use);
1976 
1977         // Return true if we are inside a default argument instantiation
1978         // and the found name refers to an instance member function, otherwise
1979         // the function calling DiagnoseEmptyLookup will try to create an
1980         // implicit member call and this is wrong for default argument.
1981         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1982           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1983           return true;
1984         }
1985 
1986         // Tell the callee to try to recover.
1987         return false;
1988       }
1989 
1990       R.clear();
1991     }
1992 
1993     DC = DC->getLookupParent();
1994   }
1995 
1996   // We didn't find anything, so try to correct for a typo.
1997   TypoCorrection Corrected;
1998   if (S && Out) {
1999     SourceLocation TypoLoc = R.getNameLoc();
2000     assert(!ExplicitTemplateArgs &&
2001            "Diagnosing an empty lookup with explicit template args!");
2002     *Out = CorrectTypoDelayed(
2003         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2004         [=](const TypoCorrection &TC) {
2005           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2006                                         diagnostic, diagnostic_suggest);
2007         },
2008         nullptr, CTK_ErrorRecovery);
2009     if (*Out)
2010       return true;
2011   } else if (S &&
2012              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2013                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2014     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2015     bool DroppedSpecifier =
2016         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2017     R.setLookupName(Corrected.getCorrection());
2018 
2019     bool AcceptableWithRecovery = false;
2020     bool AcceptableWithoutRecovery = false;
2021     NamedDecl *ND = Corrected.getFoundDecl();
2022     if (ND) {
2023       if (Corrected.isOverloaded()) {
2024         OverloadCandidateSet OCS(R.getNameLoc(),
2025                                  OverloadCandidateSet::CSK_Normal);
2026         OverloadCandidateSet::iterator Best;
2027         for (NamedDecl *CD : Corrected) {
2028           if (FunctionTemplateDecl *FTD =
2029                    dyn_cast<FunctionTemplateDecl>(CD))
2030             AddTemplateOverloadCandidate(
2031                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2032                 Args, OCS);
2033           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2034             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2035               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2036                                    Args, OCS);
2037         }
2038         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2039         case OR_Success:
2040           ND = Best->FoundDecl;
2041           Corrected.setCorrectionDecl(ND);
2042           break;
2043         default:
2044           // FIXME: Arbitrarily pick the first declaration for the note.
2045           Corrected.setCorrectionDecl(ND);
2046           break;
2047         }
2048       }
2049       R.addDecl(ND);
2050       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2051         CXXRecordDecl *Record = nullptr;
2052         if (Corrected.getCorrectionSpecifier()) {
2053           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2054           Record = Ty->getAsCXXRecordDecl();
2055         }
2056         if (!Record)
2057           Record = cast<CXXRecordDecl>(
2058               ND->getDeclContext()->getRedeclContext());
2059         R.setNamingClass(Record);
2060       }
2061 
2062       auto *UnderlyingND = ND->getUnderlyingDecl();
2063       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2064                                isa<FunctionTemplateDecl>(UnderlyingND);
2065       // FIXME: If we ended up with a typo for a type name or
2066       // Objective-C class name, we're in trouble because the parser
2067       // is in the wrong place to recover. Suggest the typo
2068       // correction, but don't make it a fix-it since we're not going
2069       // to recover well anyway.
2070       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2071                                   getAsTypeTemplateDecl(UnderlyingND) ||
2072                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2073     } else {
2074       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2075       // because we aren't able to recover.
2076       AcceptableWithoutRecovery = true;
2077     }
2078 
2079     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2080       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2081                             ? diag::note_implicit_param_decl
2082                             : diag::note_previous_decl;
2083       if (SS.isEmpty())
2084         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2085                      PDiag(NoteID), AcceptableWithRecovery);
2086       else
2087         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2088                                   << Name << computeDeclContext(SS, false)
2089                                   << DroppedSpecifier << SS.getRange(),
2090                      PDiag(NoteID), AcceptableWithRecovery);
2091 
2092       // Tell the callee whether to try to recover.
2093       return !AcceptableWithRecovery;
2094     }
2095   }
2096   R.clear();
2097 
2098   // Emit a special diagnostic for failed member lookups.
2099   // FIXME: computing the declaration context might fail here (?)
2100   if (!SS.isEmpty()) {
2101     Diag(R.getNameLoc(), diag::err_no_member)
2102       << Name << computeDeclContext(SS, false)
2103       << SS.getRange();
2104     return true;
2105   }
2106 
2107   // Give up, we can't recover.
2108   Diag(R.getNameLoc(), diagnostic) << Name;
2109   return true;
2110 }
2111 
2112 /// In Microsoft mode, if we are inside a template class whose parent class has
2113 /// dependent base classes, and we can't resolve an unqualified identifier, then
2114 /// assume the identifier is a member of a dependent base class.  We can only
2115 /// recover successfully in static methods, instance methods, and other contexts
2116 /// where 'this' is available.  This doesn't precisely match MSVC's
2117 /// instantiation model, but it's close enough.
2118 static Expr *
2119 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2120                                DeclarationNameInfo &NameInfo,
2121                                SourceLocation TemplateKWLoc,
2122                                const TemplateArgumentListInfo *TemplateArgs) {
2123   // Only try to recover from lookup into dependent bases in static methods or
2124   // contexts where 'this' is available.
2125   QualType ThisType = S.getCurrentThisType();
2126   const CXXRecordDecl *RD = nullptr;
2127   if (!ThisType.isNull())
2128     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2129   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2130     RD = MD->getParent();
2131   if (!RD || !RD->hasAnyDependentBases())
2132     return nullptr;
2133 
2134   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2135   // is available, suggest inserting 'this->' as a fixit.
2136   SourceLocation Loc = NameInfo.getLoc();
2137   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2138   DB << NameInfo.getName() << RD;
2139 
2140   if (!ThisType.isNull()) {
2141     DB << FixItHint::CreateInsertion(Loc, "this->");
2142     return CXXDependentScopeMemberExpr::Create(
2143         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2144         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2145         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2146   }
2147 
2148   // Synthesize a fake NNS that points to the derived class.  This will
2149   // perform name lookup during template instantiation.
2150   CXXScopeSpec SS;
2151   auto *NNS =
2152       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2153   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2154   return DependentScopeDeclRefExpr::Create(
2155       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2156       TemplateArgs);
2157 }
2158 
2159 ExprResult
2160 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2161                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2162                         bool HasTrailingLParen, bool IsAddressOfOperand,
2163                         CorrectionCandidateCallback *CCC,
2164                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2165   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2166          "cannot be direct & operand and have a trailing lparen");
2167   if (SS.isInvalid())
2168     return ExprError();
2169 
2170   TemplateArgumentListInfo TemplateArgsBuffer;
2171 
2172   // Decompose the UnqualifiedId into the following data.
2173   DeclarationNameInfo NameInfo;
2174   const TemplateArgumentListInfo *TemplateArgs;
2175   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2176 
2177   DeclarationName Name = NameInfo.getName();
2178   IdentifierInfo *II = Name.getAsIdentifierInfo();
2179   SourceLocation NameLoc = NameInfo.getLoc();
2180 
2181   if (II && II->isEditorPlaceholder()) {
2182     // FIXME: When typed placeholders are supported we can create a typed
2183     // placeholder expression node.
2184     return ExprError();
2185   }
2186 
2187   // C++ [temp.dep.expr]p3:
2188   //   An id-expression is type-dependent if it contains:
2189   //     -- an identifier that was declared with a dependent type,
2190   //        (note: handled after lookup)
2191   //     -- a template-id that is dependent,
2192   //        (note: handled in BuildTemplateIdExpr)
2193   //     -- a conversion-function-id that specifies a dependent type,
2194   //     -- a nested-name-specifier that contains a class-name that
2195   //        names a dependent type.
2196   // Determine whether this is a member of an unknown specialization;
2197   // we need to handle these differently.
2198   bool DependentID = false;
2199   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2200       Name.getCXXNameType()->isDependentType()) {
2201     DependentID = true;
2202   } else if (SS.isSet()) {
2203     if (DeclContext *DC = computeDeclContext(SS, false)) {
2204       if (RequireCompleteDeclContext(SS, DC))
2205         return ExprError();
2206     } else {
2207       DependentID = true;
2208     }
2209   }
2210 
2211   if (DependentID)
2212     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2213                                       IsAddressOfOperand, TemplateArgs);
2214 
2215   // Perform the required lookup.
2216   LookupResult R(*this, NameInfo,
2217                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2218                      ? LookupObjCImplicitSelfParam
2219                      : LookupOrdinaryName);
2220   if (TemplateKWLoc.isValid() || TemplateArgs) {
2221     // Lookup the template name again to correctly establish the context in
2222     // which it was found. This is really unfortunate as we already did the
2223     // lookup to determine that it was a template name in the first place. If
2224     // this becomes a performance hit, we can work harder to preserve those
2225     // results until we get here but it's likely not worth it.
2226     bool MemberOfUnknownSpecialization;
2227     AssumedTemplateKind AssumedTemplate;
2228     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2229                            MemberOfUnknownSpecialization, TemplateKWLoc,
2230                            &AssumedTemplate))
2231       return ExprError();
2232 
2233     if (MemberOfUnknownSpecialization ||
2234         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2235       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2236                                         IsAddressOfOperand, TemplateArgs);
2237   } else {
2238     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2239     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2240 
2241     // If the result might be in a dependent base class, this is a dependent
2242     // id-expression.
2243     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2244       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2245                                         IsAddressOfOperand, TemplateArgs);
2246 
2247     // If this reference is in an Objective-C method, then we need to do
2248     // some special Objective-C lookup, too.
2249     if (IvarLookupFollowUp) {
2250       ExprResult E(LookupInObjCMethod(R, S, II, true));
2251       if (E.isInvalid())
2252         return ExprError();
2253 
2254       if (Expr *Ex = E.getAs<Expr>())
2255         return Ex;
2256     }
2257   }
2258 
2259   if (R.isAmbiguous())
2260     return ExprError();
2261 
2262   // This could be an implicitly declared function reference (legal in C90,
2263   // extension in C99, forbidden in C++).
2264   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2265     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2266     if (D) R.addDecl(D);
2267   }
2268 
2269   // Determine whether this name might be a candidate for
2270   // argument-dependent lookup.
2271   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2272 
2273   if (R.empty() && !ADL) {
2274     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2275       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2276                                                    TemplateKWLoc, TemplateArgs))
2277         return E;
2278     }
2279 
2280     // Don't diagnose an empty lookup for inline assembly.
2281     if (IsInlineAsmIdentifier)
2282       return ExprError();
2283 
2284     // If this name wasn't predeclared and if this is not a function
2285     // call, diagnose the problem.
2286     TypoExpr *TE = nullptr;
2287     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2288                                                        : nullptr);
2289     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2290     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2291            "Typo correction callback misconfigured");
2292     if (CCC) {
2293       // Make sure the callback knows what the typo being diagnosed is.
2294       CCC->setTypoName(II);
2295       if (SS.isValid())
2296         CCC->setTypoNNS(SS.getScopeRep());
2297     }
2298     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2299     // a template name, but we happen to have always already looked up the name
2300     // before we get here if it must be a template name.
2301     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2302                             None, &TE)) {
2303       if (TE && KeywordReplacement) {
2304         auto &State = getTypoExprState(TE);
2305         auto BestTC = State.Consumer->getNextCorrection();
2306         if (BestTC.isKeyword()) {
2307           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2308           if (State.DiagHandler)
2309             State.DiagHandler(BestTC);
2310           KeywordReplacement->startToken();
2311           KeywordReplacement->setKind(II->getTokenID());
2312           KeywordReplacement->setIdentifierInfo(II);
2313           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2314           // Clean up the state associated with the TypoExpr, since it has
2315           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2316           clearDelayedTypo(TE);
2317           // Signal that a correction to a keyword was performed by returning a
2318           // valid-but-null ExprResult.
2319           return (Expr*)nullptr;
2320         }
2321         State.Consumer->resetCorrectionStream();
2322       }
2323       return TE ? TE : ExprError();
2324     }
2325 
2326     assert(!R.empty() &&
2327            "DiagnoseEmptyLookup returned false but added no results");
2328 
2329     // If we found an Objective-C instance variable, let
2330     // LookupInObjCMethod build the appropriate expression to
2331     // reference the ivar.
2332     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2333       R.clear();
2334       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2335       // In a hopelessly buggy code, Objective-C instance variable
2336       // lookup fails and no expression will be built to reference it.
2337       if (!E.isInvalid() && !E.get())
2338         return ExprError();
2339       return E;
2340     }
2341   }
2342 
2343   // This is guaranteed from this point on.
2344   assert(!R.empty() || ADL);
2345 
2346   // Check whether this might be a C++ implicit instance member access.
2347   // C++ [class.mfct.non-static]p3:
2348   //   When an id-expression that is not part of a class member access
2349   //   syntax and not used to form a pointer to member is used in the
2350   //   body of a non-static member function of class X, if name lookup
2351   //   resolves the name in the id-expression to a non-static non-type
2352   //   member of some class C, the id-expression is transformed into a
2353   //   class member access expression using (*this) as the
2354   //   postfix-expression to the left of the . operator.
2355   //
2356   // But we don't actually need to do this for '&' operands if R
2357   // resolved to a function or overloaded function set, because the
2358   // expression is ill-formed if it actually works out to be a
2359   // non-static member function:
2360   //
2361   // C++ [expr.ref]p4:
2362   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2363   //   [t]he expression can be used only as the left-hand operand of a
2364   //   member function call.
2365   //
2366   // There are other safeguards against such uses, but it's important
2367   // to get this right here so that we don't end up making a
2368   // spuriously dependent expression if we're inside a dependent
2369   // instance method.
2370   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2371     bool MightBeImplicitMember;
2372     if (!IsAddressOfOperand)
2373       MightBeImplicitMember = true;
2374     else if (!SS.isEmpty())
2375       MightBeImplicitMember = false;
2376     else if (R.isOverloadedResult())
2377       MightBeImplicitMember = false;
2378     else if (R.isUnresolvableResult())
2379       MightBeImplicitMember = true;
2380     else
2381       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2382                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2383                               isa<MSPropertyDecl>(R.getFoundDecl());
2384 
2385     if (MightBeImplicitMember)
2386       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2387                                              R, TemplateArgs, S);
2388   }
2389 
2390   if (TemplateArgs || TemplateKWLoc.isValid()) {
2391 
2392     // In C++1y, if this is a variable template id, then check it
2393     // in BuildTemplateIdExpr().
2394     // The single lookup result must be a variable template declaration.
2395     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2396         Id.TemplateId->Kind == TNK_Var_template) {
2397       assert(R.getAsSingle<VarTemplateDecl>() &&
2398              "There should only be one declaration found.");
2399     }
2400 
2401     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2402   }
2403 
2404   return BuildDeclarationNameExpr(SS, R, ADL);
2405 }
2406 
2407 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2408 /// declaration name, generally during template instantiation.
2409 /// There's a large number of things which don't need to be done along
2410 /// this path.
2411 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2412     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2413     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2414   DeclContext *DC = computeDeclContext(SS, false);
2415   if (!DC)
2416     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2417                                      NameInfo, /*TemplateArgs=*/nullptr);
2418 
2419   if (RequireCompleteDeclContext(SS, DC))
2420     return ExprError();
2421 
2422   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2423   LookupQualifiedName(R, DC);
2424 
2425   if (R.isAmbiguous())
2426     return ExprError();
2427 
2428   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2429     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2430                                      NameInfo, /*TemplateArgs=*/nullptr);
2431 
2432   if (R.empty()) {
2433     Diag(NameInfo.getLoc(), diag::err_no_member)
2434       << NameInfo.getName() << DC << SS.getRange();
2435     return ExprError();
2436   }
2437 
2438   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2439     // Diagnose a missing typename if this resolved unambiguously to a type in
2440     // a dependent context.  If we can recover with a type, downgrade this to
2441     // a warning in Microsoft compatibility mode.
2442     unsigned DiagID = diag::err_typename_missing;
2443     if (RecoveryTSI && getLangOpts().MSVCCompat)
2444       DiagID = diag::ext_typename_missing;
2445     SourceLocation Loc = SS.getBeginLoc();
2446     auto D = Diag(Loc, DiagID);
2447     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2448       << SourceRange(Loc, NameInfo.getEndLoc());
2449 
2450     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2451     // context.
2452     if (!RecoveryTSI)
2453       return ExprError();
2454 
2455     // Only issue the fixit if we're prepared to recover.
2456     D << FixItHint::CreateInsertion(Loc, "typename ");
2457 
2458     // Recover by pretending this was an elaborated type.
2459     QualType Ty = Context.getTypeDeclType(TD);
2460     TypeLocBuilder TLB;
2461     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2462 
2463     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2464     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2465     QTL.setElaboratedKeywordLoc(SourceLocation());
2466     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2467 
2468     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2469 
2470     return ExprEmpty();
2471   }
2472 
2473   // Defend against this resolving to an implicit member access. We usually
2474   // won't get here if this might be a legitimate a class member (we end up in
2475   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2476   // a pointer-to-member or in an unevaluated context in C++11.
2477   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2478     return BuildPossibleImplicitMemberExpr(SS,
2479                                            /*TemplateKWLoc=*/SourceLocation(),
2480                                            R, /*TemplateArgs=*/nullptr, S);
2481 
2482   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2483 }
2484 
2485 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2486 /// detected that we're currently inside an ObjC method.  Perform some
2487 /// additional lookup.
2488 ///
2489 /// Ideally, most of this would be done by lookup, but there's
2490 /// actually quite a lot of extra work involved.
2491 ///
2492 /// Returns a null sentinel to indicate trivial success.
2493 ExprResult
2494 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2495                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2496   SourceLocation Loc = Lookup.getNameLoc();
2497   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2498 
2499   // Check for error condition which is already reported.
2500   if (!CurMethod)
2501     return ExprError();
2502 
2503   // There are two cases to handle here.  1) scoped lookup could have failed,
2504   // in which case we should look for an ivar.  2) scoped lookup could have
2505   // found a decl, but that decl is outside the current instance method (i.e.
2506   // a global variable).  In these two cases, we do a lookup for an ivar with
2507   // this name, if the lookup sucedes, we replace it our current decl.
2508 
2509   // If we're in a class method, we don't normally want to look for
2510   // ivars.  But if we don't find anything else, and there's an
2511   // ivar, that's an error.
2512   bool IsClassMethod = CurMethod->isClassMethod();
2513 
2514   bool LookForIvars;
2515   if (Lookup.empty())
2516     LookForIvars = true;
2517   else if (IsClassMethod)
2518     LookForIvars = false;
2519   else
2520     LookForIvars = (Lookup.isSingleResult() &&
2521                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2522   ObjCInterfaceDecl *IFace = nullptr;
2523   if (LookForIvars) {
2524     IFace = CurMethod->getClassInterface();
2525     ObjCInterfaceDecl *ClassDeclared;
2526     ObjCIvarDecl *IV = nullptr;
2527     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2528       // Diagnose using an ivar in a class method.
2529       if (IsClassMethod)
2530         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2531                          << IV->getDeclName());
2532 
2533       // If we're referencing an invalid decl, just return this as a silent
2534       // error node.  The error diagnostic was already emitted on the decl.
2535       if (IV->isInvalidDecl())
2536         return ExprError();
2537 
2538       // Check if referencing a field with __attribute__((deprecated)).
2539       if (DiagnoseUseOfDecl(IV, Loc))
2540         return ExprError();
2541 
2542       // Diagnose the use of an ivar outside of the declaring class.
2543       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2544           !declaresSameEntity(ClassDeclared, IFace) &&
2545           !getLangOpts().DebuggerSupport)
2546         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2547 
2548       // FIXME: This should use a new expr for a direct reference, don't
2549       // turn this into Self->ivar, just return a BareIVarExpr or something.
2550       IdentifierInfo &II = Context.Idents.get("self");
2551       UnqualifiedId SelfName;
2552       SelfName.setIdentifier(&II, SourceLocation());
2553       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2554       CXXScopeSpec SelfScopeSpec;
2555       SourceLocation TemplateKWLoc;
2556       ExprResult SelfExpr =
2557           ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2558                             /*HasTrailingLParen=*/false,
2559                             /*IsAddressOfOperand=*/false);
2560       if (SelfExpr.isInvalid())
2561         return ExprError();
2562 
2563       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2564       if (SelfExpr.isInvalid())
2565         return ExprError();
2566 
2567       MarkAnyDeclReferenced(Loc, IV, true);
2568 
2569       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2570       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2571           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2572         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2573 
2574       ObjCIvarRefExpr *Result = new (Context)
2575           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2576                           IV->getLocation(), SelfExpr.get(), true, true);
2577 
2578       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2579         if (!isUnevaluatedContext() &&
2580             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2581           getCurFunction()->recordUseOfWeak(Result);
2582       }
2583       if (getLangOpts().ObjCAutoRefCount)
2584         if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2585           ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2586 
2587       return Result;
2588     }
2589   } else if (CurMethod->isInstanceMethod()) {
2590     // We should warn if a local variable hides an ivar.
2591     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2592       ObjCInterfaceDecl *ClassDeclared;
2593       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2594         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2595             declaresSameEntity(IFace, ClassDeclared))
2596           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2597       }
2598     }
2599   } else if (Lookup.isSingleResult() &&
2600              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2601     // If accessing a stand-alone ivar in a class method, this is an error.
2602     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2603       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2604                        << IV->getDeclName());
2605   }
2606 
2607   if (Lookup.empty() && II && AllowBuiltinCreation) {
2608     // FIXME. Consolidate this with similar code in LookupName.
2609     if (unsigned BuiltinID = II->getBuiltinID()) {
2610       if (!(getLangOpts().CPlusPlus &&
2611             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2612         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2613                                            S, Lookup.isForRedeclaration(),
2614                                            Lookup.getNameLoc());
2615         if (D) Lookup.addDecl(D);
2616       }
2617     }
2618   }
2619   // Sentinel value saying that we didn't do anything special.
2620   return ExprResult((Expr *)nullptr);
2621 }
2622 
2623 /// Cast a base object to a member's actual type.
2624 ///
2625 /// Logically this happens in three phases:
2626 ///
2627 /// * First we cast from the base type to the naming class.
2628 ///   The naming class is the class into which we were looking
2629 ///   when we found the member;  it's the qualifier type if a
2630 ///   qualifier was provided, and otherwise it's the base type.
2631 ///
2632 /// * Next we cast from the naming class to the declaring class.
2633 ///   If the member we found was brought into a class's scope by
2634 ///   a using declaration, this is that class;  otherwise it's
2635 ///   the class declaring the member.
2636 ///
2637 /// * Finally we cast from the declaring class to the "true"
2638 ///   declaring class of the member.  This conversion does not
2639 ///   obey access control.
2640 ExprResult
2641 Sema::PerformObjectMemberConversion(Expr *From,
2642                                     NestedNameSpecifier *Qualifier,
2643                                     NamedDecl *FoundDecl,
2644                                     NamedDecl *Member) {
2645   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2646   if (!RD)
2647     return From;
2648 
2649   QualType DestRecordType;
2650   QualType DestType;
2651   QualType FromRecordType;
2652   QualType FromType = From->getType();
2653   bool PointerConversions = false;
2654   if (isa<FieldDecl>(Member)) {
2655     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2656     auto FromPtrType = FromType->getAs<PointerType>();
2657     DestRecordType = Context.getAddrSpaceQualType(
2658         DestRecordType, FromPtrType
2659                             ? FromType->getPointeeType().getAddressSpace()
2660                             : FromType.getAddressSpace());
2661 
2662     if (FromPtrType) {
2663       DestType = Context.getPointerType(DestRecordType);
2664       FromRecordType = FromPtrType->getPointeeType();
2665       PointerConversions = true;
2666     } else {
2667       DestType = DestRecordType;
2668       FromRecordType = FromType;
2669     }
2670   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2671     if (Method->isStatic())
2672       return From;
2673 
2674     DestType = Method->getThisType();
2675     DestRecordType = DestType->getPointeeType();
2676 
2677     if (FromType->getAs<PointerType>()) {
2678       FromRecordType = FromType->getPointeeType();
2679       PointerConversions = true;
2680     } else {
2681       FromRecordType = FromType;
2682       DestType = DestRecordType;
2683     }
2684   } else {
2685     // No conversion necessary.
2686     return From;
2687   }
2688 
2689   if (DestType->isDependentType() || FromType->isDependentType())
2690     return From;
2691 
2692   // If the unqualified types are the same, no conversion is necessary.
2693   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2694     return From;
2695 
2696   SourceRange FromRange = From->getSourceRange();
2697   SourceLocation FromLoc = FromRange.getBegin();
2698 
2699   ExprValueKind VK = From->getValueKind();
2700 
2701   // C++ [class.member.lookup]p8:
2702   //   [...] Ambiguities can often be resolved by qualifying a name with its
2703   //   class name.
2704   //
2705   // If the member was a qualified name and the qualified referred to a
2706   // specific base subobject type, we'll cast to that intermediate type
2707   // first and then to the object in which the member is declared. That allows
2708   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2709   //
2710   //   class Base { public: int x; };
2711   //   class Derived1 : public Base { };
2712   //   class Derived2 : public Base { };
2713   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2714   //
2715   //   void VeryDerived::f() {
2716   //     x = 17; // error: ambiguous base subobjects
2717   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2718   //   }
2719   if (Qualifier && Qualifier->getAsType()) {
2720     QualType QType = QualType(Qualifier->getAsType(), 0);
2721     assert(QType->isRecordType() && "lookup done with non-record type");
2722 
2723     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2724 
2725     // In C++98, the qualifier type doesn't actually have to be a base
2726     // type of the object type, in which case we just ignore it.
2727     // Otherwise build the appropriate casts.
2728     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2729       CXXCastPath BasePath;
2730       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2731                                        FromLoc, FromRange, &BasePath))
2732         return ExprError();
2733 
2734       if (PointerConversions)
2735         QType = Context.getPointerType(QType);
2736       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2737                                VK, &BasePath).get();
2738 
2739       FromType = QType;
2740       FromRecordType = QRecordType;
2741 
2742       // If the qualifier type was the same as the destination type,
2743       // we're done.
2744       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2745         return From;
2746     }
2747   }
2748 
2749   bool IgnoreAccess = false;
2750 
2751   // If we actually found the member through a using declaration, cast
2752   // down to the using declaration's type.
2753   //
2754   // Pointer equality is fine here because only one declaration of a
2755   // class ever has member declarations.
2756   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2757     assert(isa<UsingShadowDecl>(FoundDecl));
2758     QualType URecordType = Context.getTypeDeclType(
2759                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2760 
2761     // We only need to do this if the naming-class to declaring-class
2762     // conversion is non-trivial.
2763     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2764       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2765       CXXCastPath BasePath;
2766       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2767                                        FromLoc, FromRange, &BasePath))
2768         return ExprError();
2769 
2770       QualType UType = URecordType;
2771       if (PointerConversions)
2772         UType = Context.getPointerType(UType);
2773       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2774                                VK, &BasePath).get();
2775       FromType = UType;
2776       FromRecordType = URecordType;
2777     }
2778 
2779     // We don't do access control for the conversion from the
2780     // declaring class to the true declaring class.
2781     IgnoreAccess = true;
2782   }
2783 
2784   CXXCastPath BasePath;
2785   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2786                                    FromLoc, FromRange, &BasePath,
2787                                    IgnoreAccess))
2788     return ExprError();
2789 
2790   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2791                            VK, &BasePath);
2792 }
2793 
2794 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2795                                       const LookupResult &R,
2796                                       bool HasTrailingLParen) {
2797   // Only when used directly as the postfix-expression of a call.
2798   if (!HasTrailingLParen)
2799     return false;
2800 
2801   // Never if a scope specifier was provided.
2802   if (SS.isSet())
2803     return false;
2804 
2805   // Only in C++ or ObjC++.
2806   if (!getLangOpts().CPlusPlus)
2807     return false;
2808 
2809   // Turn off ADL when we find certain kinds of declarations during
2810   // normal lookup:
2811   for (NamedDecl *D : R) {
2812     // C++0x [basic.lookup.argdep]p3:
2813     //     -- a declaration of a class member
2814     // Since using decls preserve this property, we check this on the
2815     // original decl.
2816     if (D->isCXXClassMember())
2817       return false;
2818 
2819     // C++0x [basic.lookup.argdep]p3:
2820     //     -- a block-scope function declaration that is not a
2821     //        using-declaration
2822     // NOTE: we also trigger this for function templates (in fact, we
2823     // don't check the decl type at all, since all other decl types
2824     // turn off ADL anyway).
2825     if (isa<UsingShadowDecl>(D))
2826       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2827     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2828       return false;
2829 
2830     // C++0x [basic.lookup.argdep]p3:
2831     //     -- a declaration that is neither a function or a function
2832     //        template
2833     // And also for builtin functions.
2834     if (isa<FunctionDecl>(D)) {
2835       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2836 
2837       // But also builtin functions.
2838       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2839         return false;
2840     } else if (!isa<FunctionTemplateDecl>(D))
2841       return false;
2842   }
2843 
2844   return true;
2845 }
2846 
2847 
2848 /// Diagnoses obvious problems with the use of the given declaration
2849 /// as an expression.  This is only actually called for lookups that
2850 /// were not overloaded, and it doesn't promise that the declaration
2851 /// will in fact be used.
2852 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2853   if (D->isInvalidDecl())
2854     return true;
2855 
2856   if (isa<TypedefNameDecl>(D)) {
2857     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2858     return true;
2859   }
2860 
2861   if (isa<ObjCInterfaceDecl>(D)) {
2862     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2863     return true;
2864   }
2865 
2866   if (isa<NamespaceDecl>(D)) {
2867     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2868     return true;
2869   }
2870 
2871   return false;
2872 }
2873 
2874 // Certain multiversion types should be treated as overloaded even when there is
2875 // only one result.
2876 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2877   assert(R.isSingleResult() && "Expected only a single result");
2878   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2879   return FD &&
2880          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2881 }
2882 
2883 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2884                                           LookupResult &R, bool NeedsADL,
2885                                           bool AcceptInvalidDecl) {
2886   // If this is a single, fully-resolved result and we don't need ADL,
2887   // just build an ordinary singleton decl ref.
2888   if (!NeedsADL && R.isSingleResult() &&
2889       !R.getAsSingle<FunctionTemplateDecl>() &&
2890       !ShouldLookupResultBeMultiVersionOverload(R))
2891     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2892                                     R.getRepresentativeDecl(), nullptr,
2893                                     AcceptInvalidDecl);
2894 
2895   // We only need to check the declaration if there's exactly one
2896   // result, because in the overloaded case the results can only be
2897   // functions and function templates.
2898   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2899       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2900     return ExprError();
2901 
2902   // Otherwise, just build an unresolved lookup expression.  Suppress
2903   // any lookup-related diagnostics; we'll hash these out later, when
2904   // we've picked a target.
2905   R.suppressDiagnostics();
2906 
2907   UnresolvedLookupExpr *ULE
2908     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2909                                    SS.getWithLocInContext(Context),
2910                                    R.getLookupNameInfo(),
2911                                    NeedsADL, R.isOverloadedResult(),
2912                                    R.begin(), R.end());
2913 
2914   return ULE;
2915 }
2916 
2917 static void
2918 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2919                                    ValueDecl *var, DeclContext *DC);
2920 
2921 /// Complete semantic analysis for a reference to the given declaration.
2922 ExprResult Sema::BuildDeclarationNameExpr(
2923     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2924     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2925     bool AcceptInvalidDecl) {
2926   assert(D && "Cannot refer to a NULL declaration");
2927   assert(!isa<FunctionTemplateDecl>(D) &&
2928          "Cannot refer unambiguously to a function template");
2929 
2930   SourceLocation Loc = NameInfo.getLoc();
2931   if (CheckDeclInExpr(*this, Loc, D))
2932     return ExprError();
2933 
2934   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2935     // Specifically diagnose references to class templates that are missing
2936     // a template argument list.
2937     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2938     return ExprError();
2939   }
2940 
2941   // Make sure that we're referring to a value.
2942   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2943   if (!VD) {
2944     Diag(Loc, diag::err_ref_non_value)
2945       << D << SS.getRange();
2946     Diag(D->getLocation(), diag::note_declared_at);
2947     return ExprError();
2948   }
2949 
2950   // Check whether this declaration can be used. Note that we suppress
2951   // this check when we're going to perform argument-dependent lookup
2952   // on this function name, because this might not be the function
2953   // that overload resolution actually selects.
2954   if (DiagnoseUseOfDecl(VD, Loc))
2955     return ExprError();
2956 
2957   // Only create DeclRefExpr's for valid Decl's.
2958   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2959     return ExprError();
2960 
2961   // Handle members of anonymous structs and unions.  If we got here,
2962   // and the reference is to a class member indirect field, then this
2963   // must be the subject of a pointer-to-member expression.
2964   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2965     if (!indirectField->isCXXClassMember())
2966       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2967                                                       indirectField);
2968 
2969   {
2970     QualType type = VD->getType();
2971     if (type.isNull())
2972       return ExprError();
2973     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2974       // C++ [except.spec]p17:
2975       //   An exception-specification is considered to be needed when:
2976       //   - in an expression, the function is the unique lookup result or
2977       //     the selected member of a set of overloaded functions.
2978       ResolveExceptionSpec(Loc, FPT);
2979       type = VD->getType();
2980     }
2981     ExprValueKind valueKind = VK_RValue;
2982 
2983     switch (D->getKind()) {
2984     // Ignore all the non-ValueDecl kinds.
2985 #define ABSTRACT_DECL(kind)
2986 #define VALUE(type, base)
2987 #define DECL(type, base) \
2988     case Decl::type:
2989 #include "clang/AST/DeclNodes.inc"
2990       llvm_unreachable("invalid value decl kind");
2991 
2992     // These shouldn't make it here.
2993     case Decl::ObjCAtDefsField:
2994       llvm_unreachable("forming non-member reference to ivar?");
2995 
2996     // Enum constants are always r-values and never references.
2997     // Unresolved using declarations are dependent.
2998     case Decl::EnumConstant:
2999     case Decl::UnresolvedUsingValue:
3000     case Decl::OMPDeclareReduction:
3001     case Decl::OMPDeclareMapper:
3002       valueKind = VK_RValue;
3003       break;
3004 
3005     // Fields and indirect fields that got here must be for
3006     // pointer-to-member expressions; we just call them l-values for
3007     // internal consistency, because this subexpression doesn't really
3008     // exist in the high-level semantics.
3009     case Decl::Field:
3010     case Decl::IndirectField:
3011     case Decl::ObjCIvar:
3012       assert(getLangOpts().CPlusPlus &&
3013              "building reference to field in C?");
3014 
3015       // These can't have reference type in well-formed programs, but
3016       // for internal consistency we do this anyway.
3017       type = type.getNonReferenceType();
3018       valueKind = VK_LValue;
3019       break;
3020 
3021     // Non-type template parameters are either l-values or r-values
3022     // depending on the type.
3023     case Decl::NonTypeTemplateParm: {
3024       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3025         type = reftype->getPointeeType();
3026         valueKind = VK_LValue; // even if the parameter is an r-value reference
3027         break;
3028       }
3029 
3030       // For non-references, we need to strip qualifiers just in case
3031       // the template parameter was declared as 'const int' or whatever.
3032       valueKind = VK_RValue;
3033       type = type.getUnqualifiedType();
3034       break;
3035     }
3036 
3037     case Decl::Var:
3038     case Decl::VarTemplateSpecialization:
3039     case Decl::VarTemplatePartialSpecialization:
3040     case Decl::Decomposition:
3041     case Decl::OMPCapturedExpr:
3042       // In C, "extern void blah;" is valid and is an r-value.
3043       if (!getLangOpts().CPlusPlus &&
3044           !type.hasQualifiers() &&
3045           type->isVoidType()) {
3046         valueKind = VK_RValue;
3047         break;
3048       }
3049       LLVM_FALLTHROUGH;
3050 
3051     case Decl::ImplicitParam:
3052     case Decl::ParmVar: {
3053       // These are always l-values.
3054       valueKind = VK_LValue;
3055       type = type.getNonReferenceType();
3056 
3057       // FIXME: Does the addition of const really only apply in
3058       // potentially-evaluated contexts? Since the variable isn't actually
3059       // captured in an unevaluated context, it seems that the answer is no.
3060       if (!isUnevaluatedContext()) {
3061         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3062         if (!CapturedType.isNull())
3063           type = CapturedType;
3064       }
3065 
3066       break;
3067     }
3068 
3069     case Decl::Binding: {
3070       // These are always lvalues.
3071       valueKind = VK_LValue;
3072       type = type.getNonReferenceType();
3073       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3074       // decides how that's supposed to work.
3075       auto *BD = cast<BindingDecl>(VD);
3076       if (BD->getDeclContext() != CurContext) {
3077         auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3078         if (DD && DD->hasLocalStorage())
3079           diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3080       }
3081       break;
3082     }
3083 
3084     case Decl::Function: {
3085       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3086         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3087           type = Context.BuiltinFnTy;
3088           valueKind = VK_RValue;
3089           break;
3090         }
3091       }
3092 
3093       const FunctionType *fty = type->castAs<FunctionType>();
3094 
3095       // If we're referring to a function with an __unknown_anytype
3096       // result type, make the entire expression __unknown_anytype.
3097       if (fty->getReturnType() == Context.UnknownAnyTy) {
3098         type = Context.UnknownAnyTy;
3099         valueKind = VK_RValue;
3100         break;
3101       }
3102 
3103       // Functions are l-values in C++.
3104       if (getLangOpts().CPlusPlus) {
3105         valueKind = VK_LValue;
3106         break;
3107       }
3108 
3109       // C99 DR 316 says that, if a function type comes from a
3110       // function definition (without a prototype), that type is only
3111       // used for checking compatibility. Therefore, when referencing
3112       // the function, we pretend that we don't have the full function
3113       // type.
3114       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3115           isa<FunctionProtoType>(fty))
3116         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3117                                               fty->getExtInfo());
3118 
3119       // Functions are r-values in C.
3120       valueKind = VK_RValue;
3121       break;
3122     }
3123 
3124     case Decl::CXXDeductionGuide:
3125       llvm_unreachable("building reference to deduction guide");
3126 
3127     case Decl::MSProperty:
3128       valueKind = VK_LValue;
3129       break;
3130 
3131     case Decl::CXXMethod:
3132       // If we're referring to a method with an __unknown_anytype
3133       // result type, make the entire expression __unknown_anytype.
3134       // This should only be possible with a type written directly.
3135       if (const FunctionProtoType *proto
3136             = dyn_cast<FunctionProtoType>(VD->getType()))
3137         if (proto->getReturnType() == Context.UnknownAnyTy) {
3138           type = Context.UnknownAnyTy;
3139           valueKind = VK_RValue;
3140           break;
3141         }
3142 
3143       // C++ methods are l-values if static, r-values if non-static.
3144       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3145         valueKind = VK_LValue;
3146         break;
3147       }
3148       LLVM_FALLTHROUGH;
3149 
3150     case Decl::CXXConversion:
3151     case Decl::CXXDestructor:
3152     case Decl::CXXConstructor:
3153       valueKind = VK_RValue;
3154       break;
3155     }
3156 
3157     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3158                             /*FIXME: TemplateKWLoc*/ SourceLocation(),
3159                             TemplateArgs);
3160   }
3161 }
3162 
3163 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3164                                     SmallString<32> &Target) {
3165   Target.resize(CharByteWidth * (Source.size() + 1));
3166   char *ResultPtr = &Target[0];
3167   const llvm::UTF8 *ErrorPtr;
3168   bool success =
3169       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3170   (void)success;
3171   assert(success);
3172   Target.resize(ResultPtr - &Target[0]);
3173 }
3174 
3175 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3176                                      PredefinedExpr::IdentKind IK) {
3177   // Pick the current block, lambda, captured statement or function.
3178   Decl *currentDecl = nullptr;
3179   if (const BlockScopeInfo *BSI = getCurBlock())
3180     currentDecl = BSI->TheDecl;
3181   else if (const LambdaScopeInfo *LSI = getCurLambda())
3182     currentDecl = LSI->CallOperator;
3183   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3184     currentDecl = CSI->TheCapturedDecl;
3185   else
3186     currentDecl = getCurFunctionOrMethodDecl();
3187 
3188   if (!currentDecl) {
3189     Diag(Loc, diag::ext_predef_outside_function);
3190     currentDecl = Context.getTranslationUnitDecl();
3191   }
3192 
3193   QualType ResTy;
3194   StringLiteral *SL = nullptr;
3195   if (cast<DeclContext>(currentDecl)->isDependentContext())
3196     ResTy = Context.DependentTy;
3197   else {
3198     // Pre-defined identifiers are of type char[x], where x is the length of
3199     // the string.
3200     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3201     unsigned Length = Str.length();
3202 
3203     llvm::APInt LengthI(32, Length + 1);
3204     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3205       ResTy =
3206           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3207       SmallString<32> RawChars;
3208       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3209                               Str, RawChars);
3210       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3211                                            /*IndexTypeQuals*/ 0);
3212       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3213                                  /*Pascal*/ false, ResTy, Loc);
3214     } else {
3215       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3216       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3217                                            /*IndexTypeQuals*/ 0);
3218       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3219                                  /*Pascal*/ false, ResTy, Loc);
3220     }
3221   }
3222 
3223   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3224 }
3225 
3226 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3227   PredefinedExpr::IdentKind IK;
3228 
3229   switch (Kind) {
3230   default: llvm_unreachable("Unknown simple primary expr!");
3231   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3232   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3233   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3234   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3235   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3236   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3237   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3238   }
3239 
3240   return BuildPredefinedExpr(Loc, IK);
3241 }
3242 
3243 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3244   SmallString<16> CharBuffer;
3245   bool Invalid = false;
3246   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3247   if (Invalid)
3248     return ExprError();
3249 
3250   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3251                             PP, Tok.getKind());
3252   if (Literal.hadError())
3253     return ExprError();
3254 
3255   QualType Ty;
3256   if (Literal.isWide())
3257     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3258   else if (Literal.isUTF8() && getLangOpts().Char8)
3259     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3260   else if (Literal.isUTF16())
3261     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3262   else if (Literal.isUTF32())
3263     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3264   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3265     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3266   else
3267     Ty = Context.CharTy;  // 'x' -> char in C++
3268 
3269   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3270   if (Literal.isWide())
3271     Kind = CharacterLiteral::Wide;
3272   else if (Literal.isUTF16())
3273     Kind = CharacterLiteral::UTF16;
3274   else if (Literal.isUTF32())
3275     Kind = CharacterLiteral::UTF32;
3276   else if (Literal.isUTF8())
3277     Kind = CharacterLiteral::UTF8;
3278 
3279   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3280                                              Tok.getLocation());
3281 
3282   if (Literal.getUDSuffix().empty())
3283     return Lit;
3284 
3285   // We're building a user-defined literal.
3286   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3287   SourceLocation UDSuffixLoc =
3288     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3289 
3290   // Make sure we're allowed user-defined literals here.
3291   if (!UDLScope)
3292     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3293 
3294   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3295   //   operator "" X (ch)
3296   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3297                                         Lit, Tok.getLocation());
3298 }
3299 
3300 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3301   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3302   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3303                                 Context.IntTy, Loc);
3304 }
3305 
3306 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3307                                   QualType Ty, SourceLocation Loc) {
3308   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3309 
3310   using llvm::APFloat;
3311   APFloat Val(Format);
3312 
3313   APFloat::opStatus result = Literal.GetFloatValue(Val);
3314 
3315   // Overflow is always an error, but underflow is only an error if
3316   // we underflowed to zero (APFloat reports denormals as underflow).
3317   if ((result & APFloat::opOverflow) ||
3318       ((result & APFloat::opUnderflow) && Val.isZero())) {
3319     unsigned diagnostic;
3320     SmallString<20> buffer;
3321     if (result & APFloat::opOverflow) {
3322       diagnostic = diag::warn_float_overflow;
3323       APFloat::getLargest(Format).toString(buffer);
3324     } else {
3325       diagnostic = diag::warn_float_underflow;
3326       APFloat::getSmallest(Format).toString(buffer);
3327     }
3328 
3329     S.Diag(Loc, diagnostic)
3330       << Ty
3331       << StringRef(buffer.data(), buffer.size());
3332   }
3333 
3334   bool isExact = (result == APFloat::opOK);
3335   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3336 }
3337 
3338 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3339   assert(E && "Invalid expression");
3340 
3341   if (E->isValueDependent())
3342     return false;
3343 
3344   QualType QT = E->getType();
3345   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3346     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3347     return true;
3348   }
3349 
3350   llvm::APSInt ValueAPS;
3351   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3352 
3353   if (R.isInvalid())
3354     return true;
3355 
3356   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3357   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3358     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3359         << ValueAPS.toString(10) << ValueIsPositive;
3360     return true;
3361   }
3362 
3363   return false;
3364 }
3365 
3366 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3367   // Fast path for a single digit (which is quite common).  A single digit
3368   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3369   if (Tok.getLength() == 1) {
3370     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3371     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3372   }
3373 
3374   SmallString<128> SpellingBuffer;
3375   // NumericLiteralParser wants to overread by one character.  Add padding to
3376   // the buffer in case the token is copied to the buffer.  If getSpelling()
3377   // returns a StringRef to the memory buffer, it should have a null char at
3378   // the EOF, so it is also safe.
3379   SpellingBuffer.resize(Tok.getLength() + 1);
3380 
3381   // Get the spelling of the token, which eliminates trigraphs, etc.
3382   bool Invalid = false;
3383   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3384   if (Invalid)
3385     return ExprError();
3386 
3387   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3388   if (Literal.hadError)
3389     return ExprError();
3390 
3391   if (Literal.hasUDSuffix()) {
3392     // We're building a user-defined literal.
3393     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3394     SourceLocation UDSuffixLoc =
3395       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3396 
3397     // Make sure we're allowed user-defined literals here.
3398     if (!UDLScope)
3399       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3400 
3401     QualType CookedTy;
3402     if (Literal.isFloatingLiteral()) {
3403       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3404       // long double, the literal is treated as a call of the form
3405       //   operator "" X (f L)
3406       CookedTy = Context.LongDoubleTy;
3407     } else {
3408       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3409       // unsigned long long, the literal is treated as a call of the form
3410       //   operator "" X (n ULL)
3411       CookedTy = Context.UnsignedLongLongTy;
3412     }
3413 
3414     DeclarationName OpName =
3415       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3416     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3417     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3418 
3419     SourceLocation TokLoc = Tok.getLocation();
3420 
3421     // Perform literal operator lookup to determine if we're building a raw
3422     // literal or a cooked one.
3423     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3424     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3425                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3426                                   /*AllowStringTemplate*/ false,
3427                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3428     case LOLR_ErrorNoDiagnostic:
3429       // Lookup failure for imaginary constants isn't fatal, there's still the
3430       // GNU extension producing _Complex types.
3431       break;
3432     case LOLR_Error:
3433       return ExprError();
3434     case LOLR_Cooked: {
3435       Expr *Lit;
3436       if (Literal.isFloatingLiteral()) {
3437         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3438       } else {
3439         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3440         if (Literal.GetIntegerValue(ResultVal))
3441           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3442               << /* Unsigned */ 1;
3443         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3444                                      Tok.getLocation());
3445       }
3446       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3447     }
3448 
3449     case LOLR_Raw: {
3450       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3451       // literal is treated as a call of the form
3452       //   operator "" X ("n")
3453       unsigned Length = Literal.getUDSuffixOffset();
3454       QualType StrTy = Context.getConstantArrayType(
3455           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3456           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3457       Expr *Lit = StringLiteral::Create(
3458           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3459           /*Pascal*/false, StrTy, &TokLoc, 1);
3460       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3461     }
3462 
3463     case LOLR_Template: {
3464       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3465       // template), L is treated as a call fo the form
3466       //   operator "" X <'c1', 'c2', ... 'ck'>()
3467       // where n is the source character sequence c1 c2 ... ck.
3468       TemplateArgumentListInfo ExplicitArgs;
3469       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3470       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3471       llvm::APSInt Value(CharBits, CharIsUnsigned);
3472       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3473         Value = TokSpelling[I];
3474         TemplateArgument Arg(Context, Value, Context.CharTy);
3475         TemplateArgumentLocInfo ArgInfo;
3476         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3477       }
3478       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3479                                       &ExplicitArgs);
3480     }
3481     case LOLR_StringTemplate:
3482       llvm_unreachable("unexpected literal operator lookup result");
3483     }
3484   }
3485 
3486   Expr *Res;
3487 
3488   if (Literal.isFixedPointLiteral()) {
3489     QualType Ty;
3490 
3491     if (Literal.isAccum) {
3492       if (Literal.isHalf) {
3493         Ty = Context.ShortAccumTy;
3494       } else if (Literal.isLong) {
3495         Ty = Context.LongAccumTy;
3496       } else {
3497         Ty = Context.AccumTy;
3498       }
3499     } else if (Literal.isFract) {
3500       if (Literal.isHalf) {
3501         Ty = Context.ShortFractTy;
3502       } else if (Literal.isLong) {
3503         Ty = Context.LongFractTy;
3504       } else {
3505         Ty = Context.FractTy;
3506       }
3507     }
3508 
3509     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3510 
3511     bool isSigned = !Literal.isUnsigned;
3512     unsigned scale = Context.getFixedPointScale(Ty);
3513     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3514 
3515     llvm::APInt Val(bit_width, 0, isSigned);
3516     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3517     bool ValIsZero = Val.isNullValue() && !Overflowed;
3518 
3519     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3520     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3521       // Clause 6.4.4 - The value of a constant shall be in the range of
3522       // representable values for its type, with exception for constants of a
3523       // fract type with a value of exactly 1; such a constant shall denote
3524       // the maximal value for the type.
3525       --Val;
3526     else if (Val.ugt(MaxVal) || Overflowed)
3527       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3528 
3529     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3530                                               Tok.getLocation(), scale);
3531   } else if (Literal.isFloatingLiteral()) {
3532     QualType Ty;
3533     if (Literal.isHalf){
3534       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3535         Ty = Context.HalfTy;
3536       else {
3537         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3538         return ExprError();
3539       }
3540     } else if (Literal.isFloat)
3541       Ty = Context.FloatTy;
3542     else if (Literal.isLong)
3543       Ty = Context.LongDoubleTy;
3544     else if (Literal.isFloat16)
3545       Ty = Context.Float16Ty;
3546     else if (Literal.isFloat128)
3547       Ty = Context.Float128Ty;
3548     else
3549       Ty = Context.DoubleTy;
3550 
3551     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3552 
3553     if (Ty == Context.DoubleTy) {
3554       if (getLangOpts().SinglePrecisionConstants) {
3555         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3556         if (BTy->getKind() != BuiltinType::Float) {
3557           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3558         }
3559       } else if (getLangOpts().OpenCL &&
3560                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3561         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3562         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3563         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3564       }
3565     }
3566   } else if (!Literal.isIntegerLiteral()) {
3567     return ExprError();
3568   } else {
3569     QualType Ty;
3570 
3571     // 'long long' is a C99 or C++11 feature.
3572     if (!getLangOpts().C99 && Literal.isLongLong) {
3573       if (getLangOpts().CPlusPlus)
3574         Diag(Tok.getLocation(),
3575              getLangOpts().CPlusPlus11 ?
3576              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3577       else
3578         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3579     }
3580 
3581     // Get the value in the widest-possible width.
3582     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3583     llvm::APInt ResultVal(MaxWidth, 0);
3584 
3585     if (Literal.GetIntegerValue(ResultVal)) {
3586       // If this value didn't fit into uintmax_t, error and force to ull.
3587       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3588           << /* Unsigned */ 1;
3589       Ty = Context.UnsignedLongLongTy;
3590       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3591              "long long is not intmax_t?");
3592     } else {
3593       // If this value fits into a ULL, try to figure out what else it fits into
3594       // according to the rules of C99 6.4.4.1p5.
3595 
3596       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3597       // be an unsigned int.
3598       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3599 
3600       // Check from smallest to largest, picking the smallest type we can.
3601       unsigned Width = 0;
3602 
3603       // Microsoft specific integer suffixes are explicitly sized.
3604       if (Literal.MicrosoftInteger) {
3605         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3606           Width = 8;
3607           Ty = Context.CharTy;
3608         } else {
3609           Width = Literal.MicrosoftInteger;
3610           Ty = Context.getIntTypeForBitwidth(Width,
3611                                              /*Signed=*/!Literal.isUnsigned);
3612         }
3613       }
3614 
3615       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3616         // Are int/unsigned possibilities?
3617         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3618 
3619         // Does it fit in a unsigned int?
3620         if (ResultVal.isIntN(IntSize)) {
3621           // Does it fit in a signed int?
3622           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3623             Ty = Context.IntTy;
3624           else if (AllowUnsigned)
3625             Ty = Context.UnsignedIntTy;
3626           Width = IntSize;
3627         }
3628       }
3629 
3630       // Are long/unsigned long possibilities?
3631       if (Ty.isNull() && !Literal.isLongLong) {
3632         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3633 
3634         // Does it fit in a unsigned long?
3635         if (ResultVal.isIntN(LongSize)) {
3636           // Does it fit in a signed long?
3637           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3638             Ty = Context.LongTy;
3639           else if (AllowUnsigned)
3640             Ty = Context.UnsignedLongTy;
3641           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3642           // is compatible.
3643           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3644             const unsigned LongLongSize =
3645                 Context.getTargetInfo().getLongLongWidth();
3646             Diag(Tok.getLocation(),
3647                  getLangOpts().CPlusPlus
3648                      ? Literal.isLong
3649                            ? diag::warn_old_implicitly_unsigned_long_cxx
3650                            : /*C++98 UB*/ diag::
3651                                  ext_old_implicitly_unsigned_long_cxx
3652                      : diag::warn_old_implicitly_unsigned_long)
3653                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3654                                             : /*will be ill-formed*/ 1);
3655             Ty = Context.UnsignedLongTy;
3656           }
3657           Width = LongSize;
3658         }
3659       }
3660 
3661       // Check long long if needed.
3662       if (Ty.isNull()) {
3663         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3664 
3665         // Does it fit in a unsigned long long?
3666         if (ResultVal.isIntN(LongLongSize)) {
3667           // Does it fit in a signed long long?
3668           // To be compatible with MSVC, hex integer literals ending with the
3669           // LL or i64 suffix are always signed in Microsoft mode.
3670           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3671               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3672             Ty = Context.LongLongTy;
3673           else if (AllowUnsigned)
3674             Ty = Context.UnsignedLongLongTy;
3675           Width = LongLongSize;
3676         }
3677       }
3678 
3679       // If we still couldn't decide a type, we probably have something that
3680       // does not fit in a signed long long, but has no U suffix.
3681       if (Ty.isNull()) {
3682         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3683         Ty = Context.UnsignedLongLongTy;
3684         Width = Context.getTargetInfo().getLongLongWidth();
3685       }
3686 
3687       if (ResultVal.getBitWidth() != Width)
3688         ResultVal = ResultVal.trunc(Width);
3689     }
3690     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3691   }
3692 
3693   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3694   if (Literal.isImaginary) {
3695     Res = new (Context) ImaginaryLiteral(Res,
3696                                         Context.getComplexType(Res->getType()));
3697 
3698     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3699   }
3700   return Res;
3701 }
3702 
3703 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3704   assert(E && "ActOnParenExpr() missing expr");
3705   return new (Context) ParenExpr(L, R, E);
3706 }
3707 
3708 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3709                                          SourceLocation Loc,
3710                                          SourceRange ArgRange) {
3711   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3712   // scalar or vector data type argument..."
3713   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3714   // type (C99 6.2.5p18) or void.
3715   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3716     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3717       << T << ArgRange;
3718     return true;
3719   }
3720 
3721   assert((T->isVoidType() || !T->isIncompleteType()) &&
3722          "Scalar types should always be complete");
3723   return false;
3724 }
3725 
3726 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3727                                            SourceLocation Loc,
3728                                            SourceRange ArgRange,
3729                                            UnaryExprOrTypeTrait TraitKind) {
3730   // Invalid types must be hard errors for SFINAE in C++.
3731   if (S.LangOpts.CPlusPlus)
3732     return true;
3733 
3734   // C99 6.5.3.4p1:
3735   if (T->isFunctionType() &&
3736       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3737        TraitKind == UETT_PreferredAlignOf)) {
3738     // sizeof(function)/alignof(function) is allowed as an extension.
3739     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3740       << TraitKind << ArgRange;
3741     return false;
3742   }
3743 
3744   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3745   // this is an error (OpenCL v1.1 s6.3.k)
3746   if (T->isVoidType()) {
3747     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3748                                         : diag::ext_sizeof_alignof_void_type;
3749     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3750     return false;
3751   }
3752 
3753   return true;
3754 }
3755 
3756 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3757                                              SourceLocation Loc,
3758                                              SourceRange ArgRange,
3759                                              UnaryExprOrTypeTrait TraitKind) {
3760   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3761   // runtime doesn't allow it.
3762   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3763     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3764       << T << (TraitKind == UETT_SizeOf)
3765       << ArgRange;
3766     return true;
3767   }
3768 
3769   return false;
3770 }
3771 
3772 /// Check whether E is a pointer from a decayed array type (the decayed
3773 /// pointer type is equal to T) and emit a warning if it is.
3774 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3775                                      Expr *E) {
3776   // Don't warn if the operation changed the type.
3777   if (T != E->getType())
3778     return;
3779 
3780   // Now look for array decays.
3781   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3782   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3783     return;
3784 
3785   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3786                                              << ICE->getType()
3787                                              << ICE->getSubExpr()->getType();
3788 }
3789 
3790 /// Check the constraints on expression operands to unary type expression
3791 /// and type traits.
3792 ///
3793 /// Completes any types necessary and validates the constraints on the operand
3794 /// expression. The logic mostly mirrors the type-based overload, but may modify
3795 /// the expression as it completes the type for that expression through template
3796 /// instantiation, etc.
3797 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3798                                             UnaryExprOrTypeTrait ExprKind) {
3799   QualType ExprTy = E->getType();
3800   assert(!ExprTy->isReferenceType());
3801 
3802   if (ExprKind == UETT_VecStep)
3803     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3804                                         E->getSourceRange());
3805 
3806   // Whitelist some types as extensions
3807   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3808                                       E->getSourceRange(), ExprKind))
3809     return false;
3810 
3811   // 'alignof' applied to an expression only requires the base element type of
3812   // the expression to be complete. 'sizeof' requires the expression's type to
3813   // be complete (and will attempt to complete it if it's an array of unknown
3814   // bound).
3815   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3816     if (RequireCompleteType(E->getExprLoc(),
3817                             Context.getBaseElementType(E->getType()),
3818                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3819                             E->getSourceRange()))
3820       return true;
3821   } else {
3822     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3823                                 ExprKind, E->getSourceRange()))
3824       return true;
3825   }
3826 
3827   // Completing the expression's type may have changed it.
3828   ExprTy = E->getType();
3829   assert(!ExprTy->isReferenceType());
3830 
3831   if (ExprTy->isFunctionType()) {
3832     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3833       << ExprKind << E->getSourceRange();
3834     return true;
3835   }
3836 
3837   // The operand for sizeof and alignof is in an unevaluated expression context,
3838   // so side effects could result in unintended consequences.
3839   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3840        ExprKind == UETT_PreferredAlignOf) &&
3841       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3842     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3843 
3844   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3845                                        E->getSourceRange(), ExprKind))
3846     return true;
3847 
3848   if (ExprKind == UETT_SizeOf) {
3849     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3850       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3851         QualType OType = PVD->getOriginalType();
3852         QualType Type = PVD->getType();
3853         if (Type->isPointerType() && OType->isArrayType()) {
3854           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3855             << Type << OType;
3856           Diag(PVD->getLocation(), diag::note_declared_at);
3857         }
3858       }
3859     }
3860 
3861     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3862     // decays into a pointer and returns an unintended result. This is most
3863     // likely a typo for "sizeof(array) op x".
3864     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3865       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3866                                BO->getLHS());
3867       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3868                                BO->getRHS());
3869     }
3870   }
3871 
3872   return false;
3873 }
3874 
3875 /// Check the constraints on operands to unary expression and type
3876 /// traits.
3877 ///
3878 /// This will complete any types necessary, and validate the various constraints
3879 /// on those operands.
3880 ///
3881 /// The UsualUnaryConversions() function is *not* called by this routine.
3882 /// C99 6.3.2.1p[2-4] all state:
3883 ///   Except when it is the operand of the sizeof operator ...
3884 ///
3885 /// C++ [expr.sizeof]p4
3886 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3887 ///   standard conversions are not applied to the operand of sizeof.
3888 ///
3889 /// This policy is followed for all of the unary trait expressions.
3890 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3891                                             SourceLocation OpLoc,
3892                                             SourceRange ExprRange,
3893                                             UnaryExprOrTypeTrait ExprKind) {
3894   if (ExprType->isDependentType())
3895     return false;
3896 
3897   // C++ [expr.sizeof]p2:
3898   //     When applied to a reference or a reference type, the result
3899   //     is the size of the referenced type.
3900   // C++11 [expr.alignof]p3:
3901   //     When alignof is applied to a reference type, the result
3902   //     shall be the alignment of the referenced type.
3903   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3904     ExprType = Ref->getPointeeType();
3905 
3906   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3907   //   When alignof or _Alignof is applied to an array type, the result
3908   //   is the alignment of the element type.
3909   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3910       ExprKind == UETT_OpenMPRequiredSimdAlign)
3911     ExprType = Context.getBaseElementType(ExprType);
3912 
3913   if (ExprKind == UETT_VecStep)
3914     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3915 
3916   // Whitelist some types as extensions
3917   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3918                                       ExprKind))
3919     return false;
3920 
3921   if (RequireCompleteType(OpLoc, ExprType,
3922                           diag::err_sizeof_alignof_incomplete_type,
3923                           ExprKind, ExprRange))
3924     return true;
3925 
3926   if (ExprType->isFunctionType()) {
3927     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3928       << ExprKind << ExprRange;
3929     return true;
3930   }
3931 
3932   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3933                                        ExprKind))
3934     return true;
3935 
3936   return false;
3937 }
3938 
3939 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3940   E = E->IgnoreParens();
3941 
3942   // Cannot know anything else if the expression is dependent.
3943   if (E->isTypeDependent())
3944     return false;
3945 
3946   if (E->getObjectKind() == OK_BitField) {
3947     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3948        << 1 << E->getSourceRange();
3949     return true;
3950   }
3951 
3952   ValueDecl *D = nullptr;
3953   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3954     D = DRE->getDecl();
3955   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3956     D = ME->getMemberDecl();
3957   }
3958 
3959   // If it's a field, require the containing struct to have a
3960   // complete definition so that we can compute the layout.
3961   //
3962   // This can happen in C++11 onwards, either by naming the member
3963   // in a way that is not transformed into a member access expression
3964   // (in an unevaluated operand, for instance), or by naming the member
3965   // in a trailing-return-type.
3966   //
3967   // For the record, since __alignof__ on expressions is a GCC
3968   // extension, GCC seems to permit this but always gives the
3969   // nonsensical answer 0.
3970   //
3971   // We don't really need the layout here --- we could instead just
3972   // directly check for all the appropriate alignment-lowing
3973   // attributes --- but that would require duplicating a lot of
3974   // logic that just isn't worth duplicating for such a marginal
3975   // use-case.
3976   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3977     // Fast path this check, since we at least know the record has a
3978     // definition if we can find a member of it.
3979     if (!FD->getParent()->isCompleteDefinition()) {
3980       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3981         << E->getSourceRange();
3982       return true;
3983     }
3984 
3985     // Otherwise, if it's a field, and the field doesn't have
3986     // reference type, then it must have a complete type (or be a
3987     // flexible array member, which we explicitly want to
3988     // white-list anyway), which makes the following checks trivial.
3989     if (!FD->getType()->isReferenceType())
3990       return false;
3991   }
3992 
3993   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3994 }
3995 
3996 bool Sema::CheckVecStepExpr(Expr *E) {
3997   E = E->IgnoreParens();
3998 
3999   // Cannot know anything else if the expression is dependent.
4000   if (E->isTypeDependent())
4001     return false;
4002 
4003   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4004 }
4005 
4006 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4007                                         CapturingScopeInfo *CSI) {
4008   assert(T->isVariablyModifiedType());
4009   assert(CSI != nullptr);
4010 
4011   // We're going to walk down into the type and look for VLA expressions.
4012   do {
4013     const Type *Ty = T.getTypePtr();
4014     switch (Ty->getTypeClass()) {
4015 #define TYPE(Class, Base)
4016 #define ABSTRACT_TYPE(Class, Base)
4017 #define NON_CANONICAL_TYPE(Class, Base)
4018 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4019 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4020 #include "clang/AST/TypeNodes.def"
4021       T = QualType();
4022       break;
4023     // These types are never variably-modified.
4024     case Type::Builtin:
4025     case Type::Complex:
4026     case Type::Vector:
4027     case Type::ExtVector:
4028     case Type::Record:
4029     case Type::Enum:
4030     case Type::Elaborated:
4031     case Type::TemplateSpecialization:
4032     case Type::ObjCObject:
4033     case Type::ObjCInterface:
4034     case Type::ObjCObjectPointer:
4035     case Type::ObjCTypeParam:
4036     case Type::Pipe:
4037       llvm_unreachable("type class is never variably-modified!");
4038     case Type::Adjusted:
4039       T = cast<AdjustedType>(Ty)->getOriginalType();
4040       break;
4041     case Type::Decayed:
4042       T = cast<DecayedType>(Ty)->getPointeeType();
4043       break;
4044     case Type::Pointer:
4045       T = cast<PointerType>(Ty)->getPointeeType();
4046       break;
4047     case Type::BlockPointer:
4048       T = cast<BlockPointerType>(Ty)->getPointeeType();
4049       break;
4050     case Type::LValueReference:
4051     case Type::RValueReference:
4052       T = cast<ReferenceType>(Ty)->getPointeeType();
4053       break;
4054     case Type::MemberPointer:
4055       T = cast<MemberPointerType>(Ty)->getPointeeType();
4056       break;
4057     case Type::ConstantArray:
4058     case Type::IncompleteArray:
4059       // Losing element qualification here is fine.
4060       T = cast<ArrayType>(Ty)->getElementType();
4061       break;
4062     case Type::VariableArray: {
4063       // Losing element qualification here is fine.
4064       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4065 
4066       // Unknown size indication requires no size computation.
4067       // Otherwise, evaluate and record it.
4068       auto Size = VAT->getSizeExpr();
4069       if (Size && !CSI->isVLATypeCaptured(VAT) &&
4070           (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4071         CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4072 
4073       T = VAT->getElementType();
4074       break;
4075     }
4076     case Type::FunctionProto:
4077     case Type::FunctionNoProto:
4078       T = cast<FunctionType>(Ty)->getReturnType();
4079       break;
4080     case Type::Paren:
4081     case Type::TypeOf:
4082     case Type::UnaryTransform:
4083     case Type::Attributed:
4084     case Type::SubstTemplateTypeParm:
4085     case Type::PackExpansion:
4086     case Type::MacroQualified:
4087       // Keep walking after single level desugaring.
4088       T = T.getSingleStepDesugaredType(Context);
4089       break;
4090     case Type::Typedef:
4091       T = cast<TypedefType>(Ty)->desugar();
4092       break;
4093     case Type::Decltype:
4094       T = cast<DecltypeType>(Ty)->desugar();
4095       break;
4096     case Type::Auto:
4097     case Type::DeducedTemplateSpecialization:
4098       T = cast<DeducedType>(Ty)->getDeducedType();
4099       break;
4100     case Type::TypeOfExpr:
4101       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4102       break;
4103     case Type::Atomic:
4104       T = cast<AtomicType>(Ty)->getValueType();
4105       break;
4106     }
4107   } while (!T.isNull() && T->isVariablyModifiedType());
4108 }
4109 
4110 /// Build a sizeof or alignof expression given a type operand.
4111 ExprResult
4112 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4113                                      SourceLocation OpLoc,
4114                                      UnaryExprOrTypeTrait ExprKind,
4115                                      SourceRange R) {
4116   if (!TInfo)
4117     return ExprError();
4118 
4119   QualType T = TInfo->getType();
4120 
4121   if (!T->isDependentType() &&
4122       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4123     return ExprError();
4124 
4125   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4126     if (auto *TT = T->getAs<TypedefType>()) {
4127       for (auto I = FunctionScopes.rbegin(),
4128                 E = std::prev(FunctionScopes.rend());
4129            I != E; ++I) {
4130         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4131         if (CSI == nullptr)
4132           break;
4133         DeclContext *DC = nullptr;
4134         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4135           DC = LSI->CallOperator;
4136         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4137           DC = CRSI->TheCapturedDecl;
4138         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4139           DC = BSI->TheDecl;
4140         if (DC) {
4141           if (DC->containsDecl(TT->getDecl()))
4142             break;
4143           captureVariablyModifiedType(Context, T, CSI);
4144         }
4145       }
4146     }
4147   }
4148 
4149   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4150   return new (Context) UnaryExprOrTypeTraitExpr(
4151       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4152 }
4153 
4154 /// Build a sizeof or alignof expression given an expression
4155 /// operand.
4156 ExprResult
4157 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4158                                      UnaryExprOrTypeTrait ExprKind) {
4159   ExprResult PE = CheckPlaceholderExpr(E);
4160   if (PE.isInvalid())
4161     return ExprError();
4162 
4163   E = PE.get();
4164 
4165   // Verify that the operand is valid.
4166   bool isInvalid = false;
4167   if (E->isTypeDependent()) {
4168     // Delay type-checking for type-dependent expressions.
4169   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4170     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4171   } else if (ExprKind == UETT_VecStep) {
4172     isInvalid = CheckVecStepExpr(E);
4173   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4174       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4175       isInvalid = true;
4176   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4177     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4178     isInvalid = true;
4179   } else {
4180     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4181   }
4182 
4183   if (isInvalid)
4184     return ExprError();
4185 
4186   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4187     PE = TransformToPotentiallyEvaluated(E);
4188     if (PE.isInvalid()) return ExprError();
4189     E = PE.get();
4190   }
4191 
4192   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4193   return new (Context) UnaryExprOrTypeTraitExpr(
4194       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4195 }
4196 
4197 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4198 /// expr and the same for @c alignof and @c __alignof
4199 /// Note that the ArgRange is invalid if isType is false.
4200 ExprResult
4201 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4202                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4203                                     void *TyOrEx, SourceRange ArgRange) {
4204   // If error parsing type, ignore.
4205   if (!TyOrEx) return ExprError();
4206 
4207   if (IsType) {
4208     TypeSourceInfo *TInfo;
4209     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4210     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4211   }
4212 
4213   Expr *ArgEx = (Expr *)TyOrEx;
4214   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4215   return Result;
4216 }
4217 
4218 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4219                                      bool IsReal) {
4220   if (V.get()->isTypeDependent())
4221     return S.Context.DependentTy;
4222 
4223   // _Real and _Imag are only l-values for normal l-values.
4224   if (V.get()->getObjectKind() != OK_Ordinary) {
4225     V = S.DefaultLvalueConversion(V.get());
4226     if (V.isInvalid())
4227       return QualType();
4228   }
4229 
4230   // These operators return the element type of a complex type.
4231   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4232     return CT->getElementType();
4233 
4234   // Otherwise they pass through real integer and floating point types here.
4235   if (V.get()->getType()->isArithmeticType())
4236     return V.get()->getType();
4237 
4238   // Test for placeholders.
4239   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4240   if (PR.isInvalid()) return QualType();
4241   if (PR.get() != V.get()) {
4242     V = PR;
4243     return CheckRealImagOperand(S, V, Loc, IsReal);
4244   }
4245 
4246   // Reject anything else.
4247   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4248     << (IsReal ? "__real" : "__imag");
4249   return QualType();
4250 }
4251 
4252 
4253 
4254 ExprResult
4255 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4256                           tok::TokenKind Kind, Expr *Input) {
4257   UnaryOperatorKind Opc;
4258   switch (Kind) {
4259   default: llvm_unreachable("Unknown unary op!");
4260   case tok::plusplus:   Opc = UO_PostInc; break;
4261   case tok::minusminus: Opc = UO_PostDec; break;
4262   }
4263 
4264   // Since this might is a postfix expression, get rid of ParenListExprs.
4265   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4266   if (Result.isInvalid()) return ExprError();
4267   Input = Result.get();
4268 
4269   return BuildUnaryOp(S, OpLoc, Opc, Input);
4270 }
4271 
4272 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4273 ///
4274 /// \return true on error
4275 static bool checkArithmeticOnObjCPointer(Sema &S,
4276                                          SourceLocation opLoc,
4277                                          Expr *op) {
4278   assert(op->getType()->isObjCObjectPointerType());
4279   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4280       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4281     return false;
4282 
4283   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4284     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4285     << op->getSourceRange();
4286   return true;
4287 }
4288 
4289 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4290   auto *BaseNoParens = Base->IgnoreParens();
4291   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4292     return MSProp->getPropertyDecl()->getType()->isArrayType();
4293   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4294 }
4295 
4296 ExprResult
4297 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4298                               Expr *idx, SourceLocation rbLoc) {
4299   if (base && !base->getType().isNull() &&
4300       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4301     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4302                                     /*Length=*/nullptr, rbLoc);
4303 
4304   // Since this might be a postfix expression, get rid of ParenListExprs.
4305   if (isa<ParenListExpr>(base)) {
4306     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4307     if (result.isInvalid()) return ExprError();
4308     base = result.get();
4309   }
4310 
4311   // A comma-expression as the index is deprecated in C++2a onwards.
4312   if (getLangOpts().CPlusPlus2a &&
4313       ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4314        (isa<CXXOperatorCallExpr>(idx) &&
4315         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4316     Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4317       << SourceRange(base->getBeginLoc(), rbLoc);
4318   }
4319 
4320   // Handle any non-overload placeholder types in the base and index
4321   // expressions.  We can't handle overloads here because the other
4322   // operand might be an overloadable type, in which case the overload
4323   // resolution for the operator overload should get the first crack
4324   // at the overload.
4325   bool IsMSPropertySubscript = false;
4326   if (base->getType()->isNonOverloadPlaceholderType()) {
4327     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4328     if (!IsMSPropertySubscript) {
4329       ExprResult result = CheckPlaceholderExpr(base);
4330       if (result.isInvalid())
4331         return ExprError();
4332       base = result.get();
4333     }
4334   }
4335   if (idx->getType()->isNonOverloadPlaceholderType()) {
4336     ExprResult result = CheckPlaceholderExpr(idx);
4337     if (result.isInvalid()) return ExprError();
4338     idx = result.get();
4339   }
4340 
4341   // Build an unanalyzed expression if either operand is type-dependent.
4342   if (getLangOpts().CPlusPlus &&
4343       (base->isTypeDependent() || idx->isTypeDependent())) {
4344     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4345                                             VK_LValue, OK_Ordinary, rbLoc);
4346   }
4347 
4348   // MSDN, property (C++)
4349   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4350   // This attribute can also be used in the declaration of an empty array in a
4351   // class or structure definition. For example:
4352   // __declspec(property(get=GetX, put=PutX)) int x[];
4353   // The above statement indicates that x[] can be used with one or more array
4354   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4355   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4356   if (IsMSPropertySubscript) {
4357     // Build MS property subscript expression if base is MS property reference
4358     // or MS property subscript.
4359     return new (Context) MSPropertySubscriptExpr(
4360         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4361   }
4362 
4363   // Use C++ overloaded-operator rules if either operand has record
4364   // type.  The spec says to do this if either type is *overloadable*,
4365   // but enum types can't declare subscript operators or conversion
4366   // operators, so there's nothing interesting for overload resolution
4367   // to do if there aren't any record types involved.
4368   //
4369   // ObjC pointers have their own subscripting logic that is not tied
4370   // to overload resolution and so should not take this path.
4371   if (getLangOpts().CPlusPlus &&
4372       (base->getType()->isRecordType() ||
4373        (!base->getType()->isObjCObjectPointerType() &&
4374         idx->getType()->isRecordType()))) {
4375     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4376   }
4377 
4378   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4379 
4380   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4381     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4382 
4383   return Res;
4384 }
4385 
4386 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4387   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4388   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4389 
4390   // For expressions like `&(*s).b`, the base is recorded and what should be
4391   // checked.
4392   const MemberExpr *Member = nullptr;
4393   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4394     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4395 
4396   LastRecord.PossibleDerefs.erase(StrippedExpr);
4397 }
4398 
4399 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4400   QualType ResultTy = E->getType();
4401   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4402 
4403   // Bail if the element is an array since it is not memory access.
4404   if (isa<ArrayType>(ResultTy))
4405     return;
4406 
4407   if (ResultTy->hasAttr(attr::NoDeref)) {
4408     LastRecord.PossibleDerefs.insert(E);
4409     return;
4410   }
4411 
4412   // Check if the base type is a pointer to a member access of a struct
4413   // marked with noderef.
4414   const Expr *Base = E->getBase();
4415   QualType BaseTy = Base->getType();
4416   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4417     // Not a pointer access
4418     return;
4419 
4420   const MemberExpr *Member = nullptr;
4421   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4422          Member->isArrow())
4423     Base = Member->getBase();
4424 
4425   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4426     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4427       LastRecord.PossibleDerefs.insert(E);
4428   }
4429 }
4430 
4431 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4432                                           Expr *LowerBound,
4433                                           SourceLocation ColonLoc, Expr *Length,
4434                                           SourceLocation RBLoc) {
4435   if (Base->getType()->isPlaceholderType() &&
4436       !Base->getType()->isSpecificPlaceholderType(
4437           BuiltinType::OMPArraySection)) {
4438     ExprResult Result = CheckPlaceholderExpr(Base);
4439     if (Result.isInvalid())
4440       return ExprError();
4441     Base = Result.get();
4442   }
4443   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4444     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4445     if (Result.isInvalid())
4446       return ExprError();
4447     Result = DefaultLvalueConversion(Result.get());
4448     if (Result.isInvalid())
4449       return ExprError();
4450     LowerBound = Result.get();
4451   }
4452   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4453     ExprResult Result = CheckPlaceholderExpr(Length);
4454     if (Result.isInvalid())
4455       return ExprError();
4456     Result = DefaultLvalueConversion(Result.get());
4457     if (Result.isInvalid())
4458       return ExprError();
4459     Length = Result.get();
4460   }
4461 
4462   // Build an unanalyzed expression if either operand is type-dependent.
4463   if (Base->isTypeDependent() ||
4464       (LowerBound &&
4465        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4466       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4467     return new (Context)
4468         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4469                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4470   }
4471 
4472   // Perform default conversions.
4473   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4474   QualType ResultTy;
4475   if (OriginalTy->isAnyPointerType()) {
4476     ResultTy = OriginalTy->getPointeeType();
4477   } else if (OriginalTy->isArrayType()) {
4478     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4479   } else {
4480     return ExprError(
4481         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4482         << Base->getSourceRange());
4483   }
4484   // C99 6.5.2.1p1
4485   if (LowerBound) {
4486     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4487                                                       LowerBound);
4488     if (Res.isInvalid())
4489       return ExprError(Diag(LowerBound->getExprLoc(),
4490                             diag::err_omp_typecheck_section_not_integer)
4491                        << 0 << LowerBound->getSourceRange());
4492     LowerBound = Res.get();
4493 
4494     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4495         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4496       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4497           << 0 << LowerBound->getSourceRange();
4498   }
4499   if (Length) {
4500     auto Res =
4501         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4502     if (Res.isInvalid())
4503       return ExprError(Diag(Length->getExprLoc(),
4504                             diag::err_omp_typecheck_section_not_integer)
4505                        << 1 << Length->getSourceRange());
4506     Length = Res.get();
4507 
4508     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4509         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4510       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4511           << 1 << Length->getSourceRange();
4512   }
4513 
4514   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4515   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4516   // type. Note that functions are not objects, and that (in C99 parlance)
4517   // incomplete types are not object types.
4518   if (ResultTy->isFunctionType()) {
4519     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4520         << ResultTy << Base->getSourceRange();
4521     return ExprError();
4522   }
4523 
4524   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4525                           diag::err_omp_section_incomplete_type, Base))
4526     return ExprError();
4527 
4528   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4529     Expr::EvalResult Result;
4530     if (LowerBound->EvaluateAsInt(Result, Context)) {
4531       // OpenMP 4.5, [2.4 Array Sections]
4532       // The array section must be a subset of the original array.
4533       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4534       if (LowerBoundValue.isNegative()) {
4535         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4536             << LowerBound->getSourceRange();
4537         return ExprError();
4538       }
4539     }
4540   }
4541 
4542   if (Length) {
4543     Expr::EvalResult Result;
4544     if (Length->EvaluateAsInt(Result, Context)) {
4545       // OpenMP 4.5, [2.4 Array Sections]
4546       // The length must evaluate to non-negative integers.
4547       llvm::APSInt LengthValue = Result.Val.getInt();
4548       if (LengthValue.isNegative()) {
4549         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4550             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4551             << Length->getSourceRange();
4552         return ExprError();
4553       }
4554     }
4555   } else if (ColonLoc.isValid() &&
4556              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4557                                       !OriginalTy->isVariableArrayType()))) {
4558     // OpenMP 4.5, [2.4 Array Sections]
4559     // When the size of the array dimension is not known, the length must be
4560     // specified explicitly.
4561     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4562         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4563     return ExprError();
4564   }
4565 
4566   if (!Base->getType()->isSpecificPlaceholderType(
4567           BuiltinType::OMPArraySection)) {
4568     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4569     if (Result.isInvalid())
4570       return ExprError();
4571     Base = Result.get();
4572   }
4573   return new (Context)
4574       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4575                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4576 }
4577 
4578 ExprResult
4579 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4580                                       Expr *Idx, SourceLocation RLoc) {
4581   Expr *LHSExp = Base;
4582   Expr *RHSExp = Idx;
4583 
4584   ExprValueKind VK = VK_LValue;
4585   ExprObjectKind OK = OK_Ordinary;
4586 
4587   // Per C++ core issue 1213, the result is an xvalue if either operand is
4588   // a non-lvalue array, and an lvalue otherwise.
4589   if (getLangOpts().CPlusPlus11) {
4590     for (auto *Op : {LHSExp, RHSExp}) {
4591       Op = Op->IgnoreImplicit();
4592       if (Op->getType()->isArrayType() && !Op->isLValue())
4593         VK = VK_XValue;
4594     }
4595   }
4596 
4597   // Perform default conversions.
4598   if (!LHSExp->getType()->getAs<VectorType>()) {
4599     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4600     if (Result.isInvalid())
4601       return ExprError();
4602     LHSExp = Result.get();
4603   }
4604   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4605   if (Result.isInvalid())
4606     return ExprError();
4607   RHSExp = Result.get();
4608 
4609   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4610 
4611   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4612   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4613   // in the subscript position. As a result, we need to derive the array base
4614   // and index from the expression types.
4615   Expr *BaseExpr, *IndexExpr;
4616   QualType ResultType;
4617   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4618     BaseExpr = LHSExp;
4619     IndexExpr = RHSExp;
4620     ResultType = Context.DependentTy;
4621   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4622     BaseExpr = LHSExp;
4623     IndexExpr = RHSExp;
4624     ResultType = PTy->getPointeeType();
4625   } else if (const ObjCObjectPointerType *PTy =
4626                LHSTy->getAs<ObjCObjectPointerType>()) {
4627     BaseExpr = LHSExp;
4628     IndexExpr = RHSExp;
4629 
4630     // Use custom logic if this should be the pseudo-object subscript
4631     // expression.
4632     if (!LangOpts.isSubscriptPointerArithmetic())
4633       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4634                                           nullptr);
4635 
4636     ResultType = PTy->getPointeeType();
4637   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4638      // Handle the uncommon case of "123[Ptr]".
4639     BaseExpr = RHSExp;
4640     IndexExpr = LHSExp;
4641     ResultType = PTy->getPointeeType();
4642   } else if (const ObjCObjectPointerType *PTy =
4643                RHSTy->getAs<ObjCObjectPointerType>()) {
4644      // Handle the uncommon case of "123[Ptr]".
4645     BaseExpr = RHSExp;
4646     IndexExpr = LHSExp;
4647     ResultType = PTy->getPointeeType();
4648     if (!LangOpts.isSubscriptPointerArithmetic()) {
4649       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4650         << ResultType << BaseExpr->getSourceRange();
4651       return ExprError();
4652     }
4653   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4654     BaseExpr = LHSExp;    // vectors: V[123]
4655     IndexExpr = RHSExp;
4656     // We apply C++ DR1213 to vector subscripting too.
4657     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4658       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4659       if (Materialized.isInvalid())
4660         return ExprError();
4661       LHSExp = Materialized.get();
4662     }
4663     VK = LHSExp->getValueKind();
4664     if (VK != VK_RValue)
4665       OK = OK_VectorComponent;
4666 
4667     ResultType = VTy->getElementType();
4668     QualType BaseType = BaseExpr->getType();
4669     Qualifiers BaseQuals = BaseType.getQualifiers();
4670     Qualifiers MemberQuals = ResultType.getQualifiers();
4671     Qualifiers Combined = BaseQuals + MemberQuals;
4672     if (Combined != MemberQuals)
4673       ResultType = Context.getQualifiedType(ResultType, Combined);
4674   } else if (LHSTy->isArrayType()) {
4675     // If we see an array that wasn't promoted by
4676     // DefaultFunctionArrayLvalueConversion, it must be an array that
4677     // wasn't promoted because of the C90 rule that doesn't
4678     // allow promoting non-lvalue arrays.  Warn, then
4679     // force the promotion here.
4680     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4681         << LHSExp->getSourceRange();
4682     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4683                                CK_ArrayToPointerDecay).get();
4684     LHSTy = LHSExp->getType();
4685 
4686     BaseExpr = LHSExp;
4687     IndexExpr = RHSExp;
4688     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4689   } else if (RHSTy->isArrayType()) {
4690     // Same as previous, except for 123[f().a] case
4691     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4692         << RHSExp->getSourceRange();
4693     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4694                                CK_ArrayToPointerDecay).get();
4695     RHSTy = RHSExp->getType();
4696 
4697     BaseExpr = RHSExp;
4698     IndexExpr = LHSExp;
4699     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4700   } else {
4701     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4702        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4703   }
4704   // C99 6.5.2.1p1
4705   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4706     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4707                      << IndexExpr->getSourceRange());
4708 
4709   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4710        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4711          && !IndexExpr->isTypeDependent())
4712     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4713 
4714   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4715   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4716   // type. Note that Functions are not objects, and that (in C99 parlance)
4717   // incomplete types are not object types.
4718   if (ResultType->isFunctionType()) {
4719     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4720         << ResultType << BaseExpr->getSourceRange();
4721     return ExprError();
4722   }
4723 
4724   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4725     // GNU extension: subscripting on pointer to void
4726     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4727       << BaseExpr->getSourceRange();
4728 
4729     // C forbids expressions of unqualified void type from being l-values.
4730     // See IsCForbiddenLValueType.
4731     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4732   } else if (!ResultType->isDependentType() &&
4733       RequireCompleteType(LLoc, ResultType,
4734                           diag::err_subscript_incomplete_type, BaseExpr))
4735     return ExprError();
4736 
4737   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4738          !ResultType.isCForbiddenLValueType());
4739 
4740   if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4741       FunctionScopes.size() > 1) {
4742     if (auto *TT =
4743             LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4744       for (auto I = FunctionScopes.rbegin(),
4745                 E = std::prev(FunctionScopes.rend());
4746            I != E; ++I) {
4747         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4748         if (CSI == nullptr)
4749           break;
4750         DeclContext *DC = nullptr;
4751         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4752           DC = LSI->CallOperator;
4753         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4754           DC = CRSI->TheCapturedDecl;
4755         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4756           DC = BSI->TheDecl;
4757         if (DC) {
4758           if (DC->containsDecl(TT->getDecl()))
4759             break;
4760           captureVariablyModifiedType(
4761               Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4762         }
4763       }
4764     }
4765   }
4766 
4767   return new (Context)
4768       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4769 }
4770 
4771 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4772                                   ParmVarDecl *Param) {
4773   if (Param->hasUnparsedDefaultArg()) {
4774     Diag(CallLoc,
4775          diag::err_use_of_default_argument_to_function_declared_later) <<
4776       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4777     Diag(UnparsedDefaultArgLocs[Param],
4778          diag::note_default_argument_declared_here);
4779     return true;
4780   }
4781 
4782   if (Param->hasUninstantiatedDefaultArg()) {
4783     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4784 
4785     EnterExpressionEvaluationContext EvalContext(
4786         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4787 
4788     // Instantiate the expression.
4789     //
4790     // FIXME: Pass in a correct Pattern argument, otherwise
4791     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4792     //
4793     // template<typename T>
4794     // struct A {
4795     //   static int FooImpl();
4796     //
4797     //   template<typename Tp>
4798     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4799     //   // template argument list [[T], [Tp]], should be [[Tp]].
4800     //   friend A<Tp> Foo(int a);
4801     // };
4802     //
4803     // template<typename T>
4804     // A<T> Foo(int a = A<T>::FooImpl());
4805     MultiLevelTemplateArgumentList MutiLevelArgList
4806       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4807 
4808     InstantiatingTemplate Inst(*this, CallLoc, Param,
4809                                MutiLevelArgList.getInnermost());
4810     if (Inst.isInvalid())
4811       return true;
4812     if (Inst.isAlreadyInstantiating()) {
4813       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4814       Param->setInvalidDecl();
4815       return true;
4816     }
4817 
4818     ExprResult Result;
4819     {
4820       // C++ [dcl.fct.default]p5:
4821       //   The names in the [default argument] expression are bound, and
4822       //   the semantic constraints are checked, at the point where the
4823       //   default argument expression appears.
4824       ContextRAII SavedContext(*this, FD);
4825       LocalInstantiationScope Local(*this);
4826       runWithSufficientStackSpace(CallLoc, [&] {
4827         Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4828                                   /*DirectInit*/false);
4829       });
4830     }
4831     if (Result.isInvalid())
4832       return true;
4833 
4834     // Check the expression as an initializer for the parameter.
4835     InitializedEntity Entity
4836       = InitializedEntity::InitializeParameter(Context, Param);
4837     InitializationKind Kind = InitializationKind::CreateCopy(
4838         Param->getLocation(),
4839         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4840     Expr *ResultE = Result.getAs<Expr>();
4841 
4842     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4843     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4844     if (Result.isInvalid())
4845       return true;
4846 
4847     Result =
4848         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4849                             /*DiscardedValue*/ false);
4850     if (Result.isInvalid())
4851       return true;
4852 
4853     // Remember the instantiated default argument.
4854     Param->setDefaultArg(Result.getAs<Expr>());
4855     if (ASTMutationListener *L = getASTMutationListener()) {
4856       L->DefaultArgumentInstantiated(Param);
4857     }
4858   }
4859 
4860   // If the default argument expression is not set yet, we are building it now.
4861   if (!Param->hasInit()) {
4862     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4863     Param->setInvalidDecl();
4864     return true;
4865   }
4866 
4867   // If the default expression creates temporaries, we need to
4868   // push them to the current stack of expression temporaries so they'll
4869   // be properly destroyed.
4870   // FIXME: We should really be rebuilding the default argument with new
4871   // bound temporaries; see the comment in PR5810.
4872   // We don't need to do that with block decls, though, because
4873   // blocks in default argument expression can never capture anything.
4874   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4875     // Set the "needs cleanups" bit regardless of whether there are
4876     // any explicit objects.
4877     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4878 
4879     // Append all the objects to the cleanup list.  Right now, this
4880     // should always be a no-op, because blocks in default argument
4881     // expressions should never be able to capture anything.
4882     assert(!Init->getNumObjects() &&
4883            "default argument expression has capturing blocks?");
4884   }
4885 
4886   // We already type-checked the argument, so we know it works.
4887   // Just mark all of the declarations in this potentially-evaluated expression
4888   // as being "referenced".
4889   EnterExpressionEvaluationContext EvalContext(
4890       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4891   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4892                                    /*SkipLocalVariables=*/true);
4893   return false;
4894 }
4895 
4896 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4897                                         FunctionDecl *FD, ParmVarDecl *Param) {
4898   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4899     return ExprError();
4900   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4901 }
4902 
4903 Sema::VariadicCallType
4904 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4905                           Expr *Fn) {
4906   if (Proto && Proto->isVariadic()) {
4907     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4908       return VariadicConstructor;
4909     else if (Fn && Fn->getType()->isBlockPointerType())
4910       return VariadicBlock;
4911     else if (FDecl) {
4912       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4913         if (Method->isInstance())
4914           return VariadicMethod;
4915     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4916       return VariadicMethod;
4917     return VariadicFunction;
4918   }
4919   return VariadicDoesNotApply;
4920 }
4921 
4922 namespace {
4923 class FunctionCallCCC final : public FunctionCallFilterCCC {
4924 public:
4925   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4926                   unsigned NumArgs, MemberExpr *ME)
4927       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4928         FunctionName(FuncName) {}
4929 
4930   bool ValidateCandidate(const TypoCorrection &candidate) override {
4931     if (!candidate.getCorrectionSpecifier() ||
4932         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4933       return false;
4934     }
4935 
4936     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4937   }
4938 
4939   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4940     return std::make_unique<FunctionCallCCC>(*this);
4941   }
4942 
4943 private:
4944   const IdentifierInfo *const FunctionName;
4945 };
4946 }
4947 
4948 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4949                                                FunctionDecl *FDecl,
4950                                                ArrayRef<Expr *> Args) {
4951   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4952   DeclarationName FuncName = FDecl->getDeclName();
4953   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4954 
4955   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4956   if (TypoCorrection Corrected = S.CorrectTypo(
4957           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4958           S.getScopeForContext(S.CurContext), nullptr, CCC,
4959           Sema::CTK_ErrorRecovery)) {
4960     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4961       if (Corrected.isOverloaded()) {
4962         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4963         OverloadCandidateSet::iterator Best;
4964         for (NamedDecl *CD : Corrected) {
4965           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4966             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4967                                    OCS);
4968         }
4969         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4970         case OR_Success:
4971           ND = Best->FoundDecl;
4972           Corrected.setCorrectionDecl(ND);
4973           break;
4974         default:
4975           break;
4976         }
4977       }
4978       ND = ND->getUnderlyingDecl();
4979       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4980         return Corrected;
4981     }
4982   }
4983   return TypoCorrection();
4984 }
4985 
4986 /// ConvertArgumentsForCall - Converts the arguments specified in
4987 /// Args/NumArgs to the parameter types of the function FDecl with
4988 /// function prototype Proto. Call is the call expression itself, and
4989 /// Fn is the function expression. For a C++ member function, this
4990 /// routine does not attempt to convert the object argument. Returns
4991 /// true if the call is ill-formed.
4992 bool
4993 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4994                               FunctionDecl *FDecl,
4995                               const FunctionProtoType *Proto,
4996                               ArrayRef<Expr *> Args,
4997                               SourceLocation RParenLoc,
4998                               bool IsExecConfig) {
4999   // Bail out early if calling a builtin with custom typechecking.
5000   if (FDecl)
5001     if (unsigned ID = FDecl->getBuiltinID())
5002       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5003         return false;
5004 
5005   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5006   // assignment, to the types of the corresponding parameter, ...
5007   unsigned NumParams = Proto->getNumParams();
5008   bool Invalid = false;
5009   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5010   unsigned FnKind = Fn->getType()->isBlockPointerType()
5011                        ? 1 /* block */
5012                        : (IsExecConfig ? 3 /* kernel function (exec config) */
5013                                        : 0 /* function */);
5014 
5015   // If too few arguments are available (and we don't have default
5016   // arguments for the remaining parameters), don't make the call.
5017   if (Args.size() < NumParams) {
5018     if (Args.size() < MinArgs) {
5019       TypoCorrection TC;
5020       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5021         unsigned diag_id =
5022             MinArgs == NumParams && !Proto->isVariadic()
5023                 ? diag::err_typecheck_call_too_few_args_suggest
5024                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5025         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5026                                         << static_cast<unsigned>(Args.size())
5027                                         << TC.getCorrectionRange());
5028       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5029         Diag(RParenLoc,
5030              MinArgs == NumParams && !Proto->isVariadic()
5031                  ? diag::err_typecheck_call_too_few_args_one
5032                  : diag::err_typecheck_call_too_few_args_at_least_one)
5033             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5034       else
5035         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5036                             ? diag::err_typecheck_call_too_few_args
5037                             : diag::err_typecheck_call_too_few_args_at_least)
5038             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5039             << Fn->getSourceRange();
5040 
5041       // Emit the location of the prototype.
5042       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5043         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5044 
5045       return true;
5046     }
5047     // We reserve space for the default arguments when we create
5048     // the call expression, before calling ConvertArgumentsForCall.
5049     assert((Call->getNumArgs() == NumParams) &&
5050            "We should have reserved space for the default arguments before!");
5051   }
5052 
5053   // If too many are passed and not variadic, error on the extras and drop
5054   // them.
5055   if (Args.size() > NumParams) {
5056     if (!Proto->isVariadic()) {
5057       TypoCorrection TC;
5058       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5059         unsigned diag_id =
5060             MinArgs == NumParams && !Proto->isVariadic()
5061                 ? diag::err_typecheck_call_too_many_args_suggest
5062                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5063         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5064                                         << static_cast<unsigned>(Args.size())
5065                                         << TC.getCorrectionRange());
5066       } else if (NumParams == 1 && FDecl &&
5067                  FDecl->getParamDecl(0)->getDeclName())
5068         Diag(Args[NumParams]->getBeginLoc(),
5069              MinArgs == NumParams
5070                  ? diag::err_typecheck_call_too_many_args_one
5071                  : diag::err_typecheck_call_too_many_args_at_most_one)
5072             << FnKind << FDecl->getParamDecl(0)
5073             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5074             << SourceRange(Args[NumParams]->getBeginLoc(),
5075                            Args.back()->getEndLoc());
5076       else
5077         Diag(Args[NumParams]->getBeginLoc(),
5078              MinArgs == NumParams
5079                  ? diag::err_typecheck_call_too_many_args
5080                  : diag::err_typecheck_call_too_many_args_at_most)
5081             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5082             << Fn->getSourceRange()
5083             << SourceRange(Args[NumParams]->getBeginLoc(),
5084                            Args.back()->getEndLoc());
5085 
5086       // Emit the location of the prototype.
5087       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5088         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5089 
5090       // This deletes the extra arguments.
5091       Call->shrinkNumArgs(NumParams);
5092       return true;
5093     }
5094   }
5095   SmallVector<Expr *, 8> AllArgs;
5096   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5097 
5098   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5099                                    AllArgs, CallType);
5100   if (Invalid)
5101     return true;
5102   unsigned TotalNumArgs = AllArgs.size();
5103   for (unsigned i = 0; i < TotalNumArgs; ++i)
5104     Call->setArg(i, AllArgs[i]);
5105 
5106   return false;
5107 }
5108 
5109 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5110                                   const FunctionProtoType *Proto,
5111                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5112                                   SmallVectorImpl<Expr *> &AllArgs,
5113                                   VariadicCallType CallType, bool AllowExplicit,
5114                                   bool IsListInitialization) {
5115   unsigned NumParams = Proto->getNumParams();
5116   bool Invalid = false;
5117   size_t ArgIx = 0;
5118   // Continue to check argument types (even if we have too few/many args).
5119   for (unsigned i = FirstParam; i < NumParams; i++) {
5120     QualType ProtoArgType = Proto->getParamType(i);
5121 
5122     Expr *Arg;
5123     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5124     if (ArgIx < Args.size()) {
5125       Arg = Args[ArgIx++];
5126 
5127       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5128                               diag::err_call_incomplete_argument, Arg))
5129         return true;
5130 
5131       // Strip the unbridged-cast placeholder expression off, if applicable.
5132       bool CFAudited = false;
5133       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5134           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5135           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5136         Arg = stripARCUnbridgedCast(Arg);
5137       else if (getLangOpts().ObjCAutoRefCount &&
5138                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5139                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5140         CFAudited = true;
5141 
5142       if (Proto->getExtParameterInfo(i).isNoEscape())
5143         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5144           BE->getBlockDecl()->setDoesNotEscape();
5145 
5146       InitializedEntity Entity =
5147           Param ? InitializedEntity::InitializeParameter(Context, Param,
5148                                                          ProtoArgType)
5149                 : InitializedEntity::InitializeParameter(
5150                       Context, ProtoArgType, Proto->isParamConsumed(i));
5151 
5152       // Remember that parameter belongs to a CF audited API.
5153       if (CFAudited)
5154         Entity.setParameterCFAudited();
5155 
5156       ExprResult ArgE = PerformCopyInitialization(
5157           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5158       if (ArgE.isInvalid())
5159         return true;
5160 
5161       Arg = ArgE.getAs<Expr>();
5162     } else {
5163       assert(Param && "can't use default arguments without a known callee");
5164 
5165       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5166       if (ArgExpr.isInvalid())
5167         return true;
5168 
5169       Arg = ArgExpr.getAs<Expr>();
5170     }
5171 
5172     // Check for array bounds violations for each argument to the call. This
5173     // check only triggers warnings when the argument isn't a more complex Expr
5174     // with its own checking, such as a BinaryOperator.
5175     CheckArrayAccess(Arg);
5176 
5177     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5178     CheckStaticArrayArgument(CallLoc, Param, Arg);
5179 
5180     AllArgs.push_back(Arg);
5181   }
5182 
5183   // If this is a variadic call, handle args passed through "...".
5184   if (CallType != VariadicDoesNotApply) {
5185     // Assume that extern "C" functions with variadic arguments that
5186     // return __unknown_anytype aren't *really* variadic.
5187     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5188         FDecl->isExternC()) {
5189       for (Expr *A : Args.slice(ArgIx)) {
5190         QualType paramType; // ignored
5191         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5192         Invalid |= arg.isInvalid();
5193         AllArgs.push_back(arg.get());
5194       }
5195 
5196     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5197     } else {
5198       for (Expr *A : Args.slice(ArgIx)) {
5199         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5200         Invalid |= Arg.isInvalid();
5201         AllArgs.push_back(Arg.get());
5202       }
5203     }
5204 
5205     // Check for array bounds violations.
5206     for (Expr *A : Args.slice(ArgIx))
5207       CheckArrayAccess(A);
5208   }
5209   return Invalid;
5210 }
5211 
5212 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5213   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5214   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5215     TL = DTL.getOriginalLoc();
5216   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5217     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5218       << ATL.getLocalSourceRange();
5219 }
5220 
5221 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5222 /// array parameter, check that it is non-null, and that if it is formed by
5223 /// array-to-pointer decay, the underlying array is sufficiently large.
5224 ///
5225 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5226 /// array type derivation, then for each call to the function, the value of the
5227 /// corresponding actual argument shall provide access to the first element of
5228 /// an array with at least as many elements as specified by the size expression.
5229 void
5230 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5231                                ParmVarDecl *Param,
5232                                const Expr *ArgExpr) {
5233   // Static array parameters are not supported in C++.
5234   if (!Param || getLangOpts().CPlusPlus)
5235     return;
5236 
5237   QualType OrigTy = Param->getOriginalType();
5238 
5239   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5240   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5241     return;
5242 
5243   if (ArgExpr->isNullPointerConstant(Context,
5244                                      Expr::NPC_NeverValueDependent)) {
5245     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5246     DiagnoseCalleeStaticArrayParam(*this, Param);
5247     return;
5248   }
5249 
5250   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5251   if (!CAT)
5252     return;
5253 
5254   const ConstantArrayType *ArgCAT =
5255     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5256   if (!ArgCAT)
5257     return;
5258 
5259   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5260                                              ArgCAT->getElementType())) {
5261     if (ArgCAT->getSize().ult(CAT->getSize())) {
5262       Diag(CallLoc, diag::warn_static_array_too_small)
5263           << ArgExpr->getSourceRange()
5264           << (unsigned)ArgCAT->getSize().getZExtValue()
5265           << (unsigned)CAT->getSize().getZExtValue() << 0;
5266       DiagnoseCalleeStaticArrayParam(*this, Param);
5267     }
5268     return;
5269   }
5270 
5271   Optional<CharUnits> ArgSize =
5272       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5273   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5274   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5275     Diag(CallLoc, diag::warn_static_array_too_small)
5276         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5277         << (unsigned)ParmSize->getQuantity() << 1;
5278     DiagnoseCalleeStaticArrayParam(*this, Param);
5279   }
5280 }
5281 
5282 /// Given a function expression of unknown-any type, try to rebuild it
5283 /// to have a function type.
5284 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5285 
5286 /// Is the given type a placeholder that we need to lower out
5287 /// immediately during argument processing?
5288 static bool isPlaceholderToRemoveAsArg(QualType type) {
5289   // Placeholders are never sugared.
5290   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5291   if (!placeholder) return false;
5292 
5293   switch (placeholder->getKind()) {
5294   // Ignore all the non-placeholder types.
5295 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5296   case BuiltinType::Id:
5297 #include "clang/Basic/OpenCLImageTypes.def"
5298 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5299   case BuiltinType::Id:
5300 #include "clang/Basic/OpenCLExtensionTypes.def"
5301   // In practice we'll never use this, since all SVE types are sugared
5302   // via TypedefTypes rather than exposed directly as BuiltinTypes.
5303 #define SVE_TYPE(Name, Id, SingletonId) \
5304   case BuiltinType::Id:
5305 #include "clang/Basic/AArch64SVEACLETypes.def"
5306 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5307 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5308 #include "clang/AST/BuiltinTypes.def"
5309     return false;
5310 
5311   // We cannot lower out overload sets; they might validly be resolved
5312   // by the call machinery.
5313   case BuiltinType::Overload:
5314     return false;
5315 
5316   // Unbridged casts in ARC can be handled in some call positions and
5317   // should be left in place.
5318   case BuiltinType::ARCUnbridgedCast:
5319     return false;
5320 
5321   // Pseudo-objects should be converted as soon as possible.
5322   case BuiltinType::PseudoObject:
5323     return true;
5324 
5325   // The debugger mode could theoretically but currently does not try
5326   // to resolve unknown-typed arguments based on known parameter types.
5327   case BuiltinType::UnknownAny:
5328     return true;
5329 
5330   // These are always invalid as call arguments and should be reported.
5331   case BuiltinType::BoundMember:
5332   case BuiltinType::BuiltinFn:
5333   case BuiltinType::OMPArraySection:
5334     return true;
5335 
5336   }
5337   llvm_unreachable("bad builtin type kind");
5338 }
5339 
5340 /// Check an argument list for placeholders that we won't try to
5341 /// handle later.
5342 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5343   // Apply this processing to all the arguments at once instead of
5344   // dying at the first failure.
5345   bool hasInvalid = false;
5346   for (size_t i = 0, e = args.size(); i != e; i++) {
5347     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5348       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5349       if (result.isInvalid()) hasInvalid = true;
5350       else args[i] = result.get();
5351     } else if (hasInvalid) {
5352       (void)S.CorrectDelayedTyposInExpr(args[i]);
5353     }
5354   }
5355   return hasInvalid;
5356 }
5357 
5358 /// If a builtin function has a pointer argument with no explicit address
5359 /// space, then it should be able to accept a pointer to any address
5360 /// space as input.  In order to do this, we need to replace the
5361 /// standard builtin declaration with one that uses the same address space
5362 /// as the call.
5363 ///
5364 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5365 ///                  it does not contain any pointer arguments without
5366 ///                  an address space qualifer.  Otherwise the rewritten
5367 ///                  FunctionDecl is returned.
5368 /// TODO: Handle pointer return types.
5369 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5370                                                 FunctionDecl *FDecl,
5371                                                 MultiExprArg ArgExprs) {
5372 
5373   QualType DeclType = FDecl->getType();
5374   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5375 
5376   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5377       ArgExprs.size() < FT->getNumParams())
5378     return nullptr;
5379 
5380   bool NeedsNewDecl = false;
5381   unsigned i = 0;
5382   SmallVector<QualType, 8> OverloadParams;
5383 
5384   for (QualType ParamType : FT->param_types()) {
5385 
5386     // Convert array arguments to pointer to simplify type lookup.
5387     ExprResult ArgRes =
5388         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5389     if (ArgRes.isInvalid())
5390       return nullptr;
5391     Expr *Arg = ArgRes.get();
5392     QualType ArgType = Arg->getType();
5393     if (!ParamType->isPointerType() ||
5394         ParamType.getQualifiers().hasAddressSpace() ||
5395         !ArgType->isPointerType() ||
5396         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5397       OverloadParams.push_back(ParamType);
5398       continue;
5399     }
5400 
5401     QualType PointeeType = ParamType->getPointeeType();
5402     if (PointeeType.getQualifiers().hasAddressSpace())
5403       continue;
5404 
5405     NeedsNewDecl = true;
5406     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5407 
5408     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5409     OverloadParams.push_back(Context.getPointerType(PointeeType));
5410   }
5411 
5412   if (!NeedsNewDecl)
5413     return nullptr;
5414 
5415   FunctionProtoType::ExtProtoInfo EPI;
5416   EPI.Variadic = FT->isVariadic();
5417   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5418                                                 OverloadParams, EPI);
5419   DeclContext *Parent = FDecl->getParent();
5420   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5421                                                     FDecl->getLocation(),
5422                                                     FDecl->getLocation(),
5423                                                     FDecl->getIdentifier(),
5424                                                     OverloadTy,
5425                                                     /*TInfo=*/nullptr,
5426                                                     SC_Extern, false,
5427                                                     /*hasPrototype=*/true);
5428   SmallVector<ParmVarDecl*, 16> Params;
5429   FT = cast<FunctionProtoType>(OverloadTy);
5430   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5431     QualType ParamType = FT->getParamType(i);
5432     ParmVarDecl *Parm =
5433         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5434                                 SourceLocation(), nullptr, ParamType,
5435                                 /*TInfo=*/nullptr, SC_None, nullptr);
5436     Parm->setScopeInfo(0, i);
5437     Params.push_back(Parm);
5438   }
5439   OverloadDecl->setParams(Params);
5440   return OverloadDecl;
5441 }
5442 
5443 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5444                                     FunctionDecl *Callee,
5445                                     MultiExprArg ArgExprs) {
5446   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5447   // similar attributes) really don't like it when functions are called with an
5448   // invalid number of args.
5449   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5450                          /*PartialOverloading=*/false) &&
5451       !Callee->isVariadic())
5452     return;
5453   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5454     return;
5455 
5456   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5457     S.Diag(Fn->getBeginLoc(),
5458            isa<CXXMethodDecl>(Callee)
5459                ? diag::err_ovl_no_viable_member_function_in_call
5460                : diag::err_ovl_no_viable_function_in_call)
5461         << Callee << Callee->getSourceRange();
5462     S.Diag(Callee->getLocation(),
5463            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5464         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5465     return;
5466   }
5467 }
5468 
5469 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5470     const UnresolvedMemberExpr *const UME, Sema &S) {
5471 
5472   const auto GetFunctionLevelDCIfCXXClass =
5473       [](Sema &S) -> const CXXRecordDecl * {
5474     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5475     if (!DC || !DC->getParent())
5476       return nullptr;
5477 
5478     // If the call to some member function was made from within a member
5479     // function body 'M' return return 'M's parent.
5480     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5481       return MD->getParent()->getCanonicalDecl();
5482     // else the call was made from within a default member initializer of a
5483     // class, so return the class.
5484     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5485       return RD->getCanonicalDecl();
5486     return nullptr;
5487   };
5488   // If our DeclContext is neither a member function nor a class (in the
5489   // case of a lambda in a default member initializer), we can't have an
5490   // enclosing 'this'.
5491 
5492   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5493   if (!CurParentClass)
5494     return false;
5495 
5496   // The naming class for implicit member functions call is the class in which
5497   // name lookup starts.
5498   const CXXRecordDecl *const NamingClass =
5499       UME->getNamingClass()->getCanonicalDecl();
5500   assert(NamingClass && "Must have naming class even for implicit access");
5501 
5502   // If the unresolved member functions were found in a 'naming class' that is
5503   // related (either the same or derived from) to the class that contains the
5504   // member function that itself contained the implicit member access.
5505 
5506   return CurParentClass == NamingClass ||
5507          CurParentClass->isDerivedFrom(NamingClass);
5508 }
5509 
5510 static void
5511 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5512     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5513 
5514   if (!UME)
5515     return;
5516 
5517   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5518   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5519   // already been captured, or if this is an implicit member function call (if
5520   // it isn't, an attempt to capture 'this' should already have been made).
5521   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5522       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5523     return;
5524 
5525   // Check if the naming class in which the unresolved members were found is
5526   // related (same as or is a base of) to the enclosing class.
5527 
5528   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5529     return;
5530 
5531 
5532   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5533   // If the enclosing function is not dependent, then this lambda is
5534   // capture ready, so if we can capture this, do so.
5535   if (!EnclosingFunctionCtx->isDependentContext()) {
5536     // If the current lambda and all enclosing lambdas can capture 'this' -
5537     // then go ahead and capture 'this' (since our unresolved overload set
5538     // contains at least one non-static member function).
5539     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5540       S.CheckCXXThisCapture(CallLoc);
5541   } else if (S.CurContext->isDependentContext()) {
5542     // ... since this is an implicit member reference, that might potentially
5543     // involve a 'this' capture, mark 'this' for potential capture in
5544     // enclosing lambdas.
5545     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5546       CurLSI->addPotentialThisCapture(CallLoc);
5547   }
5548 }
5549 
5550 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5551                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5552                                Expr *ExecConfig) {
5553   ExprResult Call =
5554       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5555   if (Call.isInvalid())
5556     return Call;
5557 
5558   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5559   // language modes.
5560   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5561     if (ULE->hasExplicitTemplateArgs() &&
5562         ULE->decls_begin() == ULE->decls_end()) {
5563       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5564                                  ? diag::warn_cxx17_compat_adl_only_template_id
5565                                  : diag::ext_adl_only_template_id)
5566           << ULE->getName();
5567     }
5568   }
5569 
5570   return Call;
5571 }
5572 
5573 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5574 /// This provides the location of the left/right parens and a list of comma
5575 /// locations.
5576 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5577                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5578                                Expr *ExecConfig, bool IsExecConfig) {
5579   // Since this might be a postfix expression, get rid of ParenListExprs.
5580   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5581   if (Result.isInvalid()) return ExprError();
5582   Fn = Result.get();
5583 
5584   if (checkArgsForPlaceholders(*this, ArgExprs))
5585     return ExprError();
5586 
5587   if (getLangOpts().CPlusPlus) {
5588     // If this is a pseudo-destructor expression, build the call immediately.
5589     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5590       if (!ArgExprs.empty()) {
5591         // Pseudo-destructor calls should not have any arguments.
5592         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5593             << FixItHint::CreateRemoval(
5594                    SourceRange(ArgExprs.front()->getBeginLoc(),
5595                                ArgExprs.back()->getEndLoc()));
5596       }
5597 
5598       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5599                               VK_RValue, RParenLoc);
5600     }
5601     if (Fn->getType() == Context.PseudoObjectTy) {
5602       ExprResult result = CheckPlaceholderExpr(Fn);
5603       if (result.isInvalid()) return ExprError();
5604       Fn = result.get();
5605     }
5606 
5607     // Determine whether this is a dependent call inside a C++ template,
5608     // in which case we won't do any semantic analysis now.
5609     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5610       if (ExecConfig) {
5611         return CUDAKernelCallExpr::Create(
5612             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5613             Context.DependentTy, VK_RValue, RParenLoc);
5614       } else {
5615 
5616         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5617             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5618             Fn->getBeginLoc());
5619 
5620         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5621                                 VK_RValue, RParenLoc);
5622       }
5623     }
5624 
5625     // Determine whether this is a call to an object (C++ [over.call.object]).
5626     if (Fn->getType()->isRecordType())
5627       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5628                                           RParenLoc);
5629 
5630     if (Fn->getType() == Context.UnknownAnyTy) {
5631       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5632       if (result.isInvalid()) return ExprError();
5633       Fn = result.get();
5634     }
5635 
5636     if (Fn->getType() == Context.BoundMemberTy) {
5637       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5638                                        RParenLoc);
5639     }
5640   }
5641 
5642   // Check for overloaded calls.  This can happen even in C due to extensions.
5643   if (Fn->getType() == Context.OverloadTy) {
5644     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5645 
5646     // We aren't supposed to apply this logic if there's an '&' involved.
5647     if (!find.HasFormOfMemberPointer) {
5648       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5649         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5650                                 VK_RValue, RParenLoc);
5651       OverloadExpr *ovl = find.Expression;
5652       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5653         return BuildOverloadedCallExpr(
5654             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5655             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5656       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5657                                        RParenLoc);
5658     }
5659   }
5660 
5661   // If we're directly calling a function, get the appropriate declaration.
5662   if (Fn->getType() == Context.UnknownAnyTy) {
5663     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5664     if (result.isInvalid()) return ExprError();
5665     Fn = result.get();
5666   }
5667 
5668   Expr *NakedFn = Fn->IgnoreParens();
5669 
5670   bool CallingNDeclIndirectly = false;
5671   NamedDecl *NDecl = nullptr;
5672   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5673     if (UnOp->getOpcode() == UO_AddrOf) {
5674       CallingNDeclIndirectly = true;
5675       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5676     }
5677   }
5678 
5679   if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5680     NDecl = DRE->getDecl();
5681 
5682     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5683     if (FDecl && FDecl->getBuiltinID()) {
5684       // Rewrite the function decl for this builtin by replacing parameters
5685       // with no explicit address space with the address space of the arguments
5686       // in ArgExprs.
5687       if ((FDecl =
5688                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5689         NDecl = FDecl;
5690         Fn = DeclRefExpr::Create(
5691             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5692             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5693             nullptr, DRE->isNonOdrUse());
5694       }
5695     }
5696   } else if (isa<MemberExpr>(NakedFn))
5697     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5698 
5699   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5700     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5701                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5702       return ExprError();
5703 
5704     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5705       return ExprError();
5706 
5707     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5708   }
5709 
5710   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5711                                ExecConfig, IsExecConfig);
5712 }
5713 
5714 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5715 ///
5716 /// __builtin_astype( value, dst type )
5717 ///
5718 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5719                                  SourceLocation BuiltinLoc,
5720                                  SourceLocation RParenLoc) {
5721   ExprValueKind VK = VK_RValue;
5722   ExprObjectKind OK = OK_Ordinary;
5723   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5724   QualType SrcTy = E->getType();
5725   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5726     return ExprError(Diag(BuiltinLoc,
5727                           diag::err_invalid_astype_of_different_size)
5728                      << DstTy
5729                      << SrcTy
5730                      << E->getSourceRange());
5731   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5732 }
5733 
5734 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5735 /// provided arguments.
5736 ///
5737 /// __builtin_convertvector( value, dst type )
5738 ///
5739 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5740                                         SourceLocation BuiltinLoc,
5741                                         SourceLocation RParenLoc) {
5742   TypeSourceInfo *TInfo;
5743   GetTypeFromParser(ParsedDestTy, &TInfo);
5744   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5745 }
5746 
5747 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5748 /// i.e. an expression not of \p OverloadTy.  The expression should
5749 /// unary-convert to an expression of function-pointer or
5750 /// block-pointer type.
5751 ///
5752 /// \param NDecl the declaration being called, if available
5753 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5754                                        SourceLocation LParenLoc,
5755                                        ArrayRef<Expr *> Args,
5756                                        SourceLocation RParenLoc, Expr *Config,
5757                                        bool IsExecConfig, ADLCallKind UsesADL) {
5758   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5759   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5760 
5761   // Functions with 'interrupt' attribute cannot be called directly.
5762   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5763     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5764     return ExprError();
5765   }
5766 
5767   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5768   // so there's some risk when calling out to non-interrupt handler functions
5769   // that the callee might not preserve them. This is easy to diagnose here,
5770   // but can be very challenging to debug.
5771   if (auto *Caller = getCurFunctionDecl())
5772     if (Caller->hasAttr<ARMInterruptAttr>()) {
5773       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5774       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5775         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5776     }
5777 
5778   // Promote the function operand.
5779   // We special-case function promotion here because we only allow promoting
5780   // builtin functions to function pointers in the callee of a call.
5781   ExprResult Result;
5782   QualType ResultTy;
5783   if (BuiltinID &&
5784       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5785     // Extract the return type from the (builtin) function pointer type.
5786     // FIXME Several builtins still have setType in
5787     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5788     // Builtins.def to ensure they are correct before removing setType calls.
5789     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5790     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5791     ResultTy = FDecl->getCallResultType();
5792   } else {
5793     Result = CallExprUnaryConversions(Fn);
5794     ResultTy = Context.BoolTy;
5795   }
5796   if (Result.isInvalid())
5797     return ExprError();
5798   Fn = Result.get();
5799 
5800   // Check for a valid function type, but only if it is not a builtin which
5801   // requires custom type checking. These will be handled by
5802   // CheckBuiltinFunctionCall below just after creation of the call expression.
5803   const FunctionType *FuncT = nullptr;
5804   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5805   retry:
5806     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5807       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5808       // have type pointer to function".
5809       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5810       if (!FuncT)
5811         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5812                          << Fn->getType() << Fn->getSourceRange());
5813     } else if (const BlockPointerType *BPT =
5814                    Fn->getType()->getAs<BlockPointerType>()) {
5815       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5816     } else {
5817       // Handle calls to expressions of unknown-any type.
5818       if (Fn->getType() == Context.UnknownAnyTy) {
5819         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5820         if (rewrite.isInvalid())
5821           return ExprError();
5822         Fn = rewrite.get();
5823         goto retry;
5824       }
5825 
5826       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5827                        << Fn->getType() << Fn->getSourceRange());
5828     }
5829   }
5830 
5831   // Get the number of parameters in the function prototype, if any.
5832   // We will allocate space for max(Args.size(), NumParams) arguments
5833   // in the call expression.
5834   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5835   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5836 
5837   CallExpr *TheCall;
5838   if (Config) {
5839     assert(UsesADL == ADLCallKind::NotADL &&
5840            "CUDAKernelCallExpr should not use ADL");
5841     TheCall =
5842         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5843                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5844   } else {
5845     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5846                                RParenLoc, NumParams, UsesADL);
5847   }
5848 
5849   if (!getLangOpts().CPlusPlus) {
5850     // Forget about the nulled arguments since typo correction
5851     // do not handle them well.
5852     TheCall->shrinkNumArgs(Args.size());
5853     // C cannot always handle TypoExpr nodes in builtin calls and direct
5854     // function calls as their argument checking don't necessarily handle
5855     // dependent types properly, so make sure any TypoExprs have been
5856     // dealt with.
5857     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5858     if (!Result.isUsable()) return ExprError();
5859     CallExpr *TheOldCall = TheCall;
5860     TheCall = dyn_cast<CallExpr>(Result.get());
5861     bool CorrectedTypos = TheCall != TheOldCall;
5862     if (!TheCall) return Result;
5863     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5864 
5865     // A new call expression node was created if some typos were corrected.
5866     // However it may not have been constructed with enough storage. In this
5867     // case, rebuild the node with enough storage. The waste of space is
5868     // immaterial since this only happens when some typos were corrected.
5869     if (CorrectedTypos && Args.size() < NumParams) {
5870       if (Config)
5871         TheCall = CUDAKernelCallExpr::Create(
5872             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5873             RParenLoc, NumParams);
5874       else
5875         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5876                                    RParenLoc, NumParams, UsesADL);
5877     }
5878     // We can now handle the nulled arguments for the default arguments.
5879     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5880   }
5881 
5882   // Bail out early if calling a builtin with custom type checking.
5883   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5884     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5885 
5886   if (getLangOpts().CUDA) {
5887     if (Config) {
5888       // CUDA: Kernel calls must be to global functions
5889       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5890         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5891             << FDecl << Fn->getSourceRange());
5892 
5893       // CUDA: Kernel function must have 'void' return type
5894       if (!FuncT->getReturnType()->isVoidType())
5895         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5896             << Fn->getType() << Fn->getSourceRange());
5897     } else {
5898       // CUDA: Calls to global functions must be configured
5899       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5900         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5901             << FDecl << Fn->getSourceRange());
5902     }
5903   }
5904 
5905   // Check for a valid return type
5906   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5907                           FDecl))
5908     return ExprError();
5909 
5910   // We know the result type of the call, set it.
5911   TheCall->setType(FuncT->getCallResultType(Context));
5912   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5913 
5914   if (Proto) {
5915     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5916                                 IsExecConfig))
5917       return ExprError();
5918   } else {
5919     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5920 
5921     if (FDecl) {
5922       // Check if we have too few/too many template arguments, based
5923       // on our knowledge of the function definition.
5924       const FunctionDecl *Def = nullptr;
5925       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5926         Proto = Def->getType()->getAs<FunctionProtoType>();
5927        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5928           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5929           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5930       }
5931 
5932       // If the function we're calling isn't a function prototype, but we have
5933       // a function prototype from a prior declaratiom, use that prototype.
5934       if (!FDecl->hasPrototype())
5935         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5936     }
5937 
5938     // Promote the arguments (C99 6.5.2.2p6).
5939     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5940       Expr *Arg = Args[i];
5941 
5942       if (Proto && i < Proto->getNumParams()) {
5943         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5944             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5945         ExprResult ArgE =
5946             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5947         if (ArgE.isInvalid())
5948           return true;
5949 
5950         Arg = ArgE.getAs<Expr>();
5951 
5952       } else {
5953         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5954 
5955         if (ArgE.isInvalid())
5956           return true;
5957 
5958         Arg = ArgE.getAs<Expr>();
5959       }
5960 
5961       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5962                               diag::err_call_incomplete_argument, Arg))
5963         return ExprError();
5964 
5965       TheCall->setArg(i, Arg);
5966     }
5967   }
5968 
5969   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5970     if (!Method->isStatic())
5971       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5972         << Fn->getSourceRange());
5973 
5974   // Check for sentinels
5975   if (NDecl)
5976     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5977 
5978   // Do special checking on direct calls to functions.
5979   if (FDecl) {
5980     if (CheckFunctionCall(FDecl, TheCall, Proto))
5981       return ExprError();
5982 
5983     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5984 
5985     if (BuiltinID)
5986       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5987   } else if (NDecl) {
5988     if (CheckPointerCall(NDecl, TheCall, Proto))
5989       return ExprError();
5990   } else {
5991     if (CheckOtherCall(TheCall, Proto))
5992       return ExprError();
5993   }
5994 
5995   return MaybeBindToTemporary(TheCall);
5996 }
5997 
5998 ExprResult
5999 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6000                            SourceLocation RParenLoc, Expr *InitExpr) {
6001   assert(Ty && "ActOnCompoundLiteral(): missing type");
6002   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6003 
6004   TypeSourceInfo *TInfo;
6005   QualType literalType = GetTypeFromParser(Ty, &TInfo);
6006   if (!TInfo)
6007     TInfo = Context.getTrivialTypeSourceInfo(literalType);
6008 
6009   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6010 }
6011 
6012 ExprResult
6013 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6014                                SourceLocation RParenLoc, Expr *LiteralExpr) {
6015   QualType literalType = TInfo->getType();
6016 
6017   if (literalType->isArrayType()) {
6018     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6019           diag::err_illegal_decl_array_incomplete_type,
6020           SourceRange(LParenLoc,
6021                       LiteralExpr->getSourceRange().getEnd())))
6022       return ExprError();
6023     if (literalType->isVariableArrayType())
6024       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6025         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6026   } else if (!literalType->isDependentType() &&
6027              RequireCompleteType(LParenLoc, literalType,
6028                diag::err_typecheck_decl_incomplete_type,
6029                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6030     return ExprError();
6031 
6032   InitializedEntity Entity
6033     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6034   InitializationKind Kind
6035     = InitializationKind::CreateCStyleCast(LParenLoc,
6036                                            SourceRange(LParenLoc, RParenLoc),
6037                                            /*InitList=*/true);
6038   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6039   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6040                                       &literalType);
6041   if (Result.isInvalid())
6042     return ExprError();
6043   LiteralExpr = Result.get();
6044 
6045   bool isFileScope = !CurContext->isFunctionOrMethod();
6046 
6047   // In C, compound literals are l-values for some reason.
6048   // For GCC compatibility, in C++, file-scope array compound literals with
6049   // constant initializers are also l-values, and compound literals are
6050   // otherwise prvalues.
6051   //
6052   // (GCC also treats C++ list-initialized file-scope array prvalues with
6053   // constant initializers as l-values, but that's non-conforming, so we don't
6054   // follow it there.)
6055   //
6056   // FIXME: It would be better to handle the lvalue cases as materializing and
6057   // lifetime-extending a temporary object, but our materialized temporaries
6058   // representation only supports lifetime extension from a variable, not "out
6059   // of thin air".
6060   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6061   // is bound to the result of applying array-to-pointer decay to the compound
6062   // literal.
6063   // FIXME: GCC supports compound literals of reference type, which should
6064   // obviously have a value kind derived from the kind of reference involved.
6065   ExprValueKind VK =
6066       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6067           ? VK_RValue
6068           : VK_LValue;
6069 
6070   if (isFileScope)
6071     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6072       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6073         Expr *Init = ILE->getInit(i);
6074         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6075       }
6076 
6077   auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6078                                               VK, LiteralExpr, isFileScope);
6079   if (isFileScope) {
6080     if (!LiteralExpr->isTypeDependent() &&
6081         !LiteralExpr->isValueDependent() &&
6082         !literalType->isDependentType()) // C99 6.5.2.5p3
6083       if (CheckForConstantInitializer(LiteralExpr, literalType))
6084         return ExprError();
6085   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6086              literalType.getAddressSpace() != LangAS::Default) {
6087     // Embedded-C extensions to C99 6.5.2.5:
6088     //   "If the compound literal occurs inside the body of a function, the
6089     //   type name shall not be qualified by an address-space qualifier."
6090     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6091       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6092     return ExprError();
6093   }
6094 
6095   // Compound literals that have automatic storage duration are destroyed at
6096   // the end of the scope. Emit diagnostics if it is or contains a C union type
6097   // that is non-trivial to destruct.
6098   if (!isFileScope)
6099     if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6100       checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6101                             NTCUC_CompoundLiteral, NTCUK_Destruct);
6102 
6103   if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6104       E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6105     checkNonTrivialCUnionInInitializer(E->getInitializer(),
6106                                        E->getInitializer()->getExprLoc());
6107 
6108   return MaybeBindToTemporary(E);
6109 }
6110 
6111 ExprResult
6112 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6113                     SourceLocation RBraceLoc) {
6114   // Only produce each kind of designated initialization diagnostic once.
6115   SourceLocation FirstDesignator;
6116   bool DiagnosedArrayDesignator = false;
6117   bool DiagnosedNestedDesignator = false;
6118   bool DiagnosedMixedDesignator = false;
6119 
6120   // Check that any designated initializers are syntactically valid in the
6121   // current language mode.
6122   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6123     if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6124       if (FirstDesignator.isInvalid())
6125         FirstDesignator = DIE->getBeginLoc();
6126 
6127       if (!getLangOpts().CPlusPlus)
6128         break;
6129 
6130       if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6131         DiagnosedNestedDesignator = true;
6132         Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6133           << DIE->getDesignatorsSourceRange();
6134       }
6135 
6136       for (auto &Desig : DIE->designators()) {
6137         if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6138           DiagnosedArrayDesignator = true;
6139           Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6140             << Desig.getSourceRange();
6141         }
6142       }
6143 
6144       if (!DiagnosedMixedDesignator &&
6145           !isa<DesignatedInitExpr>(InitArgList[0])) {
6146         DiagnosedMixedDesignator = true;
6147         Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6148           << DIE->getSourceRange();
6149         Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6150           << InitArgList[0]->getSourceRange();
6151       }
6152     } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6153                isa<DesignatedInitExpr>(InitArgList[0])) {
6154       DiagnosedMixedDesignator = true;
6155       auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6156       Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6157         << DIE->getSourceRange();
6158       Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6159         << InitArgList[I]->getSourceRange();
6160     }
6161   }
6162 
6163   if (FirstDesignator.isValid()) {
6164     // Only diagnose designated initiaization as a C++20 extension if we didn't
6165     // already diagnose use of (non-C++20) C99 designator syntax.
6166     if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6167         !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6168       Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6169                                 ? diag::warn_cxx17_compat_designated_init
6170                                 : diag::ext_cxx_designated_init);
6171     } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6172       Diag(FirstDesignator, diag::ext_designated_init);
6173     }
6174   }
6175 
6176   return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6177 }
6178 
6179 ExprResult
6180 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6181                     SourceLocation RBraceLoc) {
6182   // Semantic analysis for initializers is done by ActOnDeclarator() and
6183   // CheckInitializer() - it requires knowledge of the object being initialized.
6184 
6185   // Immediately handle non-overload placeholders.  Overloads can be
6186   // resolved contextually, but everything else here can't.
6187   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6188     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6189       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6190 
6191       // Ignore failures; dropping the entire initializer list because
6192       // of one failure would be terrible for indexing/etc.
6193       if (result.isInvalid()) continue;
6194 
6195       InitArgList[I] = result.get();
6196     }
6197   }
6198 
6199   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6200                                                RBraceLoc);
6201   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6202   return E;
6203 }
6204 
6205 /// Do an explicit extend of the given block pointer if we're in ARC.
6206 void Sema::maybeExtendBlockObject(ExprResult &E) {
6207   assert(E.get()->getType()->isBlockPointerType());
6208   assert(E.get()->isRValue());
6209 
6210   // Only do this in an r-value context.
6211   if (!getLangOpts().ObjCAutoRefCount) return;
6212 
6213   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6214                                CK_ARCExtendBlockObject, E.get(),
6215                                /*base path*/ nullptr, VK_RValue);
6216   Cleanup.setExprNeedsCleanups(true);
6217 }
6218 
6219 /// Prepare a conversion of the given expression to an ObjC object
6220 /// pointer type.
6221 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6222   QualType type = E.get()->getType();
6223   if (type->isObjCObjectPointerType()) {
6224     return CK_BitCast;
6225   } else if (type->isBlockPointerType()) {
6226     maybeExtendBlockObject(E);
6227     return CK_BlockPointerToObjCPointerCast;
6228   } else {
6229     assert(type->isPointerType());
6230     return CK_CPointerToObjCPointerCast;
6231   }
6232 }
6233 
6234 /// Prepares for a scalar cast, performing all the necessary stages
6235 /// except the final cast and returning the kind required.
6236 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6237   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6238   // Also, callers should have filtered out the invalid cases with
6239   // pointers.  Everything else should be possible.
6240 
6241   QualType SrcTy = Src.get()->getType();
6242   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6243     return CK_NoOp;
6244 
6245   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6246   case Type::STK_MemberPointer:
6247     llvm_unreachable("member pointer type in C");
6248 
6249   case Type::STK_CPointer:
6250   case Type::STK_BlockPointer:
6251   case Type::STK_ObjCObjectPointer:
6252     switch (DestTy->getScalarTypeKind()) {
6253     case Type::STK_CPointer: {
6254       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6255       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6256       if (SrcAS != DestAS)
6257         return CK_AddressSpaceConversion;
6258       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6259         return CK_NoOp;
6260       return CK_BitCast;
6261     }
6262     case Type::STK_BlockPointer:
6263       return (SrcKind == Type::STK_BlockPointer
6264                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6265     case Type::STK_ObjCObjectPointer:
6266       if (SrcKind == Type::STK_ObjCObjectPointer)
6267         return CK_BitCast;
6268       if (SrcKind == Type::STK_CPointer)
6269         return CK_CPointerToObjCPointerCast;
6270       maybeExtendBlockObject(Src);
6271       return CK_BlockPointerToObjCPointerCast;
6272     case Type::STK_Bool:
6273       return CK_PointerToBoolean;
6274     case Type::STK_Integral:
6275       return CK_PointerToIntegral;
6276     case Type::STK_Floating:
6277     case Type::STK_FloatingComplex:
6278     case Type::STK_IntegralComplex:
6279     case Type::STK_MemberPointer:
6280     case Type::STK_FixedPoint:
6281       llvm_unreachable("illegal cast from pointer");
6282     }
6283     llvm_unreachable("Should have returned before this");
6284 
6285   case Type::STK_FixedPoint:
6286     switch (DestTy->getScalarTypeKind()) {
6287     case Type::STK_FixedPoint:
6288       return CK_FixedPointCast;
6289     case Type::STK_Bool:
6290       return CK_FixedPointToBoolean;
6291     case Type::STK_Integral:
6292       return CK_FixedPointToIntegral;
6293     case Type::STK_Floating:
6294     case Type::STK_IntegralComplex:
6295     case Type::STK_FloatingComplex:
6296       Diag(Src.get()->getExprLoc(),
6297            diag::err_unimplemented_conversion_with_fixed_point_type)
6298           << DestTy;
6299       return CK_IntegralCast;
6300     case Type::STK_CPointer:
6301     case Type::STK_ObjCObjectPointer:
6302     case Type::STK_BlockPointer:
6303     case Type::STK_MemberPointer:
6304       llvm_unreachable("illegal cast to pointer type");
6305     }
6306     llvm_unreachable("Should have returned before this");
6307 
6308   case Type::STK_Bool: // casting from bool is like casting from an integer
6309   case Type::STK_Integral:
6310     switch (DestTy->getScalarTypeKind()) {
6311     case Type::STK_CPointer:
6312     case Type::STK_ObjCObjectPointer:
6313     case Type::STK_BlockPointer:
6314       if (Src.get()->isNullPointerConstant(Context,
6315                                            Expr::NPC_ValueDependentIsNull))
6316         return CK_NullToPointer;
6317       return CK_IntegralToPointer;
6318     case Type::STK_Bool:
6319       return CK_IntegralToBoolean;
6320     case Type::STK_Integral:
6321       return CK_IntegralCast;
6322     case Type::STK_Floating:
6323       return CK_IntegralToFloating;
6324     case Type::STK_IntegralComplex:
6325       Src = ImpCastExprToType(Src.get(),
6326                       DestTy->castAs<ComplexType>()->getElementType(),
6327                       CK_IntegralCast);
6328       return CK_IntegralRealToComplex;
6329     case Type::STK_FloatingComplex:
6330       Src = ImpCastExprToType(Src.get(),
6331                       DestTy->castAs<ComplexType>()->getElementType(),
6332                       CK_IntegralToFloating);
6333       return CK_FloatingRealToComplex;
6334     case Type::STK_MemberPointer:
6335       llvm_unreachable("member pointer type in C");
6336     case Type::STK_FixedPoint:
6337       return CK_IntegralToFixedPoint;
6338     }
6339     llvm_unreachable("Should have returned before this");
6340 
6341   case Type::STK_Floating:
6342     switch (DestTy->getScalarTypeKind()) {
6343     case Type::STK_Floating:
6344       return CK_FloatingCast;
6345     case Type::STK_Bool:
6346       return CK_FloatingToBoolean;
6347     case Type::STK_Integral:
6348       return CK_FloatingToIntegral;
6349     case Type::STK_FloatingComplex:
6350       Src = ImpCastExprToType(Src.get(),
6351                               DestTy->castAs<ComplexType>()->getElementType(),
6352                               CK_FloatingCast);
6353       return CK_FloatingRealToComplex;
6354     case Type::STK_IntegralComplex:
6355       Src = ImpCastExprToType(Src.get(),
6356                               DestTy->castAs<ComplexType>()->getElementType(),
6357                               CK_FloatingToIntegral);
6358       return CK_IntegralRealToComplex;
6359     case Type::STK_CPointer:
6360     case Type::STK_ObjCObjectPointer:
6361     case Type::STK_BlockPointer:
6362       llvm_unreachable("valid float->pointer cast?");
6363     case Type::STK_MemberPointer:
6364       llvm_unreachable("member pointer type in C");
6365     case Type::STK_FixedPoint:
6366       Diag(Src.get()->getExprLoc(),
6367            diag::err_unimplemented_conversion_with_fixed_point_type)
6368           << SrcTy;
6369       return CK_IntegralCast;
6370     }
6371     llvm_unreachable("Should have returned before this");
6372 
6373   case Type::STK_FloatingComplex:
6374     switch (DestTy->getScalarTypeKind()) {
6375     case Type::STK_FloatingComplex:
6376       return CK_FloatingComplexCast;
6377     case Type::STK_IntegralComplex:
6378       return CK_FloatingComplexToIntegralComplex;
6379     case Type::STK_Floating: {
6380       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6381       if (Context.hasSameType(ET, DestTy))
6382         return CK_FloatingComplexToReal;
6383       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6384       return CK_FloatingCast;
6385     }
6386     case Type::STK_Bool:
6387       return CK_FloatingComplexToBoolean;
6388     case Type::STK_Integral:
6389       Src = ImpCastExprToType(Src.get(),
6390                               SrcTy->castAs<ComplexType>()->getElementType(),
6391                               CK_FloatingComplexToReal);
6392       return CK_FloatingToIntegral;
6393     case Type::STK_CPointer:
6394     case Type::STK_ObjCObjectPointer:
6395     case Type::STK_BlockPointer:
6396       llvm_unreachable("valid complex float->pointer cast?");
6397     case Type::STK_MemberPointer:
6398       llvm_unreachable("member pointer type in C");
6399     case Type::STK_FixedPoint:
6400       Diag(Src.get()->getExprLoc(),
6401            diag::err_unimplemented_conversion_with_fixed_point_type)
6402           << SrcTy;
6403       return CK_IntegralCast;
6404     }
6405     llvm_unreachable("Should have returned before this");
6406 
6407   case Type::STK_IntegralComplex:
6408     switch (DestTy->getScalarTypeKind()) {
6409     case Type::STK_FloatingComplex:
6410       return CK_IntegralComplexToFloatingComplex;
6411     case Type::STK_IntegralComplex:
6412       return CK_IntegralComplexCast;
6413     case Type::STK_Integral: {
6414       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6415       if (Context.hasSameType(ET, DestTy))
6416         return CK_IntegralComplexToReal;
6417       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6418       return CK_IntegralCast;
6419     }
6420     case Type::STK_Bool:
6421       return CK_IntegralComplexToBoolean;
6422     case Type::STK_Floating:
6423       Src = ImpCastExprToType(Src.get(),
6424                               SrcTy->castAs<ComplexType>()->getElementType(),
6425                               CK_IntegralComplexToReal);
6426       return CK_IntegralToFloating;
6427     case Type::STK_CPointer:
6428     case Type::STK_ObjCObjectPointer:
6429     case Type::STK_BlockPointer:
6430       llvm_unreachable("valid complex int->pointer cast?");
6431     case Type::STK_MemberPointer:
6432       llvm_unreachable("member pointer type in C");
6433     case Type::STK_FixedPoint:
6434       Diag(Src.get()->getExprLoc(),
6435            diag::err_unimplemented_conversion_with_fixed_point_type)
6436           << SrcTy;
6437       return CK_IntegralCast;
6438     }
6439     llvm_unreachable("Should have returned before this");
6440   }
6441 
6442   llvm_unreachable("Unhandled scalar cast");
6443 }
6444 
6445 static bool breakDownVectorType(QualType type, uint64_t &len,
6446                                 QualType &eltType) {
6447   // Vectors are simple.
6448   if (const VectorType *vecType = type->getAs<VectorType>()) {
6449     len = vecType->getNumElements();
6450     eltType = vecType->getElementType();
6451     assert(eltType->isScalarType());
6452     return true;
6453   }
6454 
6455   // We allow lax conversion to and from non-vector types, but only if
6456   // they're real types (i.e. non-complex, non-pointer scalar types).
6457   if (!type->isRealType()) return false;
6458 
6459   len = 1;
6460   eltType = type;
6461   return true;
6462 }
6463 
6464 /// Are the two types lax-compatible vector types?  That is, given
6465 /// that one of them is a vector, do they have equal storage sizes,
6466 /// where the storage size is the number of elements times the element
6467 /// size?
6468 ///
6469 /// This will also return false if either of the types is neither a
6470 /// vector nor a real type.
6471 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6472   assert(destTy->isVectorType() || srcTy->isVectorType());
6473 
6474   // Disallow lax conversions between scalars and ExtVectors (these
6475   // conversions are allowed for other vector types because common headers
6476   // depend on them).  Most scalar OP ExtVector cases are handled by the
6477   // splat path anyway, which does what we want (convert, not bitcast).
6478   // What this rules out for ExtVectors is crazy things like char4*float.
6479   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6480   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6481 
6482   uint64_t srcLen, destLen;
6483   QualType srcEltTy, destEltTy;
6484   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6485   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6486 
6487   // ASTContext::getTypeSize will return the size rounded up to a
6488   // power of 2, so instead of using that, we need to use the raw
6489   // element size multiplied by the element count.
6490   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6491   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6492 
6493   return (srcLen * srcEltSize == destLen * destEltSize);
6494 }
6495 
6496 /// Is this a legal conversion between two types, one of which is
6497 /// known to be a vector type?
6498 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6499   assert(destTy->isVectorType() || srcTy->isVectorType());
6500 
6501   switch (Context.getLangOpts().getLaxVectorConversions()) {
6502   case LangOptions::LaxVectorConversionKind::None:
6503     return false;
6504 
6505   case LangOptions::LaxVectorConversionKind::Integer:
6506     if (!srcTy->isIntegralOrEnumerationType()) {
6507       auto *Vec = srcTy->getAs<VectorType>();
6508       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6509         return false;
6510     }
6511     if (!destTy->isIntegralOrEnumerationType()) {
6512       auto *Vec = destTy->getAs<VectorType>();
6513       if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6514         return false;
6515     }
6516     // OK, integer (vector) -> integer (vector) bitcast.
6517     break;
6518 
6519     case LangOptions::LaxVectorConversionKind::All:
6520     break;
6521   }
6522 
6523   return areLaxCompatibleVectorTypes(srcTy, destTy);
6524 }
6525 
6526 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6527                            CastKind &Kind) {
6528   assert(VectorTy->isVectorType() && "Not a vector type!");
6529 
6530   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6531     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6532       return Diag(R.getBegin(),
6533                   Ty->isVectorType() ?
6534                   diag::err_invalid_conversion_between_vectors :
6535                   diag::err_invalid_conversion_between_vector_and_integer)
6536         << VectorTy << Ty << R;
6537   } else
6538     return Diag(R.getBegin(),
6539                 diag::err_invalid_conversion_between_vector_and_scalar)
6540       << VectorTy << Ty << R;
6541 
6542   Kind = CK_BitCast;
6543   return false;
6544 }
6545 
6546 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6547   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6548 
6549   if (DestElemTy == SplattedExpr->getType())
6550     return SplattedExpr;
6551 
6552   assert(DestElemTy->isFloatingType() ||
6553          DestElemTy->isIntegralOrEnumerationType());
6554 
6555   CastKind CK;
6556   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6557     // OpenCL requires that we convert `true` boolean expressions to -1, but
6558     // only when splatting vectors.
6559     if (DestElemTy->isFloatingType()) {
6560       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6561       // in two steps: boolean to signed integral, then to floating.
6562       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6563                                                  CK_BooleanToSignedIntegral);
6564       SplattedExpr = CastExprRes.get();
6565       CK = CK_IntegralToFloating;
6566     } else {
6567       CK = CK_BooleanToSignedIntegral;
6568     }
6569   } else {
6570     ExprResult CastExprRes = SplattedExpr;
6571     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6572     if (CastExprRes.isInvalid())
6573       return ExprError();
6574     SplattedExpr = CastExprRes.get();
6575   }
6576   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6577 }
6578 
6579 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6580                                     Expr *CastExpr, CastKind &Kind) {
6581   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6582 
6583   QualType SrcTy = CastExpr->getType();
6584 
6585   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6586   // an ExtVectorType.
6587   // In OpenCL, casts between vectors of different types are not allowed.
6588   // (See OpenCL 6.2).
6589   if (SrcTy->isVectorType()) {
6590     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6591         (getLangOpts().OpenCL &&
6592          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6593       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6594         << DestTy << SrcTy << R;
6595       return ExprError();
6596     }
6597     Kind = CK_BitCast;
6598     return CastExpr;
6599   }
6600 
6601   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6602   // conversion will take place first from scalar to elt type, and then
6603   // splat from elt type to vector.
6604   if (SrcTy->isPointerType())
6605     return Diag(R.getBegin(),
6606                 diag::err_invalid_conversion_between_vector_and_scalar)
6607       << DestTy << SrcTy << R;
6608 
6609   Kind = CK_VectorSplat;
6610   return prepareVectorSplat(DestTy, CastExpr);
6611 }
6612 
6613 ExprResult
6614 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6615                     Declarator &D, ParsedType &Ty,
6616                     SourceLocation RParenLoc, Expr *CastExpr) {
6617   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6618          "ActOnCastExpr(): missing type or expr");
6619 
6620   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6621   if (D.isInvalidType())
6622     return ExprError();
6623 
6624   if (getLangOpts().CPlusPlus) {
6625     // Check that there are no default arguments (C++ only).
6626     CheckExtraCXXDefaultArguments(D);
6627   } else {
6628     // Make sure any TypoExprs have been dealt with.
6629     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6630     if (!Res.isUsable())
6631       return ExprError();
6632     CastExpr = Res.get();
6633   }
6634 
6635   checkUnusedDeclAttributes(D);
6636 
6637   QualType castType = castTInfo->getType();
6638   Ty = CreateParsedType(castType, castTInfo);
6639 
6640   bool isVectorLiteral = false;
6641 
6642   // Check for an altivec or OpenCL literal,
6643   // i.e. all the elements are integer constants.
6644   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6645   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6646   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6647        && castType->isVectorType() && (PE || PLE)) {
6648     if (PLE && PLE->getNumExprs() == 0) {
6649       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6650       return ExprError();
6651     }
6652     if (PE || PLE->getNumExprs() == 1) {
6653       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6654       if (!E->getType()->isVectorType())
6655         isVectorLiteral = true;
6656     }
6657     else
6658       isVectorLiteral = true;
6659   }
6660 
6661   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6662   // then handle it as such.
6663   if (isVectorLiteral)
6664     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6665 
6666   // If the Expr being casted is a ParenListExpr, handle it specially.
6667   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6668   // sequence of BinOp comma operators.
6669   if (isa<ParenListExpr>(CastExpr)) {
6670     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6671     if (Result.isInvalid()) return ExprError();
6672     CastExpr = Result.get();
6673   }
6674 
6675   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6676       !getSourceManager().isInSystemMacro(LParenLoc))
6677     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6678 
6679   CheckTollFreeBridgeCast(castType, CastExpr);
6680 
6681   CheckObjCBridgeRelatedCast(castType, CastExpr);
6682 
6683   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6684 
6685   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6686 }
6687 
6688 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6689                                     SourceLocation RParenLoc, Expr *E,
6690                                     TypeSourceInfo *TInfo) {
6691   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6692          "Expected paren or paren list expression");
6693 
6694   Expr **exprs;
6695   unsigned numExprs;
6696   Expr *subExpr;
6697   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6698   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6699     LiteralLParenLoc = PE->getLParenLoc();
6700     LiteralRParenLoc = PE->getRParenLoc();
6701     exprs = PE->getExprs();
6702     numExprs = PE->getNumExprs();
6703   } else { // isa<ParenExpr> by assertion at function entrance
6704     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6705     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6706     subExpr = cast<ParenExpr>(E)->getSubExpr();
6707     exprs = &subExpr;
6708     numExprs = 1;
6709   }
6710 
6711   QualType Ty = TInfo->getType();
6712   assert(Ty->isVectorType() && "Expected vector type");
6713 
6714   SmallVector<Expr *, 8> initExprs;
6715   const VectorType *VTy = Ty->getAs<VectorType>();
6716   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6717 
6718   // '(...)' form of vector initialization in AltiVec: the number of
6719   // initializers must be one or must match the size of the vector.
6720   // If a single value is specified in the initializer then it will be
6721   // replicated to all the components of the vector
6722   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6723     // The number of initializers must be one or must match the size of the
6724     // vector. If a single value is specified in the initializer then it will
6725     // be replicated to all the components of the vector
6726     if (numExprs == 1) {
6727       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6728       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6729       if (Literal.isInvalid())
6730         return ExprError();
6731       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6732                                   PrepareScalarCast(Literal, ElemTy));
6733       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6734     }
6735     else if (numExprs < numElems) {
6736       Diag(E->getExprLoc(),
6737            diag::err_incorrect_number_of_vector_initializers);
6738       return ExprError();
6739     }
6740     else
6741       initExprs.append(exprs, exprs + numExprs);
6742   }
6743   else {
6744     // For OpenCL, when the number of initializers is a single value,
6745     // it will be replicated to all components of the vector.
6746     if (getLangOpts().OpenCL &&
6747         VTy->getVectorKind() == VectorType::GenericVector &&
6748         numExprs == 1) {
6749         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6750         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6751         if (Literal.isInvalid())
6752           return ExprError();
6753         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6754                                     PrepareScalarCast(Literal, ElemTy));
6755         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6756     }
6757 
6758     initExprs.append(exprs, exprs + numExprs);
6759   }
6760   // FIXME: This means that pretty-printing the final AST will produce curly
6761   // braces instead of the original commas.
6762   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6763                                                    initExprs, LiteralRParenLoc);
6764   initE->setType(Ty);
6765   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6766 }
6767 
6768 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6769 /// the ParenListExpr into a sequence of comma binary operators.
6770 ExprResult
6771 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6772   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6773   if (!E)
6774     return OrigExpr;
6775 
6776   ExprResult Result(E->getExpr(0));
6777 
6778   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6779     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6780                         E->getExpr(i));
6781 
6782   if (Result.isInvalid()) return ExprError();
6783 
6784   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6785 }
6786 
6787 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6788                                     SourceLocation R,
6789                                     MultiExprArg Val) {
6790   return ParenListExpr::Create(Context, L, Val, R);
6791 }
6792 
6793 /// Emit a specialized diagnostic when one expression is a null pointer
6794 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6795 /// emitted.
6796 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6797                                       SourceLocation QuestionLoc) {
6798   Expr *NullExpr = LHSExpr;
6799   Expr *NonPointerExpr = RHSExpr;
6800   Expr::NullPointerConstantKind NullKind =
6801       NullExpr->isNullPointerConstant(Context,
6802                                       Expr::NPC_ValueDependentIsNotNull);
6803 
6804   if (NullKind == Expr::NPCK_NotNull) {
6805     NullExpr = RHSExpr;
6806     NonPointerExpr = LHSExpr;
6807     NullKind =
6808         NullExpr->isNullPointerConstant(Context,
6809                                         Expr::NPC_ValueDependentIsNotNull);
6810   }
6811 
6812   if (NullKind == Expr::NPCK_NotNull)
6813     return false;
6814 
6815   if (NullKind == Expr::NPCK_ZeroExpression)
6816     return false;
6817 
6818   if (NullKind == Expr::NPCK_ZeroLiteral) {
6819     // In this case, check to make sure that we got here from a "NULL"
6820     // string in the source code.
6821     NullExpr = NullExpr->IgnoreParenImpCasts();
6822     SourceLocation loc = NullExpr->getExprLoc();
6823     if (!findMacroSpelling(loc, "NULL"))
6824       return false;
6825   }
6826 
6827   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6828   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6829       << NonPointerExpr->getType() << DiagType
6830       << NonPointerExpr->getSourceRange();
6831   return true;
6832 }
6833 
6834 /// Return false if the condition expression is valid, true otherwise.
6835 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6836   QualType CondTy = Cond->getType();
6837 
6838   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6839   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6840     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6841       << CondTy << Cond->getSourceRange();
6842     return true;
6843   }
6844 
6845   // C99 6.5.15p2
6846   if (CondTy->isScalarType()) return false;
6847 
6848   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6849     << CondTy << Cond->getSourceRange();
6850   return true;
6851 }
6852 
6853 /// Handle when one or both operands are void type.
6854 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6855                                          ExprResult &RHS) {
6856     Expr *LHSExpr = LHS.get();
6857     Expr *RHSExpr = RHS.get();
6858 
6859     if (!LHSExpr->getType()->isVoidType())
6860       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6861           << RHSExpr->getSourceRange();
6862     if (!RHSExpr->getType()->isVoidType())
6863       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6864           << LHSExpr->getSourceRange();
6865     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6866     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6867     return S.Context.VoidTy;
6868 }
6869 
6870 /// Return false if the NullExpr can be promoted to PointerTy,
6871 /// true otherwise.
6872 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6873                                         QualType PointerTy) {
6874   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6875       !NullExpr.get()->isNullPointerConstant(S.Context,
6876                                             Expr::NPC_ValueDependentIsNull))
6877     return true;
6878 
6879   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6880   return false;
6881 }
6882 
6883 /// Checks compatibility between two pointers and return the resulting
6884 /// type.
6885 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6886                                                      ExprResult &RHS,
6887                                                      SourceLocation Loc) {
6888   QualType LHSTy = LHS.get()->getType();
6889   QualType RHSTy = RHS.get()->getType();
6890 
6891   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6892     // Two identical pointers types are always compatible.
6893     return LHSTy;
6894   }
6895 
6896   QualType lhptee, rhptee;
6897 
6898   // Get the pointee types.
6899   bool IsBlockPointer = false;
6900   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6901     lhptee = LHSBTy->getPointeeType();
6902     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6903     IsBlockPointer = true;
6904   } else {
6905     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6906     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6907   }
6908 
6909   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6910   // differently qualified versions of compatible types, the result type is
6911   // a pointer to an appropriately qualified version of the composite
6912   // type.
6913 
6914   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6915   // clause doesn't make sense for our extensions. E.g. address space 2 should
6916   // be incompatible with address space 3: they may live on different devices or
6917   // anything.
6918   Qualifiers lhQual = lhptee.getQualifiers();
6919   Qualifiers rhQual = rhptee.getQualifiers();
6920 
6921   LangAS ResultAddrSpace = LangAS::Default;
6922   LangAS LAddrSpace = lhQual.getAddressSpace();
6923   LangAS RAddrSpace = rhQual.getAddressSpace();
6924 
6925   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6926   // spaces is disallowed.
6927   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6928     ResultAddrSpace = LAddrSpace;
6929   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6930     ResultAddrSpace = RAddrSpace;
6931   else {
6932     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6933         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6934         << RHS.get()->getSourceRange();
6935     return QualType();
6936   }
6937 
6938   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6939   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6940   lhQual.removeCVRQualifiers();
6941   rhQual.removeCVRQualifiers();
6942 
6943   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6944   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6945   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6946   // qual types are compatible iff
6947   //  * corresponded types are compatible
6948   //  * CVR qualifiers are equal
6949   //  * address spaces are equal
6950   // Thus for conditional operator we merge CVR and address space unqualified
6951   // pointees and if there is a composite type we return a pointer to it with
6952   // merged qualifiers.
6953   LHSCastKind =
6954       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6955   RHSCastKind =
6956       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6957   lhQual.removeAddressSpace();
6958   rhQual.removeAddressSpace();
6959 
6960   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6961   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6962 
6963   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6964 
6965   if (CompositeTy.isNull()) {
6966     // In this situation, we assume void* type. No especially good
6967     // reason, but this is what gcc does, and we do have to pick
6968     // to get a consistent AST.
6969     QualType incompatTy;
6970     incompatTy = S.Context.getPointerType(
6971         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6972     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6973     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6974 
6975     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6976     // for casts between types with incompatible address space qualifiers.
6977     // For the following code the compiler produces casts between global and
6978     // local address spaces of the corresponded innermost pointees:
6979     // local int *global *a;
6980     // global int *global *b;
6981     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6982     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6983         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6984         << RHS.get()->getSourceRange();
6985 
6986     return incompatTy;
6987   }
6988 
6989   // The pointer types are compatible.
6990   // In case of OpenCL ResultTy should have the address space qualifier
6991   // which is a superset of address spaces of both the 2nd and the 3rd
6992   // operands of the conditional operator.
6993   QualType ResultTy = [&, ResultAddrSpace]() {
6994     if (S.getLangOpts().OpenCL) {
6995       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6996       CompositeQuals.setAddressSpace(ResultAddrSpace);
6997       return S.Context
6998           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6999           .withCVRQualifiers(MergedCVRQual);
7000     }
7001     return CompositeTy.withCVRQualifiers(MergedCVRQual);
7002   }();
7003   if (IsBlockPointer)
7004     ResultTy = S.Context.getBlockPointerType(ResultTy);
7005   else
7006     ResultTy = S.Context.getPointerType(ResultTy);
7007 
7008   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7009   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7010   return ResultTy;
7011 }
7012 
7013 /// Return the resulting type when the operands are both block pointers.
7014 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7015                                                           ExprResult &LHS,
7016                                                           ExprResult &RHS,
7017                                                           SourceLocation Loc) {
7018   QualType LHSTy = LHS.get()->getType();
7019   QualType RHSTy = RHS.get()->getType();
7020 
7021   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7022     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7023       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7024       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7025       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7026       return destType;
7027     }
7028     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7029       << LHSTy << RHSTy << LHS.get()->getSourceRange()
7030       << RHS.get()->getSourceRange();
7031     return QualType();
7032   }
7033 
7034   // We have 2 block pointer types.
7035   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7036 }
7037 
7038 /// Return the resulting type when the operands are both pointers.
7039 static QualType
7040 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7041                                             ExprResult &RHS,
7042                                             SourceLocation Loc) {
7043   // get the pointer types
7044   QualType LHSTy = LHS.get()->getType();
7045   QualType RHSTy = RHS.get()->getType();
7046 
7047   // get the "pointed to" types
7048   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7049   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7050 
7051   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7052   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7053     // Figure out necessary qualifiers (C99 6.5.15p6)
7054     QualType destPointee
7055       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7056     QualType destType = S.Context.getPointerType(destPointee);
7057     // Add qualifiers if necessary.
7058     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7059     // Promote to void*.
7060     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7061     return destType;
7062   }
7063   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7064     QualType destPointee
7065       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7066     QualType destType = S.Context.getPointerType(destPointee);
7067     // Add qualifiers if necessary.
7068     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7069     // Promote to void*.
7070     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7071     return destType;
7072   }
7073 
7074   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7075 }
7076 
7077 /// Return false if the first expression is not an integer and the second
7078 /// expression is not a pointer, true otherwise.
7079 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7080                                         Expr* PointerExpr, SourceLocation Loc,
7081                                         bool IsIntFirstExpr) {
7082   if (!PointerExpr->getType()->isPointerType() ||
7083       !Int.get()->getType()->isIntegerType())
7084     return false;
7085 
7086   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7087   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7088 
7089   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7090     << Expr1->getType() << Expr2->getType()
7091     << Expr1->getSourceRange() << Expr2->getSourceRange();
7092   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7093                             CK_IntegralToPointer);
7094   return true;
7095 }
7096 
7097 /// Simple conversion between integer and floating point types.
7098 ///
7099 /// Used when handling the OpenCL conditional operator where the
7100 /// condition is a vector while the other operands are scalar.
7101 ///
7102 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7103 /// types are either integer or floating type. Between the two
7104 /// operands, the type with the higher rank is defined as the "result
7105 /// type". The other operand needs to be promoted to the same type. No
7106 /// other type promotion is allowed. We cannot use
7107 /// UsualArithmeticConversions() for this purpose, since it always
7108 /// promotes promotable types.
7109 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7110                                             ExprResult &RHS,
7111                                             SourceLocation QuestionLoc) {
7112   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7113   if (LHS.isInvalid())
7114     return QualType();
7115   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7116   if (RHS.isInvalid())
7117     return QualType();
7118 
7119   // For conversion purposes, we ignore any qualifiers.
7120   // For example, "const float" and "float" are equivalent.
7121   QualType LHSType =
7122     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7123   QualType RHSType =
7124     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7125 
7126   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7127     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7128       << LHSType << LHS.get()->getSourceRange();
7129     return QualType();
7130   }
7131 
7132   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7133     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7134       << RHSType << RHS.get()->getSourceRange();
7135     return QualType();
7136   }
7137 
7138   // If both types are identical, no conversion is needed.
7139   if (LHSType == RHSType)
7140     return LHSType;
7141 
7142   // Now handle "real" floating types (i.e. float, double, long double).
7143   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7144     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7145                                  /*IsCompAssign = */ false);
7146 
7147   // Finally, we have two differing integer types.
7148   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7149   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7150 }
7151 
7152 /// Convert scalar operands to a vector that matches the
7153 ///        condition in length.
7154 ///
7155 /// Used when handling the OpenCL conditional operator where the
7156 /// condition is a vector while the other operands are scalar.
7157 ///
7158 /// We first compute the "result type" for the scalar operands
7159 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7160 /// into a vector of that type where the length matches the condition
7161 /// vector type. s6.11.6 requires that the element types of the result
7162 /// and the condition must have the same number of bits.
7163 static QualType
7164 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7165                               QualType CondTy, SourceLocation QuestionLoc) {
7166   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7167   if (ResTy.isNull()) return QualType();
7168 
7169   const VectorType *CV = CondTy->getAs<VectorType>();
7170   assert(CV);
7171 
7172   // Determine the vector result type
7173   unsigned NumElements = CV->getNumElements();
7174   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7175 
7176   // Ensure that all types have the same number of bits
7177   if (S.Context.getTypeSize(CV->getElementType())
7178       != S.Context.getTypeSize(ResTy)) {
7179     // Since VectorTy is created internally, it does not pretty print
7180     // with an OpenCL name. Instead, we just print a description.
7181     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7182     SmallString<64> Str;
7183     llvm::raw_svector_ostream OS(Str);
7184     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7185     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7186       << CondTy << OS.str();
7187     return QualType();
7188   }
7189 
7190   // Convert operands to the vector result type
7191   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7192   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7193 
7194   return VectorTy;
7195 }
7196 
7197 /// Return false if this is a valid OpenCL condition vector
7198 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7199                                        SourceLocation QuestionLoc) {
7200   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7201   // integral type.
7202   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7203   assert(CondTy);
7204   QualType EleTy = CondTy->getElementType();
7205   if (EleTy->isIntegerType()) return false;
7206 
7207   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7208     << Cond->getType() << Cond->getSourceRange();
7209   return true;
7210 }
7211 
7212 /// Return false if the vector condition type and the vector
7213 ///        result type are compatible.
7214 ///
7215 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7216 /// number of elements, and their element types have the same number
7217 /// of bits.
7218 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7219                               SourceLocation QuestionLoc) {
7220   const VectorType *CV = CondTy->getAs<VectorType>();
7221   const VectorType *RV = VecResTy->getAs<VectorType>();
7222   assert(CV && RV);
7223 
7224   if (CV->getNumElements() != RV->getNumElements()) {
7225     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7226       << CondTy << VecResTy;
7227     return true;
7228   }
7229 
7230   QualType CVE = CV->getElementType();
7231   QualType RVE = RV->getElementType();
7232 
7233   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7234     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7235       << CondTy << VecResTy;
7236     return true;
7237   }
7238 
7239   return false;
7240 }
7241 
7242 /// Return the resulting type for the conditional operator in
7243 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7244 ///        s6.3.i) when the condition is a vector type.
7245 static QualType
7246 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7247                              ExprResult &LHS, ExprResult &RHS,
7248                              SourceLocation QuestionLoc) {
7249   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7250   if (Cond.isInvalid())
7251     return QualType();
7252   QualType CondTy = Cond.get()->getType();
7253 
7254   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7255     return QualType();
7256 
7257   // If either operand is a vector then find the vector type of the
7258   // result as specified in OpenCL v1.1 s6.3.i.
7259   if (LHS.get()->getType()->isVectorType() ||
7260       RHS.get()->getType()->isVectorType()) {
7261     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7262                                               /*isCompAssign*/false,
7263                                               /*AllowBothBool*/true,
7264                                               /*AllowBoolConversions*/false);
7265     if (VecResTy.isNull()) return QualType();
7266     // The result type must match the condition type as specified in
7267     // OpenCL v1.1 s6.11.6.
7268     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7269       return QualType();
7270     return VecResTy;
7271   }
7272 
7273   // Both operands are scalar.
7274   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7275 }
7276 
7277 /// Return true if the Expr is block type
7278 static bool checkBlockType(Sema &S, const Expr *E) {
7279   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7280     QualType Ty = CE->getCallee()->getType();
7281     if (Ty->isBlockPointerType()) {
7282       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7283       return true;
7284     }
7285   }
7286   return false;
7287 }
7288 
7289 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7290 /// In that case, LHS = cond.
7291 /// C99 6.5.15
7292 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7293                                         ExprResult &RHS, ExprValueKind &VK,
7294                                         ExprObjectKind &OK,
7295                                         SourceLocation QuestionLoc) {
7296 
7297   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7298   if (!LHSResult.isUsable()) return QualType();
7299   LHS = LHSResult;
7300 
7301   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7302   if (!RHSResult.isUsable()) return QualType();
7303   RHS = RHSResult;
7304 
7305   // C++ is sufficiently different to merit its own checker.
7306   if (getLangOpts().CPlusPlus)
7307     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7308 
7309   VK = VK_RValue;
7310   OK = OK_Ordinary;
7311 
7312   // The OpenCL operator with a vector condition is sufficiently
7313   // different to merit its own checker.
7314   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7315     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7316 
7317   // First, check the condition.
7318   Cond = UsualUnaryConversions(Cond.get());
7319   if (Cond.isInvalid())
7320     return QualType();
7321   if (checkCondition(*this, Cond.get(), QuestionLoc))
7322     return QualType();
7323 
7324   // Now check the two expressions.
7325   if (LHS.get()->getType()->isVectorType() ||
7326       RHS.get()->getType()->isVectorType())
7327     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7328                                /*AllowBothBool*/true,
7329                                /*AllowBoolConversions*/false);
7330 
7331   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7332   if (LHS.isInvalid() || RHS.isInvalid())
7333     return QualType();
7334 
7335   QualType LHSTy = LHS.get()->getType();
7336   QualType RHSTy = RHS.get()->getType();
7337 
7338   // Diagnose attempts to convert between __float128 and long double where
7339   // such conversions currently can't be handled.
7340   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7341     Diag(QuestionLoc,
7342          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7343       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7344     return QualType();
7345   }
7346 
7347   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7348   // selection operator (?:).
7349   if (getLangOpts().OpenCL &&
7350       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7351     return QualType();
7352   }
7353 
7354   // If both operands have arithmetic type, do the usual arithmetic conversions
7355   // to find a common type: C99 6.5.15p3,5.
7356   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7357     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7358     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7359 
7360     return ResTy;
7361   }
7362 
7363   // If both operands are the same structure or union type, the result is that
7364   // type.
7365   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7366     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7367       if (LHSRT->getDecl() == RHSRT->getDecl())
7368         // "If both the operands have structure or union type, the result has
7369         // that type."  This implies that CV qualifiers are dropped.
7370         return LHSTy.getUnqualifiedType();
7371     // FIXME: Type of conditional expression must be complete in C mode.
7372   }
7373 
7374   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7375   // The following || allows only one side to be void (a GCC-ism).
7376   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7377     return checkConditionalVoidType(*this, LHS, RHS);
7378   }
7379 
7380   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7381   // the type of the other operand."
7382   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7383   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7384 
7385   // All objective-c pointer type analysis is done here.
7386   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7387                                                         QuestionLoc);
7388   if (LHS.isInvalid() || RHS.isInvalid())
7389     return QualType();
7390   if (!compositeType.isNull())
7391     return compositeType;
7392 
7393 
7394   // Handle block pointer types.
7395   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7396     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7397                                                      QuestionLoc);
7398 
7399   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7400   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7401     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7402                                                        QuestionLoc);
7403 
7404   // GCC compatibility: soften pointer/integer mismatch.  Note that
7405   // null pointers have been filtered out by this point.
7406   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7407       /*IsIntFirstExpr=*/true))
7408     return RHSTy;
7409   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7410       /*IsIntFirstExpr=*/false))
7411     return LHSTy;
7412 
7413   // Emit a better diagnostic if one of the expressions is a null pointer
7414   // constant and the other is not a pointer type. In this case, the user most
7415   // likely forgot to take the address of the other expression.
7416   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7417     return QualType();
7418 
7419   // Otherwise, the operands are not compatible.
7420   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7421     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7422     << RHS.get()->getSourceRange();
7423   return QualType();
7424 }
7425 
7426 /// FindCompositeObjCPointerType - Helper method to find composite type of
7427 /// two objective-c pointer types of the two input expressions.
7428 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7429                                             SourceLocation QuestionLoc) {
7430   QualType LHSTy = LHS.get()->getType();
7431   QualType RHSTy = RHS.get()->getType();
7432 
7433   // Handle things like Class and struct objc_class*.  Here we case the result
7434   // to the pseudo-builtin, because that will be implicitly cast back to the
7435   // redefinition type if an attempt is made to access its fields.
7436   if (LHSTy->isObjCClassType() &&
7437       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7438     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7439     return LHSTy;
7440   }
7441   if (RHSTy->isObjCClassType() &&
7442       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7443     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7444     return RHSTy;
7445   }
7446   // And the same for struct objc_object* / id
7447   if (LHSTy->isObjCIdType() &&
7448       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7449     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7450     return LHSTy;
7451   }
7452   if (RHSTy->isObjCIdType() &&
7453       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7454     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7455     return RHSTy;
7456   }
7457   // And the same for struct objc_selector* / SEL
7458   if (Context.isObjCSelType(LHSTy) &&
7459       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7460     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7461     return LHSTy;
7462   }
7463   if (Context.isObjCSelType(RHSTy) &&
7464       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7465     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7466     return RHSTy;
7467   }
7468   // Check constraints for Objective-C object pointers types.
7469   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7470 
7471     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7472       // Two identical object pointer types are always compatible.
7473       return LHSTy;
7474     }
7475     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7476     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7477     QualType compositeType = LHSTy;
7478 
7479     // If both operands are interfaces and either operand can be
7480     // assigned to the other, use that type as the composite
7481     // type. This allows
7482     //   xxx ? (A*) a : (B*) b
7483     // where B is a subclass of A.
7484     //
7485     // Additionally, as for assignment, if either type is 'id'
7486     // allow silent coercion. Finally, if the types are
7487     // incompatible then make sure to use 'id' as the composite
7488     // type so the result is acceptable for sending messages to.
7489 
7490     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7491     // It could return the composite type.
7492     if (!(compositeType =
7493           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7494       // Nothing more to do.
7495     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7496       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7497     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7498       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7499     } else if ((LHSTy->isObjCQualifiedIdType() ||
7500                 RHSTy->isObjCQualifiedIdType()) &&
7501                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7502       // Need to handle "id<xx>" explicitly.
7503       // GCC allows qualified id and any Objective-C type to devolve to
7504       // id. Currently localizing to here until clear this should be
7505       // part of ObjCQualifiedIdTypesAreCompatible.
7506       compositeType = Context.getObjCIdType();
7507     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7508       compositeType = Context.getObjCIdType();
7509     } else {
7510       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7511       << LHSTy << RHSTy
7512       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7513       QualType incompatTy = Context.getObjCIdType();
7514       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7515       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7516       return incompatTy;
7517     }
7518     // The object pointer types are compatible.
7519     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7520     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7521     return compositeType;
7522   }
7523   // Check Objective-C object pointer types and 'void *'
7524   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7525     if (getLangOpts().ObjCAutoRefCount) {
7526       // ARC forbids the implicit conversion of object pointers to 'void *',
7527       // so these types are not compatible.
7528       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7529           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7530       LHS = RHS = true;
7531       return QualType();
7532     }
7533     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7534     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7535     QualType destPointee
7536     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7537     QualType destType = Context.getPointerType(destPointee);
7538     // Add qualifiers if necessary.
7539     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7540     // Promote to void*.
7541     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7542     return destType;
7543   }
7544   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7545     if (getLangOpts().ObjCAutoRefCount) {
7546       // ARC forbids the implicit conversion of object pointers to 'void *',
7547       // so these types are not compatible.
7548       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7549           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7550       LHS = RHS = true;
7551       return QualType();
7552     }
7553     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7554     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7555     QualType destPointee
7556     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7557     QualType destType = Context.getPointerType(destPointee);
7558     // Add qualifiers if necessary.
7559     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7560     // Promote to void*.
7561     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7562     return destType;
7563   }
7564   return QualType();
7565 }
7566 
7567 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7568 /// ParenRange in parentheses.
7569 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7570                                const PartialDiagnostic &Note,
7571                                SourceRange ParenRange) {
7572   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7573   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7574       EndLoc.isValid()) {
7575     Self.Diag(Loc, Note)
7576       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7577       << FixItHint::CreateInsertion(EndLoc, ")");
7578   } else {
7579     // We can't display the parentheses, so just show the bare note.
7580     Self.Diag(Loc, Note) << ParenRange;
7581   }
7582 }
7583 
7584 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7585   return BinaryOperator::isAdditiveOp(Opc) ||
7586          BinaryOperator::isMultiplicativeOp(Opc) ||
7587          BinaryOperator::isShiftOp(Opc);
7588 }
7589 
7590 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7591 /// expression, either using a built-in or overloaded operator,
7592 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7593 /// expression.
7594 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7595                                    Expr **RHSExprs) {
7596   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7597   E = E->IgnoreImpCasts();
7598   E = E->IgnoreConversionOperator();
7599   E = E->IgnoreImpCasts();
7600   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7601     E = MTE->GetTemporaryExpr();
7602     E = E->IgnoreImpCasts();
7603   }
7604 
7605   // Built-in binary operator.
7606   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7607     if (IsArithmeticOp(OP->getOpcode())) {
7608       *Opcode = OP->getOpcode();
7609       *RHSExprs = OP->getRHS();
7610       return true;
7611     }
7612   }
7613 
7614   // Overloaded operator.
7615   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7616     if (Call->getNumArgs() != 2)
7617       return false;
7618 
7619     // Make sure this is really a binary operator that is safe to pass into
7620     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7621     OverloadedOperatorKind OO = Call->getOperator();
7622     if (OO < OO_Plus || OO > OO_Arrow ||
7623         OO == OO_PlusPlus || OO == OO_MinusMinus)
7624       return false;
7625 
7626     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7627     if (IsArithmeticOp(OpKind)) {
7628       *Opcode = OpKind;
7629       *RHSExprs = Call->getArg(1);
7630       return true;
7631     }
7632   }
7633 
7634   return false;
7635 }
7636 
7637 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7638 /// or is a logical expression such as (x==y) which has int type, but is
7639 /// commonly interpreted as boolean.
7640 static bool ExprLooksBoolean(Expr *E) {
7641   E = E->IgnoreParenImpCasts();
7642 
7643   if (E->getType()->isBooleanType())
7644     return true;
7645   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7646     return OP->isComparisonOp() || OP->isLogicalOp();
7647   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7648     return OP->getOpcode() == UO_LNot;
7649   if (E->getType()->isPointerType())
7650     return true;
7651   // FIXME: What about overloaded operator calls returning "unspecified boolean
7652   // type"s (commonly pointer-to-members)?
7653 
7654   return false;
7655 }
7656 
7657 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7658 /// and binary operator are mixed in a way that suggests the programmer assumed
7659 /// the conditional operator has higher precedence, for example:
7660 /// "int x = a + someBinaryCondition ? 1 : 2".
7661 static void DiagnoseConditionalPrecedence(Sema &Self,
7662                                           SourceLocation OpLoc,
7663                                           Expr *Condition,
7664                                           Expr *LHSExpr,
7665                                           Expr *RHSExpr) {
7666   BinaryOperatorKind CondOpcode;
7667   Expr *CondRHS;
7668 
7669   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7670     return;
7671   if (!ExprLooksBoolean(CondRHS))
7672     return;
7673 
7674   // The condition is an arithmetic binary expression, with a right-
7675   // hand side that looks boolean, so warn.
7676 
7677   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7678       << Condition->getSourceRange()
7679       << BinaryOperator::getOpcodeStr(CondOpcode);
7680 
7681   SuggestParentheses(
7682       Self, OpLoc,
7683       Self.PDiag(diag::note_precedence_silence)
7684           << BinaryOperator::getOpcodeStr(CondOpcode),
7685       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7686 
7687   SuggestParentheses(Self, OpLoc,
7688                      Self.PDiag(diag::note_precedence_conditional_first),
7689                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7690 }
7691 
7692 /// Compute the nullability of a conditional expression.
7693 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7694                                               QualType LHSTy, QualType RHSTy,
7695                                               ASTContext &Ctx) {
7696   if (!ResTy->isAnyPointerType())
7697     return ResTy;
7698 
7699   auto GetNullability = [&Ctx](QualType Ty) {
7700     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7701     if (Kind)
7702       return *Kind;
7703     return NullabilityKind::Unspecified;
7704   };
7705 
7706   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7707   NullabilityKind MergedKind;
7708 
7709   // Compute nullability of a binary conditional expression.
7710   if (IsBin) {
7711     if (LHSKind == NullabilityKind::NonNull)
7712       MergedKind = NullabilityKind::NonNull;
7713     else
7714       MergedKind = RHSKind;
7715   // Compute nullability of a normal conditional expression.
7716   } else {
7717     if (LHSKind == NullabilityKind::Nullable ||
7718         RHSKind == NullabilityKind::Nullable)
7719       MergedKind = NullabilityKind::Nullable;
7720     else if (LHSKind == NullabilityKind::NonNull)
7721       MergedKind = RHSKind;
7722     else if (RHSKind == NullabilityKind::NonNull)
7723       MergedKind = LHSKind;
7724     else
7725       MergedKind = NullabilityKind::Unspecified;
7726   }
7727 
7728   // Return if ResTy already has the correct nullability.
7729   if (GetNullability(ResTy) == MergedKind)
7730     return ResTy;
7731 
7732   // Strip all nullability from ResTy.
7733   while (ResTy->getNullability(Ctx))
7734     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7735 
7736   // Create a new AttributedType with the new nullability kind.
7737   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7738   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7739 }
7740 
7741 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7742 /// in the case of a the GNU conditional expr extension.
7743 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7744                                     SourceLocation ColonLoc,
7745                                     Expr *CondExpr, Expr *LHSExpr,
7746                                     Expr *RHSExpr) {
7747   if (!getLangOpts().CPlusPlus) {
7748     // C cannot handle TypoExpr nodes in the condition because it
7749     // doesn't handle dependent types properly, so make sure any TypoExprs have
7750     // been dealt with before checking the operands.
7751     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7752     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7753     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7754 
7755     if (!CondResult.isUsable())
7756       return ExprError();
7757 
7758     if (LHSExpr) {
7759       if (!LHSResult.isUsable())
7760         return ExprError();
7761     }
7762 
7763     if (!RHSResult.isUsable())
7764       return ExprError();
7765 
7766     CondExpr = CondResult.get();
7767     LHSExpr = LHSResult.get();
7768     RHSExpr = RHSResult.get();
7769   }
7770 
7771   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7772   // was the condition.
7773   OpaqueValueExpr *opaqueValue = nullptr;
7774   Expr *commonExpr = nullptr;
7775   if (!LHSExpr) {
7776     commonExpr = CondExpr;
7777     // Lower out placeholder types first.  This is important so that we don't
7778     // try to capture a placeholder. This happens in few cases in C++; such
7779     // as Objective-C++'s dictionary subscripting syntax.
7780     if (commonExpr->hasPlaceholderType()) {
7781       ExprResult result = CheckPlaceholderExpr(commonExpr);
7782       if (!result.isUsable()) return ExprError();
7783       commonExpr = result.get();
7784     }
7785     // We usually want to apply unary conversions *before* saving, except
7786     // in the special case of a C++ l-value conditional.
7787     if (!(getLangOpts().CPlusPlus
7788           && !commonExpr->isTypeDependent()
7789           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7790           && commonExpr->isGLValue()
7791           && commonExpr->isOrdinaryOrBitFieldObject()
7792           && RHSExpr->isOrdinaryOrBitFieldObject()
7793           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7794       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7795       if (commonRes.isInvalid())
7796         return ExprError();
7797       commonExpr = commonRes.get();
7798     }
7799 
7800     // If the common expression is a class or array prvalue, materialize it
7801     // so that we can safely refer to it multiple times.
7802     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7803                                    commonExpr->getType()->isArrayType())) {
7804       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7805       if (MatExpr.isInvalid())
7806         return ExprError();
7807       commonExpr = MatExpr.get();
7808     }
7809 
7810     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7811                                                 commonExpr->getType(),
7812                                                 commonExpr->getValueKind(),
7813                                                 commonExpr->getObjectKind(),
7814                                                 commonExpr);
7815     LHSExpr = CondExpr = opaqueValue;
7816   }
7817 
7818   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7819   ExprValueKind VK = VK_RValue;
7820   ExprObjectKind OK = OK_Ordinary;
7821   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7822   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7823                                              VK, OK, QuestionLoc);
7824   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7825       RHS.isInvalid())
7826     return ExprError();
7827 
7828   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7829                                 RHS.get());
7830 
7831   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7832 
7833   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7834                                          Context);
7835 
7836   if (!commonExpr)
7837     return new (Context)
7838         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7839                             RHS.get(), result, VK, OK);
7840 
7841   return new (Context) BinaryConditionalOperator(
7842       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7843       ColonLoc, result, VK, OK);
7844 }
7845 
7846 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7847 // being closely modeled after the C99 spec:-). The odd characteristic of this
7848 // routine is it effectively iqnores the qualifiers on the top level pointee.
7849 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7850 // FIXME: add a couple examples in this comment.
7851 static Sema::AssignConvertType
7852 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7853   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7854   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7855 
7856   // get the "pointed to" type (ignoring qualifiers at the top level)
7857   const Type *lhptee, *rhptee;
7858   Qualifiers lhq, rhq;
7859   std::tie(lhptee, lhq) =
7860       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7861   std::tie(rhptee, rhq) =
7862       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7863 
7864   Sema::AssignConvertType ConvTy = Sema::Compatible;
7865 
7866   // C99 6.5.16.1p1: This following citation is common to constraints
7867   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7868   // qualifiers of the type *pointed to* by the right;
7869 
7870   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7871   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7872       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7873     // Ignore lifetime for further calculation.
7874     lhq.removeObjCLifetime();
7875     rhq.removeObjCLifetime();
7876   }
7877 
7878   if (!lhq.compatiblyIncludes(rhq)) {
7879     // Treat address-space mismatches as fatal.
7880     if (!lhq.isAddressSpaceSupersetOf(rhq))
7881       return Sema::IncompatiblePointerDiscardsQualifiers;
7882 
7883     // It's okay to add or remove GC or lifetime qualifiers when converting to
7884     // and from void*.
7885     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7886                         .compatiblyIncludes(
7887                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7888              && (lhptee->isVoidType() || rhptee->isVoidType()))
7889       ; // keep old
7890 
7891     // Treat lifetime mismatches as fatal.
7892     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7893       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7894 
7895     // For GCC/MS compatibility, other qualifier mismatches are treated
7896     // as still compatible in C.
7897     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7898   }
7899 
7900   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7901   // incomplete type and the other is a pointer to a qualified or unqualified
7902   // version of void...
7903   if (lhptee->isVoidType()) {
7904     if (rhptee->isIncompleteOrObjectType())
7905       return ConvTy;
7906 
7907     // As an extension, we allow cast to/from void* to function pointer.
7908     assert(rhptee->isFunctionType());
7909     return Sema::FunctionVoidPointer;
7910   }
7911 
7912   if (rhptee->isVoidType()) {
7913     if (lhptee->isIncompleteOrObjectType())
7914       return ConvTy;
7915 
7916     // As an extension, we allow cast to/from void* to function pointer.
7917     assert(lhptee->isFunctionType());
7918     return Sema::FunctionVoidPointer;
7919   }
7920 
7921   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7922   // unqualified versions of compatible types, ...
7923   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7924   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7925     // Check if the pointee types are compatible ignoring the sign.
7926     // We explicitly check for char so that we catch "char" vs
7927     // "unsigned char" on systems where "char" is unsigned.
7928     if (lhptee->isCharType())
7929       ltrans = S.Context.UnsignedCharTy;
7930     else if (lhptee->hasSignedIntegerRepresentation())
7931       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7932 
7933     if (rhptee->isCharType())
7934       rtrans = S.Context.UnsignedCharTy;
7935     else if (rhptee->hasSignedIntegerRepresentation())
7936       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7937 
7938     if (ltrans == rtrans) {
7939       // Types are compatible ignoring the sign. Qualifier incompatibility
7940       // takes priority over sign incompatibility because the sign
7941       // warning can be disabled.
7942       if (ConvTy != Sema::Compatible)
7943         return ConvTy;
7944 
7945       return Sema::IncompatiblePointerSign;
7946     }
7947 
7948     // If we are a multi-level pointer, it's possible that our issue is simply
7949     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7950     // the eventual target type is the same and the pointers have the same
7951     // level of indirection, this must be the issue.
7952     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7953       do {
7954         std::tie(lhptee, lhq) =
7955           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7956         std::tie(rhptee, rhq) =
7957           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7958 
7959         // Inconsistent address spaces at this point is invalid, even if the
7960         // address spaces would be compatible.
7961         // FIXME: This doesn't catch address space mismatches for pointers of
7962         // different nesting levels, like:
7963         //   __local int *** a;
7964         //   int ** b = a;
7965         // It's not clear how to actually determine when such pointers are
7966         // invalidly incompatible.
7967         if (lhq.getAddressSpace() != rhq.getAddressSpace())
7968           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
7969 
7970       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7971 
7972       if (lhptee == rhptee)
7973         return Sema::IncompatibleNestedPointerQualifiers;
7974     }
7975 
7976     // General pointer incompatibility takes priority over qualifiers.
7977     return Sema::IncompatiblePointer;
7978   }
7979   if (!S.getLangOpts().CPlusPlus &&
7980       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7981     return Sema::IncompatiblePointer;
7982   return ConvTy;
7983 }
7984 
7985 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7986 /// block pointer types are compatible or whether a block and normal pointer
7987 /// are compatible. It is more restrict than comparing two function pointer
7988 // types.
7989 static Sema::AssignConvertType
7990 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7991                                     QualType RHSType) {
7992   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7993   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7994 
7995   QualType lhptee, rhptee;
7996 
7997   // get the "pointed to" type (ignoring qualifiers at the top level)
7998   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7999   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8000 
8001   // In C++, the types have to match exactly.
8002   if (S.getLangOpts().CPlusPlus)
8003     return Sema::IncompatibleBlockPointer;
8004 
8005   Sema::AssignConvertType ConvTy = Sema::Compatible;
8006 
8007   // For blocks we enforce that qualifiers are identical.
8008   Qualifiers LQuals = lhptee.getLocalQualifiers();
8009   Qualifiers RQuals = rhptee.getLocalQualifiers();
8010   if (S.getLangOpts().OpenCL) {
8011     LQuals.removeAddressSpace();
8012     RQuals.removeAddressSpace();
8013   }
8014   if (LQuals != RQuals)
8015     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8016 
8017   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8018   // assignment.
8019   // The current behavior is similar to C++ lambdas. A block might be
8020   // assigned to a variable iff its return type and parameters are compatible
8021   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8022   // an assignment. Presumably it should behave in way that a function pointer
8023   // assignment does in C, so for each parameter and return type:
8024   //  * CVR and address space of LHS should be a superset of CVR and address
8025   //  space of RHS.
8026   //  * unqualified types should be compatible.
8027   if (S.getLangOpts().OpenCL) {
8028     if (!S.Context.typesAreBlockPointerCompatible(
8029             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8030             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8031       return Sema::IncompatibleBlockPointer;
8032   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8033     return Sema::IncompatibleBlockPointer;
8034 
8035   return ConvTy;
8036 }
8037 
8038 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8039 /// for assignment compatibility.
8040 static Sema::AssignConvertType
8041 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8042                                    QualType RHSType) {
8043   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8044   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8045 
8046   if (LHSType->isObjCBuiltinType()) {
8047     // Class is not compatible with ObjC object pointers.
8048     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8049         !RHSType->isObjCQualifiedClassType())
8050       return Sema::IncompatiblePointer;
8051     return Sema::Compatible;
8052   }
8053   if (RHSType->isObjCBuiltinType()) {
8054     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8055         !LHSType->isObjCQualifiedClassType())
8056       return Sema::IncompatiblePointer;
8057     return Sema::Compatible;
8058   }
8059   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
8060   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
8061 
8062   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8063       // make an exception for id<P>
8064       !LHSType->isObjCQualifiedIdType())
8065     return Sema::CompatiblePointerDiscardsQualifiers;
8066 
8067   if (S.Context.typesAreCompatible(LHSType, RHSType))
8068     return Sema::Compatible;
8069   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8070     return Sema::IncompatibleObjCQualifiedId;
8071   return Sema::IncompatiblePointer;
8072 }
8073 
8074 Sema::AssignConvertType
8075 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8076                                  QualType LHSType, QualType RHSType) {
8077   // Fake up an opaque expression.  We don't actually care about what
8078   // cast operations are required, so if CheckAssignmentConstraints
8079   // adds casts to this they'll be wasted, but fortunately that doesn't
8080   // usually happen on valid code.
8081   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8082   ExprResult RHSPtr = &RHSExpr;
8083   CastKind K;
8084 
8085   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8086 }
8087 
8088 /// This helper function returns true if QT is a vector type that has element
8089 /// type ElementType.
8090 static bool isVector(QualType QT, QualType ElementType) {
8091   if (const VectorType *VT = QT->getAs<VectorType>())
8092     return VT->getElementType() == ElementType;
8093   return false;
8094 }
8095 
8096 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8097 /// has code to accommodate several GCC extensions when type checking
8098 /// pointers. Here are some objectionable examples that GCC considers warnings:
8099 ///
8100 ///  int a, *pint;
8101 ///  short *pshort;
8102 ///  struct foo *pfoo;
8103 ///
8104 ///  pint = pshort; // warning: assignment from incompatible pointer type
8105 ///  a = pint; // warning: assignment makes integer from pointer without a cast
8106 ///  pint = a; // warning: assignment makes pointer from integer without a cast
8107 ///  pint = pfoo; // warning: assignment from incompatible pointer type
8108 ///
8109 /// As a result, the code for dealing with pointers is more complex than the
8110 /// C99 spec dictates.
8111 ///
8112 /// Sets 'Kind' for any result kind except Incompatible.
8113 Sema::AssignConvertType
8114 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8115                                  CastKind &Kind, bool ConvertRHS) {
8116   QualType RHSType = RHS.get()->getType();
8117   QualType OrigLHSType = LHSType;
8118 
8119   // Get canonical types.  We're not formatting these types, just comparing
8120   // them.
8121   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8122   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8123 
8124   // Common case: no conversion required.
8125   if (LHSType == RHSType) {
8126     Kind = CK_NoOp;
8127     return Compatible;
8128   }
8129 
8130   // If we have an atomic type, try a non-atomic assignment, then just add an
8131   // atomic qualification step.
8132   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8133     Sema::AssignConvertType result =
8134       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8135     if (result != Compatible)
8136       return result;
8137     if (Kind != CK_NoOp && ConvertRHS)
8138       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8139     Kind = CK_NonAtomicToAtomic;
8140     return Compatible;
8141   }
8142 
8143   // If the left-hand side is a reference type, then we are in a
8144   // (rare!) case where we've allowed the use of references in C,
8145   // e.g., as a parameter type in a built-in function. In this case,
8146   // just make sure that the type referenced is compatible with the
8147   // right-hand side type. The caller is responsible for adjusting
8148   // LHSType so that the resulting expression does not have reference
8149   // type.
8150   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8151     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8152       Kind = CK_LValueBitCast;
8153       return Compatible;
8154     }
8155     return Incompatible;
8156   }
8157 
8158   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8159   // to the same ExtVector type.
8160   if (LHSType->isExtVectorType()) {
8161     if (RHSType->isExtVectorType())
8162       return Incompatible;
8163     if (RHSType->isArithmeticType()) {
8164       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8165       if (ConvertRHS)
8166         RHS = prepareVectorSplat(LHSType, RHS.get());
8167       Kind = CK_VectorSplat;
8168       return Compatible;
8169     }
8170   }
8171 
8172   // Conversions to or from vector type.
8173   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8174     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8175       // Allow assignments of an AltiVec vector type to an equivalent GCC
8176       // vector type and vice versa
8177       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8178         Kind = CK_BitCast;
8179         return Compatible;
8180       }
8181 
8182       // If we are allowing lax vector conversions, and LHS and RHS are both
8183       // vectors, the total size only needs to be the same. This is a bitcast;
8184       // no bits are changed but the result type is different.
8185       if (isLaxVectorConversion(RHSType, LHSType)) {
8186         Kind = CK_BitCast;
8187         return IncompatibleVectors;
8188       }
8189     }
8190 
8191     // When the RHS comes from another lax conversion (e.g. binops between
8192     // scalars and vectors) the result is canonicalized as a vector. When the
8193     // LHS is also a vector, the lax is allowed by the condition above. Handle
8194     // the case where LHS is a scalar.
8195     if (LHSType->isScalarType()) {
8196       const VectorType *VecType = RHSType->getAs<VectorType>();
8197       if (VecType && VecType->getNumElements() == 1 &&
8198           isLaxVectorConversion(RHSType, LHSType)) {
8199         ExprResult *VecExpr = &RHS;
8200         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8201         Kind = CK_BitCast;
8202         return Compatible;
8203       }
8204     }
8205 
8206     return Incompatible;
8207   }
8208 
8209   // Diagnose attempts to convert between __float128 and long double where
8210   // such conversions currently can't be handled.
8211   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8212     return Incompatible;
8213 
8214   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8215   // discards the imaginary part.
8216   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8217       !LHSType->getAs<ComplexType>())
8218     return Incompatible;
8219 
8220   // Arithmetic conversions.
8221   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8222       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8223     if (ConvertRHS)
8224       Kind = PrepareScalarCast(RHS, LHSType);
8225     return Compatible;
8226   }
8227 
8228   // Conversions to normal pointers.
8229   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8230     // U* -> T*
8231     if (isa<PointerType>(RHSType)) {
8232       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8233       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8234       if (AddrSpaceL != AddrSpaceR)
8235         Kind = CK_AddressSpaceConversion;
8236       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8237         Kind = CK_NoOp;
8238       else
8239         Kind = CK_BitCast;
8240       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8241     }
8242 
8243     // int -> T*
8244     if (RHSType->isIntegerType()) {
8245       Kind = CK_IntegralToPointer; // FIXME: null?
8246       return IntToPointer;
8247     }
8248 
8249     // C pointers are not compatible with ObjC object pointers,
8250     // with two exceptions:
8251     if (isa<ObjCObjectPointerType>(RHSType)) {
8252       //  - conversions to void*
8253       if (LHSPointer->getPointeeType()->isVoidType()) {
8254         Kind = CK_BitCast;
8255         return Compatible;
8256       }
8257 
8258       //  - conversions from 'Class' to the redefinition type
8259       if (RHSType->isObjCClassType() &&
8260           Context.hasSameType(LHSType,
8261                               Context.getObjCClassRedefinitionType())) {
8262         Kind = CK_BitCast;
8263         return Compatible;
8264       }
8265 
8266       Kind = CK_BitCast;
8267       return IncompatiblePointer;
8268     }
8269 
8270     // U^ -> void*
8271     if (RHSType->getAs<BlockPointerType>()) {
8272       if (LHSPointer->getPointeeType()->isVoidType()) {
8273         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8274         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8275                                 ->getPointeeType()
8276                                 .getAddressSpace();
8277         Kind =
8278             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8279         return Compatible;
8280       }
8281     }
8282 
8283     return Incompatible;
8284   }
8285 
8286   // Conversions to block pointers.
8287   if (isa<BlockPointerType>(LHSType)) {
8288     // U^ -> T^
8289     if (RHSType->isBlockPointerType()) {
8290       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8291                               ->getPointeeType()
8292                               .getAddressSpace();
8293       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8294                               ->getPointeeType()
8295                               .getAddressSpace();
8296       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8297       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8298     }
8299 
8300     // int or null -> T^
8301     if (RHSType->isIntegerType()) {
8302       Kind = CK_IntegralToPointer; // FIXME: null
8303       return IntToBlockPointer;
8304     }
8305 
8306     // id -> T^
8307     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8308       Kind = CK_AnyPointerToBlockPointerCast;
8309       return Compatible;
8310     }
8311 
8312     // void* -> T^
8313     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8314       if (RHSPT->getPointeeType()->isVoidType()) {
8315         Kind = CK_AnyPointerToBlockPointerCast;
8316         return Compatible;
8317       }
8318 
8319     return Incompatible;
8320   }
8321 
8322   // Conversions to Objective-C pointers.
8323   if (isa<ObjCObjectPointerType>(LHSType)) {
8324     // A* -> B*
8325     if (RHSType->isObjCObjectPointerType()) {
8326       Kind = CK_BitCast;
8327       Sema::AssignConvertType result =
8328         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8329       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8330           result == Compatible &&
8331           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8332         result = IncompatibleObjCWeakRef;
8333       return result;
8334     }
8335 
8336     // int or null -> A*
8337     if (RHSType->isIntegerType()) {
8338       Kind = CK_IntegralToPointer; // FIXME: null
8339       return IntToPointer;
8340     }
8341 
8342     // In general, C pointers are not compatible with ObjC object pointers,
8343     // with two exceptions:
8344     if (isa<PointerType>(RHSType)) {
8345       Kind = CK_CPointerToObjCPointerCast;
8346 
8347       //  - conversions from 'void*'
8348       if (RHSType->isVoidPointerType()) {
8349         return Compatible;
8350       }
8351 
8352       //  - conversions to 'Class' from its redefinition type
8353       if (LHSType->isObjCClassType() &&
8354           Context.hasSameType(RHSType,
8355                               Context.getObjCClassRedefinitionType())) {
8356         return Compatible;
8357       }
8358 
8359       return IncompatiblePointer;
8360     }
8361 
8362     // Only under strict condition T^ is compatible with an Objective-C pointer.
8363     if (RHSType->isBlockPointerType() &&
8364         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8365       if (ConvertRHS)
8366         maybeExtendBlockObject(RHS);
8367       Kind = CK_BlockPointerToObjCPointerCast;
8368       return Compatible;
8369     }
8370 
8371     return Incompatible;
8372   }
8373 
8374   // Conversions from pointers that are not covered by the above.
8375   if (isa<PointerType>(RHSType)) {
8376     // T* -> _Bool
8377     if (LHSType == Context.BoolTy) {
8378       Kind = CK_PointerToBoolean;
8379       return Compatible;
8380     }
8381 
8382     // T* -> int
8383     if (LHSType->isIntegerType()) {
8384       Kind = CK_PointerToIntegral;
8385       return PointerToInt;
8386     }
8387 
8388     return Incompatible;
8389   }
8390 
8391   // Conversions from Objective-C pointers that are not covered by the above.
8392   if (isa<ObjCObjectPointerType>(RHSType)) {
8393     // T* -> _Bool
8394     if (LHSType == Context.BoolTy) {
8395       Kind = CK_PointerToBoolean;
8396       return Compatible;
8397     }
8398 
8399     // T* -> int
8400     if (LHSType->isIntegerType()) {
8401       Kind = CK_PointerToIntegral;
8402       return PointerToInt;
8403     }
8404 
8405     return Incompatible;
8406   }
8407 
8408   // struct A -> struct B
8409   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8410     if (Context.typesAreCompatible(LHSType, RHSType)) {
8411       Kind = CK_NoOp;
8412       return Compatible;
8413     }
8414   }
8415 
8416   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8417     Kind = CK_IntToOCLSampler;
8418     return Compatible;
8419   }
8420 
8421   return Incompatible;
8422 }
8423 
8424 /// Constructs a transparent union from an expression that is
8425 /// used to initialize the transparent union.
8426 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8427                                       ExprResult &EResult, QualType UnionType,
8428                                       FieldDecl *Field) {
8429   // Build an initializer list that designates the appropriate member
8430   // of the transparent union.
8431   Expr *E = EResult.get();
8432   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8433                                                    E, SourceLocation());
8434   Initializer->setType(UnionType);
8435   Initializer->setInitializedFieldInUnion(Field);
8436 
8437   // Build a compound literal constructing a value of the transparent
8438   // union type from this initializer list.
8439   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8440   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8441                                         VK_RValue, Initializer, false);
8442 }
8443 
8444 Sema::AssignConvertType
8445 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8446                                                ExprResult &RHS) {
8447   QualType RHSType = RHS.get()->getType();
8448 
8449   // If the ArgType is a Union type, we want to handle a potential
8450   // transparent_union GCC extension.
8451   const RecordType *UT = ArgType->getAsUnionType();
8452   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8453     return Incompatible;
8454 
8455   // The field to initialize within the transparent union.
8456   RecordDecl *UD = UT->getDecl();
8457   FieldDecl *InitField = nullptr;
8458   // It's compatible if the expression matches any of the fields.
8459   for (auto *it : UD->fields()) {
8460     if (it->getType()->isPointerType()) {
8461       // If the transparent union contains a pointer type, we allow:
8462       // 1) void pointer
8463       // 2) null pointer constant
8464       if (RHSType->isPointerType())
8465         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8466           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8467           InitField = it;
8468           break;
8469         }
8470 
8471       if (RHS.get()->isNullPointerConstant(Context,
8472                                            Expr::NPC_ValueDependentIsNull)) {
8473         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8474                                 CK_NullToPointer);
8475         InitField = it;
8476         break;
8477       }
8478     }
8479 
8480     CastKind Kind;
8481     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8482           == Compatible) {
8483       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8484       InitField = it;
8485       break;
8486     }
8487   }
8488 
8489   if (!InitField)
8490     return Incompatible;
8491 
8492   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8493   return Compatible;
8494 }
8495 
8496 Sema::AssignConvertType
8497 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8498                                        bool Diagnose,
8499                                        bool DiagnoseCFAudited,
8500                                        bool ConvertRHS) {
8501   // We need to be able to tell the caller whether we diagnosed a problem, if
8502   // they ask us to issue diagnostics.
8503   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8504 
8505   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8506   // we can't avoid *all* modifications at the moment, so we need some somewhere
8507   // to put the updated value.
8508   ExprResult LocalRHS = CallerRHS;
8509   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8510 
8511   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8512     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8513       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8514           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8515         Diag(RHS.get()->getExprLoc(),
8516              diag::warn_noderef_to_dereferenceable_pointer)
8517             << RHS.get()->getSourceRange();
8518       }
8519     }
8520   }
8521 
8522   if (getLangOpts().CPlusPlus) {
8523     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8524       // C++ 5.17p3: If the left operand is not of class type, the
8525       // expression is implicitly converted (C++ 4) to the
8526       // cv-unqualified type of the left operand.
8527       QualType RHSType = RHS.get()->getType();
8528       if (Diagnose) {
8529         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8530                                         AA_Assigning);
8531       } else {
8532         ImplicitConversionSequence ICS =
8533             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8534                                   /*SuppressUserConversions=*/false,
8535                                   /*AllowExplicit=*/false,
8536                                   /*InOverloadResolution=*/false,
8537                                   /*CStyle=*/false,
8538                                   /*AllowObjCWritebackConversion=*/false);
8539         if (ICS.isFailure())
8540           return Incompatible;
8541         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8542                                         ICS, AA_Assigning);
8543       }
8544       if (RHS.isInvalid())
8545         return Incompatible;
8546       Sema::AssignConvertType result = Compatible;
8547       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8548           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8549         result = IncompatibleObjCWeakRef;
8550       return result;
8551     }
8552 
8553     // FIXME: Currently, we fall through and treat C++ classes like C
8554     // structures.
8555     // FIXME: We also fall through for atomics; not sure what should
8556     // happen there, though.
8557   } else if (RHS.get()->getType() == Context.OverloadTy) {
8558     // As a set of extensions to C, we support overloading on functions. These
8559     // functions need to be resolved here.
8560     DeclAccessPair DAP;
8561     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8562             RHS.get(), LHSType, /*Complain=*/false, DAP))
8563       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8564     else
8565       return Incompatible;
8566   }
8567 
8568   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8569   // a null pointer constant.
8570   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8571        LHSType->isBlockPointerType()) &&
8572       RHS.get()->isNullPointerConstant(Context,
8573                                        Expr::NPC_ValueDependentIsNull)) {
8574     if (Diagnose || ConvertRHS) {
8575       CastKind Kind;
8576       CXXCastPath Path;
8577       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8578                              /*IgnoreBaseAccess=*/false, Diagnose);
8579       if (ConvertRHS)
8580         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8581     }
8582     return Compatible;
8583   }
8584 
8585   // OpenCL queue_t type assignment.
8586   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8587                                  Context, Expr::NPC_ValueDependentIsNull)) {
8588     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8589     return Compatible;
8590   }
8591 
8592   // This check seems unnatural, however it is necessary to ensure the proper
8593   // conversion of functions/arrays. If the conversion were done for all
8594   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8595   // expressions that suppress this implicit conversion (&, sizeof).
8596   //
8597   // Suppress this for references: C++ 8.5.3p5.
8598   if (!LHSType->isReferenceType()) {
8599     // FIXME: We potentially allocate here even if ConvertRHS is false.
8600     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8601     if (RHS.isInvalid())
8602       return Incompatible;
8603   }
8604   CastKind Kind;
8605   Sema::AssignConvertType result =
8606     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8607 
8608   // C99 6.5.16.1p2: The value of the right operand is converted to the
8609   // type of the assignment expression.
8610   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8611   // so that we can use references in built-in functions even in C.
8612   // The getNonReferenceType() call makes sure that the resulting expression
8613   // does not have reference type.
8614   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8615     QualType Ty = LHSType.getNonLValueExprType(Context);
8616     Expr *E = RHS.get();
8617 
8618     // Check for various Objective-C errors. If we are not reporting
8619     // diagnostics and just checking for errors, e.g., during overload
8620     // resolution, return Incompatible to indicate the failure.
8621     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8622         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8623                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8624       if (!Diagnose)
8625         return Incompatible;
8626     }
8627     if (getLangOpts().ObjC &&
8628         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8629                                            E->getType(), E, Diagnose) ||
8630          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8631       if (!Diagnose)
8632         return Incompatible;
8633       // Replace the expression with a corrected version and continue so we
8634       // can find further errors.
8635       RHS = E;
8636       return Compatible;
8637     }
8638 
8639     if (ConvertRHS)
8640       RHS = ImpCastExprToType(E, Ty, Kind);
8641   }
8642 
8643   return result;
8644 }
8645 
8646 namespace {
8647 /// The original operand to an operator, prior to the application of the usual
8648 /// arithmetic conversions and converting the arguments of a builtin operator
8649 /// candidate.
8650 struct OriginalOperand {
8651   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8652     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8653       Op = MTE->GetTemporaryExpr();
8654     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8655       Op = BTE->getSubExpr();
8656     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8657       Orig = ICE->getSubExprAsWritten();
8658       Conversion = ICE->getConversionFunction();
8659     }
8660   }
8661 
8662   QualType getType() const { return Orig->getType(); }
8663 
8664   Expr *Orig;
8665   NamedDecl *Conversion;
8666 };
8667 }
8668 
8669 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8670                                ExprResult &RHS) {
8671   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8672 
8673   Diag(Loc, diag::err_typecheck_invalid_operands)
8674     << OrigLHS.getType() << OrigRHS.getType()
8675     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8676 
8677   // If a user-defined conversion was applied to either of the operands prior
8678   // to applying the built-in operator rules, tell the user about it.
8679   if (OrigLHS.Conversion) {
8680     Diag(OrigLHS.Conversion->getLocation(),
8681          diag::note_typecheck_invalid_operands_converted)
8682       << 0 << LHS.get()->getType();
8683   }
8684   if (OrigRHS.Conversion) {
8685     Diag(OrigRHS.Conversion->getLocation(),
8686          diag::note_typecheck_invalid_operands_converted)
8687       << 1 << RHS.get()->getType();
8688   }
8689 
8690   return QualType();
8691 }
8692 
8693 // Diagnose cases where a scalar was implicitly converted to a vector and
8694 // diagnose the underlying types. Otherwise, diagnose the error
8695 // as invalid vector logical operands for non-C++ cases.
8696 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8697                                             ExprResult &RHS) {
8698   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8699   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8700 
8701   bool LHSNatVec = LHSType->isVectorType();
8702   bool RHSNatVec = RHSType->isVectorType();
8703 
8704   if (!(LHSNatVec && RHSNatVec)) {
8705     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8706     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8707     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8708         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8709         << Vector->getSourceRange();
8710     return QualType();
8711   }
8712 
8713   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8714       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8715       << RHS.get()->getSourceRange();
8716 
8717   return QualType();
8718 }
8719 
8720 /// Try to convert a value of non-vector type to a vector type by converting
8721 /// the type to the element type of the vector and then performing a splat.
8722 /// If the language is OpenCL, we only use conversions that promote scalar
8723 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8724 /// for float->int.
8725 ///
8726 /// OpenCL V2.0 6.2.6.p2:
8727 /// An error shall occur if any scalar operand type has greater rank
8728 /// than the type of the vector element.
8729 ///
8730 /// \param scalar - if non-null, actually perform the conversions
8731 /// \return true if the operation fails (but without diagnosing the failure)
8732 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8733                                      QualType scalarTy,
8734                                      QualType vectorEltTy,
8735                                      QualType vectorTy,
8736                                      unsigned &DiagID) {
8737   // The conversion to apply to the scalar before splatting it,
8738   // if necessary.
8739   CastKind scalarCast = CK_NoOp;
8740 
8741   if (vectorEltTy->isIntegralType(S.Context)) {
8742     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8743         (scalarTy->isIntegerType() &&
8744          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8745       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8746       return true;
8747     }
8748     if (!scalarTy->isIntegralType(S.Context))
8749       return true;
8750     scalarCast = CK_IntegralCast;
8751   } else if (vectorEltTy->isRealFloatingType()) {
8752     if (scalarTy->isRealFloatingType()) {
8753       if (S.getLangOpts().OpenCL &&
8754           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8755         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8756         return true;
8757       }
8758       scalarCast = CK_FloatingCast;
8759     }
8760     else if (scalarTy->isIntegralType(S.Context))
8761       scalarCast = CK_IntegralToFloating;
8762     else
8763       return true;
8764   } else {
8765     return true;
8766   }
8767 
8768   // Adjust scalar if desired.
8769   if (scalar) {
8770     if (scalarCast != CK_NoOp)
8771       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8772     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8773   }
8774   return false;
8775 }
8776 
8777 /// Convert vector E to a vector with the same number of elements but different
8778 /// element type.
8779 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8780   const auto *VecTy = E->getType()->getAs<VectorType>();
8781   assert(VecTy && "Expression E must be a vector");
8782   QualType NewVecTy = S.Context.getVectorType(ElementType,
8783                                               VecTy->getNumElements(),
8784                                               VecTy->getVectorKind());
8785 
8786   // Look through the implicit cast. Return the subexpression if its type is
8787   // NewVecTy.
8788   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8789     if (ICE->getSubExpr()->getType() == NewVecTy)
8790       return ICE->getSubExpr();
8791 
8792   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8793   return S.ImpCastExprToType(E, NewVecTy, Cast);
8794 }
8795 
8796 /// Test if a (constant) integer Int can be casted to another integer type
8797 /// IntTy without losing precision.
8798 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8799                                       QualType OtherIntTy) {
8800   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8801 
8802   // Reject cases where the value of the Int is unknown as that would
8803   // possibly cause truncation, but accept cases where the scalar can be
8804   // demoted without loss of precision.
8805   Expr::EvalResult EVResult;
8806   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8807   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8808   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8809   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8810 
8811   if (CstInt) {
8812     // If the scalar is constant and is of a higher order and has more active
8813     // bits that the vector element type, reject it.
8814     llvm::APSInt Result = EVResult.Val.getInt();
8815     unsigned NumBits = IntSigned
8816                            ? (Result.isNegative() ? Result.getMinSignedBits()
8817                                                   : Result.getActiveBits())
8818                            : Result.getActiveBits();
8819     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8820       return true;
8821 
8822     // If the signedness of the scalar type and the vector element type
8823     // differs and the number of bits is greater than that of the vector
8824     // element reject it.
8825     return (IntSigned != OtherIntSigned &&
8826             NumBits > S.Context.getIntWidth(OtherIntTy));
8827   }
8828 
8829   // Reject cases where the value of the scalar is not constant and it's
8830   // order is greater than that of the vector element type.
8831   return (Order < 0);
8832 }
8833 
8834 /// Test if a (constant) integer Int can be casted to floating point type
8835 /// FloatTy without losing precision.
8836 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8837                                      QualType FloatTy) {
8838   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8839 
8840   // Determine if the integer constant can be expressed as a floating point
8841   // number of the appropriate type.
8842   Expr::EvalResult EVResult;
8843   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8844 
8845   uint64_t Bits = 0;
8846   if (CstInt) {
8847     // Reject constants that would be truncated if they were converted to
8848     // the floating point type. Test by simple to/from conversion.
8849     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8850     //        could be avoided if there was a convertFromAPInt method
8851     //        which could signal back if implicit truncation occurred.
8852     llvm::APSInt Result = EVResult.Val.getInt();
8853     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8854     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8855                            llvm::APFloat::rmTowardZero);
8856     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8857                              !IntTy->hasSignedIntegerRepresentation());
8858     bool Ignored = false;
8859     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8860                            &Ignored);
8861     if (Result != ConvertBack)
8862       return true;
8863   } else {
8864     // Reject types that cannot be fully encoded into the mantissa of
8865     // the float.
8866     Bits = S.Context.getTypeSize(IntTy);
8867     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8868         S.Context.getFloatTypeSemantics(FloatTy));
8869     if (Bits > FloatPrec)
8870       return true;
8871   }
8872 
8873   return false;
8874 }
8875 
8876 /// Attempt to convert and splat Scalar into a vector whose types matches
8877 /// Vector following GCC conversion rules. The rule is that implicit
8878 /// conversion can occur when Scalar can be casted to match Vector's element
8879 /// type without causing truncation of Scalar.
8880 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8881                                         ExprResult *Vector) {
8882   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8883   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8884   const VectorType *VT = VectorTy->getAs<VectorType>();
8885 
8886   assert(!isa<ExtVectorType>(VT) &&
8887          "ExtVectorTypes should not be handled here!");
8888 
8889   QualType VectorEltTy = VT->getElementType();
8890 
8891   // Reject cases where the vector element type or the scalar element type are
8892   // not integral or floating point types.
8893   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8894     return true;
8895 
8896   // The conversion to apply to the scalar before splatting it,
8897   // if necessary.
8898   CastKind ScalarCast = CK_NoOp;
8899 
8900   // Accept cases where the vector elements are integers and the scalar is
8901   // an integer.
8902   // FIXME: Notionally if the scalar was a floating point value with a precise
8903   //        integral representation, we could cast it to an appropriate integer
8904   //        type and then perform the rest of the checks here. GCC will perform
8905   //        this conversion in some cases as determined by the input language.
8906   //        We should accept it on a language independent basis.
8907   if (VectorEltTy->isIntegralType(S.Context) &&
8908       ScalarTy->isIntegralType(S.Context) &&
8909       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8910 
8911     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8912       return true;
8913 
8914     ScalarCast = CK_IntegralCast;
8915   } else if (VectorEltTy->isRealFloatingType()) {
8916     if (ScalarTy->isRealFloatingType()) {
8917 
8918       // Reject cases where the scalar type is not a constant and has a higher
8919       // Order than the vector element type.
8920       llvm::APFloat Result(0.0);
8921       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8922       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8923       if (!CstScalar && Order < 0)
8924         return true;
8925 
8926       // If the scalar cannot be safely casted to the vector element type,
8927       // reject it.
8928       if (CstScalar) {
8929         bool Truncated = false;
8930         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8931                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8932         if (Truncated)
8933           return true;
8934       }
8935 
8936       ScalarCast = CK_FloatingCast;
8937     } else if (ScalarTy->isIntegralType(S.Context)) {
8938       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8939         return true;
8940 
8941       ScalarCast = CK_IntegralToFloating;
8942     } else
8943       return true;
8944   }
8945 
8946   // Adjust scalar if desired.
8947   if (Scalar) {
8948     if (ScalarCast != CK_NoOp)
8949       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8950     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8951   }
8952   return false;
8953 }
8954 
8955 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8956                                    SourceLocation Loc, bool IsCompAssign,
8957                                    bool AllowBothBool,
8958                                    bool AllowBoolConversions) {
8959   if (!IsCompAssign) {
8960     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8961     if (LHS.isInvalid())
8962       return QualType();
8963   }
8964   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8965   if (RHS.isInvalid())
8966     return QualType();
8967 
8968   // For conversion purposes, we ignore any qualifiers.
8969   // For example, "const float" and "float" are equivalent.
8970   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8971   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8972 
8973   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8974   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8975   assert(LHSVecType || RHSVecType);
8976 
8977   // AltiVec-style "vector bool op vector bool" combinations are allowed
8978   // for some operators but not others.
8979   if (!AllowBothBool &&
8980       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8981       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8982     return InvalidOperands(Loc, LHS, RHS);
8983 
8984   // If the vector types are identical, return.
8985   if (Context.hasSameType(LHSType, RHSType))
8986     return LHSType;
8987 
8988   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8989   if (LHSVecType && RHSVecType &&
8990       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8991     if (isa<ExtVectorType>(LHSVecType)) {
8992       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8993       return LHSType;
8994     }
8995 
8996     if (!IsCompAssign)
8997       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8998     return RHSType;
8999   }
9000 
9001   // AllowBoolConversions says that bool and non-bool AltiVec vectors
9002   // can be mixed, with the result being the non-bool type.  The non-bool
9003   // operand must have integer element type.
9004   if (AllowBoolConversions && LHSVecType && RHSVecType &&
9005       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9006       (Context.getTypeSize(LHSVecType->getElementType()) ==
9007        Context.getTypeSize(RHSVecType->getElementType()))) {
9008     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9009         LHSVecType->getElementType()->isIntegerType() &&
9010         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9011       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9012       return LHSType;
9013     }
9014     if (!IsCompAssign &&
9015         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9016         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9017         RHSVecType->getElementType()->isIntegerType()) {
9018       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9019       return RHSType;
9020     }
9021   }
9022 
9023   // If there's a vector type and a scalar, try to convert the scalar to
9024   // the vector element type and splat.
9025   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9026   if (!RHSVecType) {
9027     if (isa<ExtVectorType>(LHSVecType)) {
9028       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9029                                     LHSVecType->getElementType(), LHSType,
9030                                     DiagID))
9031         return LHSType;
9032     } else {
9033       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9034         return LHSType;
9035     }
9036   }
9037   if (!LHSVecType) {
9038     if (isa<ExtVectorType>(RHSVecType)) {
9039       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9040                                     LHSType, RHSVecType->getElementType(),
9041                                     RHSType, DiagID))
9042         return RHSType;
9043     } else {
9044       if (LHS.get()->getValueKind() == VK_LValue ||
9045           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9046         return RHSType;
9047     }
9048   }
9049 
9050   // FIXME: The code below also handles conversion between vectors and
9051   // non-scalars, we should break this down into fine grained specific checks
9052   // and emit proper diagnostics.
9053   QualType VecType = LHSVecType ? LHSType : RHSType;
9054   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9055   QualType OtherType = LHSVecType ? RHSType : LHSType;
9056   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9057   if (isLaxVectorConversion(OtherType, VecType)) {
9058     // If we're allowing lax vector conversions, only the total (data) size
9059     // needs to be the same. For non compound assignment, if one of the types is
9060     // scalar, the result is always the vector type.
9061     if (!IsCompAssign) {
9062       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9063       return VecType;
9064     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9065     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9066     // type. Note that this is already done by non-compound assignments in
9067     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9068     // <1 x T> -> T. The result is also a vector type.
9069     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9070                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9071       ExprResult *RHSExpr = &RHS;
9072       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9073       return VecType;
9074     }
9075   }
9076 
9077   // Okay, the expression is invalid.
9078 
9079   // If there's a non-vector, non-real operand, diagnose that.
9080   if ((!RHSVecType && !RHSType->isRealType()) ||
9081       (!LHSVecType && !LHSType->isRealType())) {
9082     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9083       << LHSType << RHSType
9084       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9085     return QualType();
9086   }
9087 
9088   // OpenCL V1.1 6.2.6.p1:
9089   // If the operands are of more than one vector type, then an error shall
9090   // occur. Implicit conversions between vector types are not permitted, per
9091   // section 6.2.1.
9092   if (getLangOpts().OpenCL &&
9093       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9094       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9095     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9096                                                            << RHSType;
9097     return QualType();
9098   }
9099 
9100 
9101   // If there is a vector type that is not a ExtVector and a scalar, we reach
9102   // this point if scalar could not be converted to the vector's element type
9103   // without truncation.
9104   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9105       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9106     QualType Scalar = LHSVecType ? RHSType : LHSType;
9107     QualType Vector = LHSVecType ? LHSType : RHSType;
9108     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9109     Diag(Loc,
9110          diag::err_typecheck_vector_not_convertable_implict_truncation)
9111         << ScalarOrVector << Scalar << Vector;
9112 
9113     return QualType();
9114   }
9115 
9116   // Otherwise, use the generic diagnostic.
9117   Diag(Loc, DiagID)
9118     << LHSType << RHSType
9119     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9120   return QualType();
9121 }
9122 
9123 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
9124 // expression.  These are mainly cases where the null pointer is used as an
9125 // integer instead of a pointer.
9126 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9127                                 SourceLocation Loc, bool IsCompare) {
9128   // The canonical way to check for a GNU null is with isNullPointerConstant,
9129   // but we use a bit of a hack here for speed; this is a relatively
9130   // hot path, and isNullPointerConstant is slow.
9131   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9132   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9133 
9134   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9135 
9136   // Avoid analyzing cases where the result will either be invalid (and
9137   // diagnosed as such) or entirely valid and not something to warn about.
9138   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9139       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9140     return;
9141 
9142   // Comparison operations would not make sense with a null pointer no matter
9143   // what the other expression is.
9144   if (!IsCompare) {
9145     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9146         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9147         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9148     return;
9149   }
9150 
9151   // The rest of the operations only make sense with a null pointer
9152   // if the other expression is a pointer.
9153   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9154       NonNullType->canDecayToPointerType())
9155     return;
9156 
9157   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9158       << LHSNull /* LHS is NULL */ << NonNullType
9159       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9160 }
9161 
9162 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9163                                           SourceLocation Loc) {
9164   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9165   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9166   if (!LUE || !RUE)
9167     return;
9168   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9169       RUE->getKind() != UETT_SizeOf)
9170     return;
9171 
9172   const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9173   QualType LHSTy = LHSArg->getType();
9174   QualType RHSTy;
9175 
9176   if (RUE->isArgumentType())
9177     RHSTy = RUE->getArgumentType();
9178   else
9179     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9180 
9181   if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9182     if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9183       return;
9184 
9185     S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9186     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9187       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9188         S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9189             << LHSArgDecl;
9190     }
9191   } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9192     QualType ArrayElemTy = ArrayTy->getElementType();
9193     if (ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9194         S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9195       return;
9196     S.Diag(Loc, diag::warn_division_sizeof_array)
9197         << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9198     if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9199       if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9200         S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9201             << LHSArgDecl;
9202     }
9203   }
9204 }
9205 
9206 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9207                                                ExprResult &RHS,
9208                                                SourceLocation Loc, bool IsDiv) {
9209   // Check for division/remainder by zero.
9210   Expr::EvalResult RHSValue;
9211   if (!RHS.get()->isValueDependent() &&
9212       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9213       RHSValue.Val.getInt() == 0)
9214     S.DiagRuntimeBehavior(Loc, RHS.get(),
9215                           S.PDiag(diag::warn_remainder_division_by_zero)
9216                             << IsDiv << RHS.get()->getSourceRange());
9217 }
9218 
9219 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9220                                            SourceLocation Loc,
9221                                            bool IsCompAssign, bool IsDiv) {
9222   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9223 
9224   if (LHS.get()->getType()->isVectorType() ||
9225       RHS.get()->getType()->isVectorType())
9226     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9227                                /*AllowBothBool*/getLangOpts().AltiVec,
9228                                /*AllowBoolConversions*/false);
9229 
9230   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9231   if (LHS.isInvalid() || RHS.isInvalid())
9232     return QualType();
9233 
9234 
9235   if (compType.isNull() || !compType->isArithmeticType())
9236     return InvalidOperands(Loc, LHS, RHS);
9237   if (IsDiv) {
9238     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9239     DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9240   }
9241   return compType;
9242 }
9243 
9244 QualType Sema::CheckRemainderOperands(
9245   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9246   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9247 
9248   if (LHS.get()->getType()->isVectorType() ||
9249       RHS.get()->getType()->isVectorType()) {
9250     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9251         RHS.get()->getType()->hasIntegerRepresentation())
9252       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9253                                  /*AllowBothBool*/getLangOpts().AltiVec,
9254                                  /*AllowBoolConversions*/false);
9255     return InvalidOperands(Loc, LHS, RHS);
9256   }
9257 
9258   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9259   if (LHS.isInvalid() || RHS.isInvalid())
9260     return QualType();
9261 
9262   if (compType.isNull() || !compType->isIntegerType())
9263     return InvalidOperands(Loc, LHS, RHS);
9264   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9265   return compType;
9266 }
9267 
9268 /// Diagnose invalid arithmetic on two void pointers.
9269 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9270                                                 Expr *LHSExpr, Expr *RHSExpr) {
9271   S.Diag(Loc, S.getLangOpts().CPlusPlus
9272                 ? diag::err_typecheck_pointer_arith_void_type
9273                 : diag::ext_gnu_void_ptr)
9274     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9275                             << RHSExpr->getSourceRange();
9276 }
9277 
9278 /// Diagnose invalid arithmetic on a void pointer.
9279 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9280                                             Expr *Pointer) {
9281   S.Diag(Loc, S.getLangOpts().CPlusPlus
9282                 ? diag::err_typecheck_pointer_arith_void_type
9283                 : diag::ext_gnu_void_ptr)
9284     << 0 /* one pointer */ << Pointer->getSourceRange();
9285 }
9286 
9287 /// Diagnose invalid arithmetic on a null pointer.
9288 ///
9289 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9290 /// idiom, which we recognize as a GNU extension.
9291 ///
9292 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9293                                             Expr *Pointer, bool IsGNUIdiom) {
9294   if (IsGNUIdiom)
9295     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9296       << Pointer->getSourceRange();
9297   else
9298     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9299       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9300 }
9301 
9302 /// Diagnose invalid arithmetic on two function pointers.
9303 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9304                                                     Expr *LHS, Expr *RHS) {
9305   assert(LHS->getType()->isAnyPointerType());
9306   assert(RHS->getType()->isAnyPointerType());
9307   S.Diag(Loc, S.getLangOpts().CPlusPlus
9308                 ? diag::err_typecheck_pointer_arith_function_type
9309                 : diag::ext_gnu_ptr_func_arith)
9310     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9311     // We only show the second type if it differs from the first.
9312     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9313                                                    RHS->getType())
9314     << RHS->getType()->getPointeeType()
9315     << LHS->getSourceRange() << RHS->getSourceRange();
9316 }
9317 
9318 /// Diagnose invalid arithmetic on a function pointer.
9319 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9320                                                 Expr *Pointer) {
9321   assert(Pointer->getType()->isAnyPointerType());
9322   S.Diag(Loc, S.getLangOpts().CPlusPlus
9323                 ? diag::err_typecheck_pointer_arith_function_type
9324                 : diag::ext_gnu_ptr_func_arith)
9325     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9326     << 0 /* one pointer, so only one type */
9327     << Pointer->getSourceRange();
9328 }
9329 
9330 /// Emit error if Operand is incomplete pointer type
9331 ///
9332 /// \returns True if pointer has incomplete type
9333 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9334                                                  Expr *Operand) {
9335   QualType ResType = Operand->getType();
9336   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9337     ResType = ResAtomicType->getValueType();
9338 
9339   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9340   QualType PointeeTy = ResType->getPointeeType();
9341   return S.RequireCompleteType(Loc, PointeeTy,
9342                                diag::err_typecheck_arithmetic_incomplete_type,
9343                                PointeeTy, Operand->getSourceRange());
9344 }
9345 
9346 /// Check the validity of an arithmetic pointer operand.
9347 ///
9348 /// If the operand has pointer type, this code will check for pointer types
9349 /// which are invalid in arithmetic operations. These will be diagnosed
9350 /// appropriately, including whether or not the use is supported as an
9351 /// extension.
9352 ///
9353 /// \returns True when the operand is valid to use (even if as an extension).
9354 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9355                                             Expr *Operand) {
9356   QualType ResType = Operand->getType();
9357   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9358     ResType = ResAtomicType->getValueType();
9359 
9360   if (!ResType->isAnyPointerType()) return true;
9361 
9362   QualType PointeeTy = ResType->getPointeeType();
9363   if (PointeeTy->isVoidType()) {
9364     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9365     return !S.getLangOpts().CPlusPlus;
9366   }
9367   if (PointeeTy->isFunctionType()) {
9368     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9369     return !S.getLangOpts().CPlusPlus;
9370   }
9371 
9372   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9373 
9374   return true;
9375 }
9376 
9377 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9378 /// operands.
9379 ///
9380 /// This routine will diagnose any invalid arithmetic on pointer operands much
9381 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9382 /// for emitting a single diagnostic even for operations where both LHS and RHS
9383 /// are (potentially problematic) pointers.
9384 ///
9385 /// \returns True when the operand is valid to use (even if as an extension).
9386 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9387                                                 Expr *LHSExpr, Expr *RHSExpr) {
9388   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9389   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9390   if (!isLHSPointer && !isRHSPointer) return true;
9391 
9392   QualType LHSPointeeTy, RHSPointeeTy;
9393   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9394   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9395 
9396   // if both are pointers check if operation is valid wrt address spaces
9397   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9398     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9399     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9400     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9401       S.Diag(Loc,
9402              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9403           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9404           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9405       return false;
9406     }
9407   }
9408 
9409   // Check for arithmetic on pointers to incomplete types.
9410   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9411   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9412   if (isLHSVoidPtr || isRHSVoidPtr) {
9413     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9414     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9415     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9416 
9417     return !S.getLangOpts().CPlusPlus;
9418   }
9419 
9420   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9421   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9422   if (isLHSFuncPtr || isRHSFuncPtr) {
9423     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9424     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9425                                                                 RHSExpr);
9426     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9427 
9428     return !S.getLangOpts().CPlusPlus;
9429   }
9430 
9431   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9432     return false;
9433   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9434     return false;
9435 
9436   return true;
9437 }
9438 
9439 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9440 /// literal.
9441 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9442                                   Expr *LHSExpr, Expr *RHSExpr) {
9443   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9444   Expr* IndexExpr = RHSExpr;
9445   if (!StrExpr) {
9446     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9447     IndexExpr = LHSExpr;
9448   }
9449 
9450   bool IsStringPlusInt = StrExpr &&
9451       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9452   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9453     return;
9454 
9455   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9456   Self.Diag(OpLoc, diag::warn_string_plus_int)
9457       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9458 
9459   // Only print a fixit for "str" + int, not for int + "str".
9460   if (IndexExpr == RHSExpr) {
9461     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9462     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9463         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9464         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9465         << FixItHint::CreateInsertion(EndLoc, "]");
9466   } else
9467     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9468 }
9469 
9470 /// Emit a warning when adding a char literal to a string.
9471 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9472                                    Expr *LHSExpr, Expr *RHSExpr) {
9473   const Expr *StringRefExpr = LHSExpr;
9474   const CharacterLiteral *CharExpr =
9475       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9476 
9477   if (!CharExpr) {
9478     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9479     StringRefExpr = RHSExpr;
9480   }
9481 
9482   if (!CharExpr || !StringRefExpr)
9483     return;
9484 
9485   const QualType StringType = StringRefExpr->getType();
9486 
9487   // Return if not a PointerType.
9488   if (!StringType->isAnyPointerType())
9489     return;
9490 
9491   // Return if not a CharacterType.
9492   if (!StringType->getPointeeType()->isAnyCharacterType())
9493     return;
9494 
9495   ASTContext &Ctx = Self.getASTContext();
9496   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9497 
9498   const QualType CharType = CharExpr->getType();
9499   if (!CharType->isAnyCharacterType() &&
9500       CharType->isIntegerType() &&
9501       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9502     Self.Diag(OpLoc, diag::warn_string_plus_char)
9503         << DiagRange << Ctx.CharTy;
9504   } else {
9505     Self.Diag(OpLoc, diag::warn_string_plus_char)
9506         << DiagRange << CharExpr->getType();
9507   }
9508 
9509   // Only print a fixit for str + char, not for char + str.
9510   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9511     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9512     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9513         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9514         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9515         << FixItHint::CreateInsertion(EndLoc, "]");
9516   } else {
9517     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9518   }
9519 }
9520 
9521 /// Emit error when two pointers are incompatible.
9522 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9523                                            Expr *LHSExpr, Expr *RHSExpr) {
9524   assert(LHSExpr->getType()->isAnyPointerType());
9525   assert(RHSExpr->getType()->isAnyPointerType());
9526   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9527     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9528     << RHSExpr->getSourceRange();
9529 }
9530 
9531 // C99 6.5.6
9532 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9533                                      SourceLocation Loc, BinaryOperatorKind Opc,
9534                                      QualType* CompLHSTy) {
9535   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9536 
9537   if (LHS.get()->getType()->isVectorType() ||
9538       RHS.get()->getType()->isVectorType()) {
9539     QualType compType = CheckVectorOperands(
9540         LHS, RHS, Loc, CompLHSTy,
9541         /*AllowBothBool*/getLangOpts().AltiVec,
9542         /*AllowBoolConversions*/getLangOpts().ZVector);
9543     if (CompLHSTy) *CompLHSTy = compType;
9544     return compType;
9545   }
9546 
9547   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9548   if (LHS.isInvalid() || RHS.isInvalid())
9549     return QualType();
9550 
9551   // Diagnose "string literal" '+' int and string '+' "char literal".
9552   if (Opc == BO_Add) {
9553     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9554     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9555   }
9556 
9557   // handle the common case first (both operands are arithmetic).
9558   if (!compType.isNull() && compType->isArithmeticType()) {
9559     if (CompLHSTy) *CompLHSTy = compType;
9560     return compType;
9561   }
9562 
9563   // Type-checking.  Ultimately the pointer's going to be in PExp;
9564   // note that we bias towards the LHS being the pointer.
9565   Expr *PExp = LHS.get(), *IExp = RHS.get();
9566 
9567   bool isObjCPointer;
9568   if (PExp->getType()->isPointerType()) {
9569     isObjCPointer = false;
9570   } else if (PExp->getType()->isObjCObjectPointerType()) {
9571     isObjCPointer = true;
9572   } else {
9573     std::swap(PExp, IExp);
9574     if (PExp->getType()->isPointerType()) {
9575       isObjCPointer = false;
9576     } else if (PExp->getType()->isObjCObjectPointerType()) {
9577       isObjCPointer = true;
9578     } else {
9579       return InvalidOperands(Loc, LHS, RHS);
9580     }
9581   }
9582   assert(PExp->getType()->isAnyPointerType());
9583 
9584   if (!IExp->getType()->isIntegerType())
9585     return InvalidOperands(Loc, LHS, RHS);
9586 
9587   // Adding to a null pointer results in undefined behavior.
9588   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9589           Context, Expr::NPC_ValueDependentIsNotNull)) {
9590     // In C++ adding zero to a null pointer is defined.
9591     Expr::EvalResult KnownVal;
9592     if (!getLangOpts().CPlusPlus ||
9593         (!IExp->isValueDependent() &&
9594          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9595           KnownVal.Val.getInt() != 0))) {
9596       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9597       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9598           Context, BO_Add, PExp, IExp);
9599       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9600     }
9601   }
9602 
9603   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9604     return QualType();
9605 
9606   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9607     return QualType();
9608 
9609   // Check array bounds for pointer arithemtic
9610   CheckArrayAccess(PExp, IExp);
9611 
9612   if (CompLHSTy) {
9613     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9614     if (LHSTy.isNull()) {
9615       LHSTy = LHS.get()->getType();
9616       if (LHSTy->isPromotableIntegerType())
9617         LHSTy = Context.getPromotedIntegerType(LHSTy);
9618     }
9619     *CompLHSTy = LHSTy;
9620   }
9621 
9622   return PExp->getType();
9623 }
9624 
9625 // C99 6.5.6
9626 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9627                                         SourceLocation Loc,
9628                                         QualType* CompLHSTy) {
9629   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9630 
9631   if (LHS.get()->getType()->isVectorType() ||
9632       RHS.get()->getType()->isVectorType()) {
9633     QualType compType = CheckVectorOperands(
9634         LHS, RHS, Loc, CompLHSTy,
9635         /*AllowBothBool*/getLangOpts().AltiVec,
9636         /*AllowBoolConversions*/getLangOpts().ZVector);
9637     if (CompLHSTy) *CompLHSTy = compType;
9638     return compType;
9639   }
9640 
9641   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9642   if (LHS.isInvalid() || RHS.isInvalid())
9643     return QualType();
9644 
9645   // Enforce type constraints: C99 6.5.6p3.
9646 
9647   // Handle the common case first (both operands are arithmetic).
9648   if (!compType.isNull() && compType->isArithmeticType()) {
9649     if (CompLHSTy) *CompLHSTy = compType;
9650     return compType;
9651   }
9652 
9653   // Either ptr - int   or   ptr - ptr.
9654   if (LHS.get()->getType()->isAnyPointerType()) {
9655     QualType lpointee = LHS.get()->getType()->getPointeeType();
9656 
9657     // Diagnose bad cases where we step over interface counts.
9658     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9659         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9660       return QualType();
9661 
9662     // The result type of a pointer-int computation is the pointer type.
9663     if (RHS.get()->getType()->isIntegerType()) {
9664       // Subtracting from a null pointer should produce a warning.
9665       // The last argument to the diagnose call says this doesn't match the
9666       // GNU int-to-pointer idiom.
9667       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9668                                            Expr::NPC_ValueDependentIsNotNull)) {
9669         // In C++ adding zero to a null pointer is defined.
9670         Expr::EvalResult KnownVal;
9671         if (!getLangOpts().CPlusPlus ||
9672             (!RHS.get()->isValueDependent() &&
9673              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9674               KnownVal.Val.getInt() != 0))) {
9675           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9676         }
9677       }
9678 
9679       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9680         return QualType();
9681 
9682       // Check array bounds for pointer arithemtic
9683       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9684                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9685 
9686       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9687       return LHS.get()->getType();
9688     }
9689 
9690     // Handle pointer-pointer subtractions.
9691     if (const PointerType *RHSPTy
9692           = RHS.get()->getType()->getAs<PointerType>()) {
9693       QualType rpointee = RHSPTy->getPointeeType();
9694 
9695       if (getLangOpts().CPlusPlus) {
9696         // Pointee types must be the same: C++ [expr.add]
9697         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9698           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9699         }
9700       } else {
9701         // Pointee types must be compatible C99 6.5.6p3
9702         if (!Context.typesAreCompatible(
9703                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9704                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9705           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9706           return QualType();
9707         }
9708       }
9709 
9710       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9711                                                LHS.get(), RHS.get()))
9712         return QualType();
9713 
9714       // FIXME: Add warnings for nullptr - ptr.
9715 
9716       // The pointee type may have zero size.  As an extension, a structure or
9717       // union may have zero size or an array may have zero length.  In this
9718       // case subtraction does not make sense.
9719       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9720         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9721         if (ElementSize.isZero()) {
9722           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9723             << rpointee.getUnqualifiedType()
9724             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9725         }
9726       }
9727 
9728       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9729       return Context.getPointerDiffType();
9730     }
9731   }
9732 
9733   return InvalidOperands(Loc, LHS, RHS);
9734 }
9735 
9736 static bool isScopedEnumerationType(QualType T) {
9737   if (const EnumType *ET = T->getAs<EnumType>())
9738     return ET->getDecl()->isScoped();
9739   return false;
9740 }
9741 
9742 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9743                                    SourceLocation Loc, BinaryOperatorKind Opc,
9744                                    QualType LHSType) {
9745   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9746   // so skip remaining warnings as we don't want to modify values within Sema.
9747   if (S.getLangOpts().OpenCL)
9748     return;
9749 
9750   // Check right/shifter operand
9751   Expr::EvalResult RHSResult;
9752   if (RHS.get()->isValueDependent() ||
9753       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9754     return;
9755   llvm::APSInt Right = RHSResult.Val.getInt();
9756 
9757   if (Right.isNegative()) {
9758     S.DiagRuntimeBehavior(Loc, RHS.get(),
9759                           S.PDiag(diag::warn_shift_negative)
9760                             << RHS.get()->getSourceRange());
9761     return;
9762   }
9763   llvm::APInt LeftBits(Right.getBitWidth(),
9764                        S.Context.getTypeSize(LHS.get()->getType()));
9765   if (Right.uge(LeftBits)) {
9766     S.DiagRuntimeBehavior(Loc, RHS.get(),
9767                           S.PDiag(diag::warn_shift_gt_typewidth)
9768                             << RHS.get()->getSourceRange());
9769     return;
9770   }
9771   if (Opc != BO_Shl)
9772     return;
9773 
9774   // When left shifting an ICE which is signed, we can check for overflow which
9775   // according to C++ standards prior to C++2a has undefined behavior
9776   // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9777   // more than the maximum value representable in the result type, so never
9778   // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9779   // expression is still probably a bug.)
9780   Expr::EvalResult LHSResult;
9781   if (LHS.get()->isValueDependent() ||
9782       LHSType->hasUnsignedIntegerRepresentation() ||
9783       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9784     return;
9785   llvm::APSInt Left = LHSResult.Val.getInt();
9786 
9787   // If LHS does not have a signed type and non-negative value
9788   // then, the behavior is undefined before C++2a. Warn about it.
9789   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9790       !S.getLangOpts().CPlusPlus2a) {
9791     S.DiagRuntimeBehavior(Loc, LHS.get(),
9792                           S.PDiag(diag::warn_shift_lhs_negative)
9793                             << LHS.get()->getSourceRange());
9794     return;
9795   }
9796 
9797   llvm::APInt ResultBits =
9798       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9799   if (LeftBits.uge(ResultBits))
9800     return;
9801   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9802   Result = Result.shl(Right);
9803 
9804   // Print the bit representation of the signed integer as an unsigned
9805   // hexadecimal number.
9806   SmallString<40> HexResult;
9807   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9808 
9809   // If we are only missing a sign bit, this is less likely to result in actual
9810   // bugs -- if the result is cast back to an unsigned type, it will have the
9811   // expected value. Thus we place this behind a different warning that can be
9812   // turned off separately if needed.
9813   if (LeftBits == ResultBits - 1) {
9814     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9815         << HexResult << LHSType
9816         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9817     return;
9818   }
9819 
9820   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9821     << HexResult.str() << Result.getMinSignedBits() << LHSType
9822     << Left.getBitWidth() << LHS.get()->getSourceRange()
9823     << RHS.get()->getSourceRange();
9824 }
9825 
9826 /// Return the resulting type when a vector is shifted
9827 ///        by a scalar or vector shift amount.
9828 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9829                                  SourceLocation Loc, bool IsCompAssign) {
9830   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9831   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9832       !LHS.get()->getType()->isVectorType()) {
9833     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9834       << RHS.get()->getType() << LHS.get()->getType()
9835       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9836     return QualType();
9837   }
9838 
9839   if (!IsCompAssign) {
9840     LHS = S.UsualUnaryConversions(LHS.get());
9841     if (LHS.isInvalid()) return QualType();
9842   }
9843 
9844   RHS = S.UsualUnaryConversions(RHS.get());
9845   if (RHS.isInvalid()) return QualType();
9846 
9847   QualType LHSType = LHS.get()->getType();
9848   // Note that LHS might be a scalar because the routine calls not only in
9849   // OpenCL case.
9850   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9851   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9852 
9853   // Note that RHS might not be a vector.
9854   QualType RHSType = RHS.get()->getType();
9855   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9856   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9857 
9858   // The operands need to be integers.
9859   if (!LHSEleType->isIntegerType()) {
9860     S.Diag(Loc, diag::err_typecheck_expect_int)
9861       << LHS.get()->getType() << LHS.get()->getSourceRange();
9862     return QualType();
9863   }
9864 
9865   if (!RHSEleType->isIntegerType()) {
9866     S.Diag(Loc, diag::err_typecheck_expect_int)
9867       << RHS.get()->getType() << RHS.get()->getSourceRange();
9868     return QualType();
9869   }
9870 
9871   if (!LHSVecTy) {
9872     assert(RHSVecTy);
9873     if (IsCompAssign)
9874       return RHSType;
9875     if (LHSEleType != RHSEleType) {
9876       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9877       LHSEleType = RHSEleType;
9878     }
9879     QualType VecTy =
9880         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9881     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9882     LHSType = VecTy;
9883   } else if (RHSVecTy) {
9884     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9885     // are applied component-wise. So if RHS is a vector, then ensure
9886     // that the number of elements is the same as LHS...
9887     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9888       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9889         << LHS.get()->getType() << RHS.get()->getType()
9890         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9891       return QualType();
9892     }
9893     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9894       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9895       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9896       if (LHSBT != RHSBT &&
9897           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9898         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9899             << LHS.get()->getType() << RHS.get()->getType()
9900             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9901       }
9902     }
9903   } else {
9904     // ...else expand RHS to match the number of elements in LHS.
9905     QualType VecTy =
9906       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9907     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9908   }
9909 
9910   return LHSType;
9911 }
9912 
9913 // C99 6.5.7
9914 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9915                                   SourceLocation Loc, BinaryOperatorKind Opc,
9916                                   bool IsCompAssign) {
9917   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9918 
9919   // Vector shifts promote their scalar inputs to vector type.
9920   if (LHS.get()->getType()->isVectorType() ||
9921       RHS.get()->getType()->isVectorType()) {
9922     if (LangOpts.ZVector) {
9923       // The shift operators for the z vector extensions work basically
9924       // like general shifts, except that neither the LHS nor the RHS is
9925       // allowed to be a "vector bool".
9926       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9927         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9928           return InvalidOperands(Loc, LHS, RHS);
9929       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9930         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9931           return InvalidOperands(Loc, LHS, RHS);
9932     }
9933     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9934   }
9935 
9936   // Shifts don't perform usual arithmetic conversions, they just do integer
9937   // promotions on each operand. C99 6.5.7p3
9938 
9939   // For the LHS, do usual unary conversions, but then reset them away
9940   // if this is a compound assignment.
9941   ExprResult OldLHS = LHS;
9942   LHS = UsualUnaryConversions(LHS.get());
9943   if (LHS.isInvalid())
9944     return QualType();
9945   QualType LHSType = LHS.get()->getType();
9946   if (IsCompAssign) LHS = OldLHS;
9947 
9948   // The RHS is simpler.
9949   RHS = UsualUnaryConversions(RHS.get());
9950   if (RHS.isInvalid())
9951     return QualType();
9952   QualType RHSType = RHS.get()->getType();
9953 
9954   // C99 6.5.7p2: Each of the operands shall have integer type.
9955   if (!LHSType->hasIntegerRepresentation() ||
9956       !RHSType->hasIntegerRepresentation())
9957     return InvalidOperands(Loc, LHS, RHS);
9958 
9959   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9960   // hasIntegerRepresentation() above instead of this.
9961   if (isScopedEnumerationType(LHSType) ||
9962       isScopedEnumerationType(RHSType)) {
9963     return InvalidOperands(Loc, LHS, RHS);
9964   }
9965   // Sanity-check shift operands
9966   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9967 
9968   // "The type of the result is that of the promoted left operand."
9969   return LHSType;
9970 }
9971 
9972 /// If two different enums are compared, raise a warning.
9973 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9974                                 Expr *RHS) {
9975   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9976   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9977 
9978   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9979   if (!LHSEnumType)
9980     return;
9981   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9982   if (!RHSEnumType)
9983     return;
9984 
9985   // Ignore anonymous enums.
9986   if (!LHSEnumType->getDecl()->getIdentifier() &&
9987       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9988     return;
9989   if (!RHSEnumType->getDecl()->getIdentifier() &&
9990       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9991     return;
9992 
9993   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9994     return;
9995 
9996   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9997       << LHSStrippedType << RHSStrippedType
9998       << LHS->getSourceRange() << RHS->getSourceRange();
9999 }
10000 
10001 /// Diagnose bad pointer comparisons.
10002 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10003                                               ExprResult &LHS, ExprResult &RHS,
10004                                               bool IsError) {
10005   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10006                       : diag::ext_typecheck_comparison_of_distinct_pointers)
10007     << LHS.get()->getType() << RHS.get()->getType()
10008     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10009 }
10010 
10011 /// Returns false if the pointers are converted to a composite type,
10012 /// true otherwise.
10013 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10014                                            ExprResult &LHS, ExprResult &RHS) {
10015   // C++ [expr.rel]p2:
10016   //   [...] Pointer conversions (4.10) and qualification
10017   //   conversions (4.4) are performed on pointer operands (or on
10018   //   a pointer operand and a null pointer constant) to bring
10019   //   them to their composite pointer type. [...]
10020   //
10021   // C++ [expr.eq]p1 uses the same notion for (in)equality
10022   // comparisons of pointers.
10023 
10024   QualType LHSType = LHS.get()->getType();
10025   QualType RHSType = RHS.get()->getType();
10026   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10027          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10028 
10029   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10030   if (T.isNull()) {
10031     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
10032         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
10033       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10034     else
10035       S.InvalidOperands(Loc, LHS, RHS);
10036     return true;
10037   }
10038 
10039   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
10040   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
10041   return false;
10042 }
10043 
10044 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10045                                                     ExprResult &LHS,
10046                                                     ExprResult &RHS,
10047                                                     bool IsError) {
10048   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10049                       : diag::ext_typecheck_comparison_of_fptr_to_void)
10050     << LHS.get()->getType() << RHS.get()->getType()
10051     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10052 }
10053 
10054 static bool isObjCObjectLiteral(ExprResult &E) {
10055   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10056   case Stmt::ObjCArrayLiteralClass:
10057   case Stmt::ObjCDictionaryLiteralClass:
10058   case Stmt::ObjCStringLiteralClass:
10059   case Stmt::ObjCBoxedExprClass:
10060     return true;
10061   default:
10062     // Note that ObjCBoolLiteral is NOT an object literal!
10063     return false;
10064   }
10065 }
10066 
10067 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10068   const ObjCObjectPointerType *Type =
10069     LHS->getType()->getAs<ObjCObjectPointerType>();
10070 
10071   // If this is not actually an Objective-C object, bail out.
10072   if (!Type)
10073     return false;
10074 
10075   // Get the LHS object's interface type.
10076   QualType InterfaceType = Type->getPointeeType();
10077 
10078   // If the RHS isn't an Objective-C object, bail out.
10079   if (!RHS->getType()->isObjCObjectPointerType())
10080     return false;
10081 
10082   // Try to find the -isEqual: method.
10083   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10084   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10085                                                       InterfaceType,
10086                                                       /*IsInstance=*/true);
10087   if (!Method) {
10088     if (Type->isObjCIdType()) {
10089       // For 'id', just check the global pool.
10090       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10091                                                   /*receiverId=*/true);
10092     } else {
10093       // Check protocols.
10094       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10095                                              /*IsInstance=*/true);
10096     }
10097   }
10098 
10099   if (!Method)
10100     return false;
10101 
10102   QualType T = Method->parameters()[0]->getType();
10103   if (!T->isObjCObjectPointerType())
10104     return false;
10105 
10106   QualType R = Method->getReturnType();
10107   if (!R->isScalarType())
10108     return false;
10109 
10110   return true;
10111 }
10112 
10113 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10114   FromE = FromE->IgnoreParenImpCasts();
10115   switch (FromE->getStmtClass()) {
10116     default:
10117       break;
10118     case Stmt::ObjCStringLiteralClass:
10119       // "string literal"
10120       return LK_String;
10121     case Stmt::ObjCArrayLiteralClass:
10122       // "array literal"
10123       return LK_Array;
10124     case Stmt::ObjCDictionaryLiteralClass:
10125       // "dictionary literal"
10126       return LK_Dictionary;
10127     case Stmt::BlockExprClass:
10128       return LK_Block;
10129     case Stmt::ObjCBoxedExprClass: {
10130       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10131       switch (Inner->getStmtClass()) {
10132         case Stmt::IntegerLiteralClass:
10133         case Stmt::FloatingLiteralClass:
10134         case Stmt::CharacterLiteralClass:
10135         case Stmt::ObjCBoolLiteralExprClass:
10136         case Stmt::CXXBoolLiteralExprClass:
10137           // "numeric literal"
10138           return LK_Numeric;
10139         case Stmt::ImplicitCastExprClass: {
10140           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10141           // Boolean literals can be represented by implicit casts.
10142           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10143             return LK_Numeric;
10144           break;
10145         }
10146         default:
10147           break;
10148       }
10149       return LK_Boxed;
10150     }
10151   }
10152   return LK_None;
10153 }
10154 
10155 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10156                                           ExprResult &LHS, ExprResult &RHS,
10157                                           BinaryOperator::Opcode Opc){
10158   Expr *Literal;
10159   Expr *Other;
10160   if (isObjCObjectLiteral(LHS)) {
10161     Literal = LHS.get();
10162     Other = RHS.get();
10163   } else {
10164     Literal = RHS.get();
10165     Other = LHS.get();
10166   }
10167 
10168   // Don't warn on comparisons against nil.
10169   Other = Other->IgnoreParenCasts();
10170   if (Other->isNullPointerConstant(S.getASTContext(),
10171                                    Expr::NPC_ValueDependentIsNotNull))
10172     return;
10173 
10174   // This should be kept in sync with warn_objc_literal_comparison.
10175   // LK_String should always be after the other literals, since it has its own
10176   // warning flag.
10177   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10178   assert(LiteralKind != Sema::LK_Block);
10179   if (LiteralKind == Sema::LK_None) {
10180     llvm_unreachable("Unknown Objective-C object literal kind");
10181   }
10182 
10183   if (LiteralKind == Sema::LK_String)
10184     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10185       << Literal->getSourceRange();
10186   else
10187     S.Diag(Loc, diag::warn_objc_literal_comparison)
10188       << LiteralKind << Literal->getSourceRange();
10189 
10190   if (BinaryOperator::isEqualityOp(Opc) &&
10191       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10192     SourceLocation Start = LHS.get()->getBeginLoc();
10193     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10194     CharSourceRange OpRange =
10195       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10196 
10197     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10198       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10199       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10200       << FixItHint::CreateInsertion(End, "]");
10201   }
10202 }
10203 
10204 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10205 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10206                                            ExprResult &RHS, SourceLocation Loc,
10207                                            BinaryOperatorKind Opc) {
10208   // Check that left hand side is !something.
10209   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10210   if (!UO || UO->getOpcode() != UO_LNot) return;
10211 
10212   // Only check if the right hand side is non-bool arithmetic type.
10213   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10214 
10215   // Make sure that the something in !something is not bool.
10216   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10217   if (SubExpr->isKnownToHaveBooleanValue()) return;
10218 
10219   // Emit warning.
10220   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10221   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10222       << Loc << IsBitwiseOp;
10223 
10224   // First note suggest !(x < y)
10225   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10226   SourceLocation FirstClose = RHS.get()->getEndLoc();
10227   FirstClose = S.getLocForEndOfToken(FirstClose);
10228   if (FirstClose.isInvalid())
10229     FirstOpen = SourceLocation();
10230   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10231       << IsBitwiseOp
10232       << FixItHint::CreateInsertion(FirstOpen, "(")
10233       << FixItHint::CreateInsertion(FirstClose, ")");
10234 
10235   // Second note suggests (!x) < y
10236   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10237   SourceLocation SecondClose = LHS.get()->getEndLoc();
10238   SecondClose = S.getLocForEndOfToken(SecondClose);
10239   if (SecondClose.isInvalid())
10240     SecondOpen = SourceLocation();
10241   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10242       << FixItHint::CreateInsertion(SecondOpen, "(")
10243       << FixItHint::CreateInsertion(SecondClose, ")");
10244 }
10245 
10246 // Get the decl for a simple expression: a reference to a variable,
10247 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10248 static ValueDecl *getCompareDecl(Expr *E) {
10249   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10250     return DR->getDecl();
10251   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10252     if (Ivar->isFreeIvar())
10253       return Ivar->getDecl();
10254   }
10255   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10256     if (Mem->isImplicitAccess())
10257       return Mem->getMemberDecl();
10258   }
10259   return nullptr;
10260 }
10261 
10262 /// Diagnose some forms of syntactically-obvious tautological comparison.
10263 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10264                                            Expr *LHS, Expr *RHS,
10265                                            BinaryOperatorKind Opc) {
10266   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10267   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10268 
10269   QualType LHSType = LHS->getType();
10270   QualType RHSType = RHS->getType();
10271   if (LHSType->hasFloatingRepresentation() ||
10272       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10273       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10274       S.inTemplateInstantiation())
10275     return;
10276 
10277   // Comparisons between two array types are ill-formed for operator<=>, so
10278   // we shouldn't emit any additional warnings about it.
10279   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10280     return;
10281 
10282   // For non-floating point types, check for self-comparisons of the form
10283   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10284   // often indicate logic errors in the program.
10285   //
10286   // NOTE: Don't warn about comparison expressions resulting from macro
10287   // expansion. Also don't warn about comparisons which are only self
10288   // comparisons within a template instantiation. The warnings should catch
10289   // obvious cases in the definition of the template anyways. The idea is to
10290   // warn when the typed comparison operator will always evaluate to the same
10291   // result.
10292   ValueDecl *DL = getCompareDecl(LHSStripped);
10293   ValueDecl *DR = getCompareDecl(RHSStripped);
10294 
10295   // Used for indexing into %select in warn_comparison_always
10296   enum {
10297     AlwaysConstant,
10298     AlwaysTrue,
10299     AlwaysFalse,
10300     AlwaysEqual, // std::strong_ordering::equal from operator<=>
10301   };
10302   if (DL && DR && declaresSameEntity(DL, DR)) {
10303     unsigned Result;
10304     switch (Opc) {
10305     case BO_EQ: case BO_LE: case BO_GE:
10306       Result = AlwaysTrue;
10307       break;
10308     case BO_NE: case BO_LT: case BO_GT:
10309       Result = AlwaysFalse;
10310       break;
10311     case BO_Cmp:
10312       Result = AlwaysEqual;
10313       break;
10314     default:
10315       Result = AlwaysConstant;
10316       break;
10317     }
10318     S.DiagRuntimeBehavior(Loc, nullptr,
10319                           S.PDiag(diag::warn_comparison_always)
10320                               << 0 /*self-comparison*/
10321                               << Result);
10322   } else if (DL && DR &&
10323              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10324              !DL->isWeak() && !DR->isWeak()) {
10325     // What is it always going to evaluate to?
10326     unsigned Result;
10327     switch(Opc) {
10328     case BO_EQ: // e.g. array1 == array2
10329       Result = AlwaysFalse;
10330       break;
10331     case BO_NE: // e.g. array1 != array2
10332       Result = AlwaysTrue;
10333       break;
10334     default: // e.g. array1 <= array2
10335       // The best we can say is 'a constant'
10336       Result = AlwaysConstant;
10337       break;
10338     }
10339     S.DiagRuntimeBehavior(Loc, nullptr,
10340                           S.PDiag(diag::warn_comparison_always)
10341                               << 1 /*array comparison*/
10342                               << Result);
10343   }
10344 
10345   if (isa<CastExpr>(LHSStripped))
10346     LHSStripped = LHSStripped->IgnoreParenCasts();
10347   if (isa<CastExpr>(RHSStripped))
10348     RHSStripped = RHSStripped->IgnoreParenCasts();
10349 
10350   // Warn about comparisons against a string constant (unless the other
10351   // operand is null); the user probably wants strcmp.
10352   Expr *LiteralString = nullptr;
10353   Expr *LiteralStringStripped = nullptr;
10354   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10355       !RHSStripped->isNullPointerConstant(S.Context,
10356                                           Expr::NPC_ValueDependentIsNull)) {
10357     LiteralString = LHS;
10358     LiteralStringStripped = LHSStripped;
10359   } else if ((isa<StringLiteral>(RHSStripped) ||
10360               isa<ObjCEncodeExpr>(RHSStripped)) &&
10361              !LHSStripped->isNullPointerConstant(S.Context,
10362                                           Expr::NPC_ValueDependentIsNull)) {
10363     LiteralString = RHS;
10364     LiteralStringStripped = RHSStripped;
10365   }
10366 
10367   if (LiteralString) {
10368     S.DiagRuntimeBehavior(Loc, nullptr,
10369                           S.PDiag(diag::warn_stringcompare)
10370                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10371                               << LiteralString->getSourceRange());
10372   }
10373 }
10374 
10375 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10376   switch (CK) {
10377   default: {
10378 #ifndef NDEBUG
10379     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10380                  << "\n";
10381 #endif
10382     llvm_unreachable("unhandled cast kind");
10383   }
10384   case CK_UserDefinedConversion:
10385     return ICK_Identity;
10386   case CK_LValueToRValue:
10387     return ICK_Lvalue_To_Rvalue;
10388   case CK_ArrayToPointerDecay:
10389     return ICK_Array_To_Pointer;
10390   case CK_FunctionToPointerDecay:
10391     return ICK_Function_To_Pointer;
10392   case CK_IntegralCast:
10393     return ICK_Integral_Conversion;
10394   case CK_FloatingCast:
10395     return ICK_Floating_Conversion;
10396   case CK_IntegralToFloating:
10397   case CK_FloatingToIntegral:
10398     return ICK_Floating_Integral;
10399   case CK_IntegralComplexCast:
10400   case CK_FloatingComplexCast:
10401   case CK_FloatingComplexToIntegralComplex:
10402   case CK_IntegralComplexToFloatingComplex:
10403     return ICK_Complex_Conversion;
10404   case CK_FloatingComplexToReal:
10405   case CK_FloatingRealToComplex:
10406   case CK_IntegralComplexToReal:
10407   case CK_IntegralRealToComplex:
10408     return ICK_Complex_Real;
10409   }
10410 }
10411 
10412 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10413                                              QualType FromType,
10414                                              SourceLocation Loc) {
10415   // Check for a narrowing implicit conversion.
10416   StandardConversionSequence SCS;
10417   SCS.setAsIdentityConversion();
10418   SCS.setToType(0, FromType);
10419   SCS.setToType(1, ToType);
10420   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10421     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10422 
10423   APValue PreNarrowingValue;
10424   QualType PreNarrowingType;
10425   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10426                                PreNarrowingType,
10427                                /*IgnoreFloatToIntegralConversion*/ true)) {
10428   case NK_Dependent_Narrowing:
10429     // Implicit conversion to a narrower type, but the expression is
10430     // value-dependent so we can't tell whether it's actually narrowing.
10431   case NK_Not_Narrowing:
10432     return false;
10433 
10434   case NK_Constant_Narrowing:
10435     // Implicit conversion to a narrower type, and the value is not a constant
10436     // expression.
10437     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10438         << /*Constant*/ 1
10439         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10440     return true;
10441 
10442   case NK_Variable_Narrowing:
10443     // Implicit conversion to a narrower type, and the value is not a constant
10444     // expression.
10445   case NK_Type_Narrowing:
10446     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10447         << /*Constant*/ 0 << FromType << ToType;
10448     // TODO: It's not a constant expression, but what if the user intended it
10449     // to be? Can we produce notes to help them figure out why it isn't?
10450     return true;
10451   }
10452   llvm_unreachable("unhandled case in switch");
10453 }
10454 
10455 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10456                                                          ExprResult &LHS,
10457                                                          ExprResult &RHS,
10458                                                          SourceLocation Loc) {
10459   using CCT = ComparisonCategoryType;
10460 
10461   QualType LHSType = LHS.get()->getType();
10462   QualType RHSType = RHS.get()->getType();
10463   // Dig out the original argument type and expression before implicit casts
10464   // were applied. These are the types/expressions we need to check the
10465   // [expr.spaceship] requirements against.
10466   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10467   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10468   QualType LHSStrippedType = LHSStripped.get()->getType();
10469   QualType RHSStrippedType = RHSStripped.get()->getType();
10470 
10471   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10472   // other is not, the program is ill-formed.
10473   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10474     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10475     return QualType();
10476   }
10477 
10478   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10479                     RHSStrippedType->isEnumeralType();
10480   if (NumEnumArgs == 1) {
10481     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10482     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10483     if (OtherTy->hasFloatingRepresentation()) {
10484       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10485       return QualType();
10486     }
10487   }
10488   if (NumEnumArgs == 2) {
10489     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10490     // type E, the operator yields the result of converting the operands
10491     // to the underlying type of E and applying <=> to the converted operands.
10492     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10493       S.InvalidOperands(Loc, LHS, RHS);
10494       return QualType();
10495     }
10496     QualType IntType =
10497         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10498     assert(IntType->isArithmeticType());
10499 
10500     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10501     // promote the boolean type, and all other promotable integer types, to
10502     // avoid this.
10503     if (IntType->isPromotableIntegerType())
10504       IntType = S.Context.getPromotedIntegerType(IntType);
10505 
10506     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10507     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10508     LHSType = RHSType = IntType;
10509   }
10510 
10511   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10512   // usual arithmetic conversions are applied to the operands.
10513   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10514   if (LHS.isInvalid() || RHS.isInvalid())
10515     return QualType();
10516   if (Type.isNull())
10517     return S.InvalidOperands(Loc, LHS, RHS);
10518   assert(Type->isArithmeticType() || Type->isEnumeralType());
10519 
10520   bool HasNarrowing = checkThreeWayNarrowingConversion(
10521       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10522   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10523                                                    RHS.get()->getBeginLoc());
10524   if (HasNarrowing)
10525     return QualType();
10526 
10527   assert(!Type.isNull() && "composite type for <=> has not been set");
10528 
10529   auto TypeKind = [&]() {
10530     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10531       if (CT->getElementType()->hasFloatingRepresentation())
10532         return CCT::WeakEquality;
10533       return CCT::StrongEquality;
10534     }
10535     if (Type->isIntegralOrEnumerationType())
10536       return CCT::StrongOrdering;
10537     if (Type->hasFloatingRepresentation())
10538       return CCT::PartialOrdering;
10539     llvm_unreachable("other types are unimplemented");
10540   }();
10541 
10542   return S.CheckComparisonCategoryType(TypeKind, Loc);
10543 }
10544 
10545 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10546                                                  ExprResult &RHS,
10547                                                  SourceLocation Loc,
10548                                                  BinaryOperatorKind Opc) {
10549   if (Opc == BO_Cmp)
10550     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10551 
10552   // C99 6.5.8p3 / C99 6.5.9p4
10553   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10554   if (LHS.isInvalid() || RHS.isInvalid())
10555     return QualType();
10556   if (Type.isNull())
10557     return S.InvalidOperands(Loc, LHS, RHS);
10558   assert(Type->isArithmeticType() || Type->isEnumeralType());
10559 
10560   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10561 
10562   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10563     return S.InvalidOperands(Loc, LHS, RHS);
10564 
10565   // Check for comparisons of floating point operands using != and ==.
10566   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10567     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10568 
10569   // The result of comparisons is 'bool' in C++, 'int' in C.
10570   return S.Context.getLogicalOperationType();
10571 }
10572 
10573 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10574   if (!NullE.get()->getType()->isAnyPointerType())
10575     return;
10576   int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10577   if (!E.get()->getType()->isAnyPointerType() &&
10578       E.get()->isNullPointerConstant(Context,
10579                                      Expr::NPC_ValueDependentIsNotNull) ==
10580         Expr::NPCK_ZeroExpression) {
10581     if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10582       if (CL->getValue() == 0)
10583         Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10584             << NullValue
10585             << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10586                                             NullValue ? "NULL" : "(void *)0");
10587     } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10588         TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10589         QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10590         if (T == Context.CharTy)
10591           Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10592               << NullValue
10593               << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10594                                               NullValue ? "NULL" : "(void *)0");
10595       }
10596   }
10597 }
10598 
10599 // C99 6.5.8, C++ [expr.rel]
10600 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10601                                     SourceLocation Loc,
10602                                     BinaryOperatorKind Opc) {
10603   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10604   bool IsThreeWay = Opc == BO_Cmp;
10605   auto IsAnyPointerType = [](ExprResult E) {
10606     QualType Ty = E.get()->getType();
10607     return Ty->isPointerType() || Ty->isMemberPointerType();
10608   };
10609 
10610   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10611   // type, array-to-pointer, ..., conversions are performed on both operands to
10612   // bring them to their composite type.
10613   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10614   // any type-related checks.
10615   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10616     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10617     if (LHS.isInvalid())
10618       return QualType();
10619     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10620     if (RHS.isInvalid())
10621       return QualType();
10622   } else {
10623     LHS = DefaultLvalueConversion(LHS.get());
10624     if (LHS.isInvalid())
10625       return QualType();
10626     RHS = DefaultLvalueConversion(RHS.get());
10627     if (RHS.isInvalid())
10628       return QualType();
10629   }
10630 
10631   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10632   if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10633     CheckPtrComparisonWithNullChar(LHS, RHS);
10634     CheckPtrComparisonWithNullChar(RHS, LHS);
10635   }
10636 
10637   // Handle vector comparisons separately.
10638   if (LHS.get()->getType()->isVectorType() ||
10639       RHS.get()->getType()->isVectorType())
10640     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10641 
10642   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10643   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10644 
10645   QualType LHSType = LHS.get()->getType();
10646   QualType RHSType = RHS.get()->getType();
10647   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10648       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10649     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10650 
10651   const Expr::NullPointerConstantKind LHSNullKind =
10652       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10653   const Expr::NullPointerConstantKind RHSNullKind =
10654       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10655   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10656   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10657 
10658   auto computeResultTy = [&]() {
10659     if (Opc != BO_Cmp)
10660       return Context.getLogicalOperationType();
10661     assert(getLangOpts().CPlusPlus);
10662     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10663 
10664     QualType CompositeTy = LHS.get()->getType();
10665     assert(!CompositeTy->isReferenceType());
10666 
10667     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10668       return CheckComparisonCategoryType(Kind, Loc);
10669     };
10670 
10671     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10672     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10673     // result is of type std::strong_equality
10674     if (CompositeTy->isFunctionPointerType() ||
10675         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10676       // FIXME: consider making the function pointer case produce
10677       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10678       // and direction polls
10679       return buildResultTy(ComparisonCategoryType::StrongEquality);
10680 
10681     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10682     // pointer type, p <=> q is of type std::strong_ordering.
10683     if (CompositeTy->isPointerType()) {
10684       // P0946R0: Comparisons between a null pointer constant and an object
10685       // pointer result in std::strong_equality
10686       if (LHSIsNull != RHSIsNull)
10687         return buildResultTy(ComparisonCategoryType::StrongEquality);
10688       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10689     }
10690     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10691     // TODO: Extend support for operator<=> to ObjC types.
10692     return InvalidOperands(Loc, LHS, RHS);
10693   };
10694 
10695 
10696   if (!IsRelational && LHSIsNull != RHSIsNull) {
10697     bool IsEquality = Opc == BO_EQ;
10698     if (RHSIsNull)
10699       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10700                                    RHS.get()->getSourceRange());
10701     else
10702       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10703                                    LHS.get()->getSourceRange());
10704   }
10705 
10706   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10707       (RHSType->isIntegerType() && !RHSIsNull)) {
10708     // Skip normal pointer conversion checks in this case; we have better
10709     // diagnostics for this below.
10710   } else if (getLangOpts().CPlusPlus) {
10711     // Equality comparison of a function pointer to a void pointer is invalid,
10712     // but we allow it as an extension.
10713     // FIXME: If we really want to allow this, should it be part of composite
10714     // pointer type computation so it works in conditionals too?
10715     if (!IsRelational &&
10716         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10717          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10718       // This is a gcc extension compatibility comparison.
10719       // In a SFINAE context, we treat this as a hard error to maintain
10720       // conformance with the C++ standard.
10721       diagnoseFunctionPointerToVoidComparison(
10722           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10723 
10724       if (isSFINAEContext())
10725         return QualType();
10726 
10727       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10728       return computeResultTy();
10729     }
10730 
10731     // C++ [expr.eq]p2:
10732     //   If at least one operand is a pointer [...] bring them to their
10733     //   composite pointer type.
10734     // C++ [expr.spaceship]p6
10735     //  If at least one of the operands is of pointer type, [...] bring them
10736     //  to their composite pointer type.
10737     // C++ [expr.rel]p2:
10738     //   If both operands are pointers, [...] bring them to their composite
10739     //   pointer type.
10740     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10741             (IsRelational ? 2 : 1) &&
10742         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10743                                          RHSType->isObjCObjectPointerType()))) {
10744       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10745         return QualType();
10746       return computeResultTy();
10747     }
10748   } else if (LHSType->isPointerType() &&
10749              RHSType->isPointerType()) { // C99 6.5.8p2
10750     // All of the following pointer-related warnings are GCC extensions, except
10751     // when handling null pointer constants.
10752     QualType LCanPointeeTy =
10753       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10754     QualType RCanPointeeTy =
10755       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10756 
10757     // C99 6.5.9p2 and C99 6.5.8p2
10758     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10759                                    RCanPointeeTy.getUnqualifiedType())) {
10760       // Valid unless a relational comparison of function pointers
10761       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10762         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10763           << LHSType << RHSType << LHS.get()->getSourceRange()
10764           << RHS.get()->getSourceRange();
10765       }
10766     } else if (!IsRelational &&
10767                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10768       // Valid unless comparison between non-null pointer and function pointer
10769       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10770           && !LHSIsNull && !RHSIsNull)
10771         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10772                                                 /*isError*/false);
10773     } else {
10774       // Invalid
10775       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10776     }
10777     if (LCanPointeeTy != RCanPointeeTy) {
10778       // Treat NULL constant as a special case in OpenCL.
10779       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10780         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10781         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10782           Diag(Loc,
10783                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10784               << LHSType << RHSType << 0 /* comparison */
10785               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10786         }
10787       }
10788       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10789       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10790       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10791                                                : CK_BitCast;
10792       if (LHSIsNull && !RHSIsNull)
10793         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10794       else
10795         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10796     }
10797     return computeResultTy();
10798   }
10799 
10800   if (getLangOpts().CPlusPlus) {
10801     // C++ [expr.eq]p4:
10802     //   Two operands of type std::nullptr_t or one operand of type
10803     //   std::nullptr_t and the other a null pointer constant compare equal.
10804     if (!IsRelational && LHSIsNull && RHSIsNull) {
10805       if (LHSType->isNullPtrType()) {
10806         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10807         return computeResultTy();
10808       }
10809       if (RHSType->isNullPtrType()) {
10810         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10811         return computeResultTy();
10812       }
10813     }
10814 
10815     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10816     // These aren't covered by the composite pointer type rules.
10817     if (!IsRelational && RHSType->isNullPtrType() &&
10818         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10819       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10820       return computeResultTy();
10821     }
10822     if (!IsRelational && LHSType->isNullPtrType() &&
10823         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10824       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10825       return computeResultTy();
10826     }
10827 
10828     if (IsRelational &&
10829         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10830          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10831       // HACK: Relational comparison of nullptr_t against a pointer type is
10832       // invalid per DR583, but we allow it within std::less<> and friends,
10833       // since otherwise common uses of it break.
10834       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10835       // friends to have std::nullptr_t overload candidates.
10836       DeclContext *DC = CurContext;
10837       if (isa<FunctionDecl>(DC))
10838         DC = DC->getParent();
10839       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10840         if (CTSD->isInStdNamespace() &&
10841             llvm::StringSwitch<bool>(CTSD->getName())
10842                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10843                 .Default(false)) {
10844           if (RHSType->isNullPtrType())
10845             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10846           else
10847             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10848           return computeResultTy();
10849         }
10850       }
10851     }
10852 
10853     // C++ [expr.eq]p2:
10854     //   If at least one operand is a pointer to member, [...] bring them to
10855     //   their composite pointer type.
10856     if (!IsRelational &&
10857         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10858       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10859         return QualType();
10860       else
10861         return computeResultTy();
10862     }
10863   }
10864 
10865   // Handle block pointer types.
10866   if (!IsRelational && LHSType->isBlockPointerType() &&
10867       RHSType->isBlockPointerType()) {
10868     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10869     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10870 
10871     if (!LHSIsNull && !RHSIsNull &&
10872         !Context.typesAreCompatible(lpointee, rpointee)) {
10873       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10874         << LHSType << RHSType << LHS.get()->getSourceRange()
10875         << RHS.get()->getSourceRange();
10876     }
10877     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10878     return computeResultTy();
10879   }
10880 
10881   // Allow block pointers to be compared with null pointer constants.
10882   if (!IsRelational
10883       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10884           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10885     if (!LHSIsNull && !RHSIsNull) {
10886       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10887              ->getPointeeType()->isVoidType())
10888             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10889                 ->getPointeeType()->isVoidType())))
10890         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10891           << LHSType << RHSType << LHS.get()->getSourceRange()
10892           << RHS.get()->getSourceRange();
10893     }
10894     if (LHSIsNull && !RHSIsNull)
10895       LHS = ImpCastExprToType(LHS.get(), RHSType,
10896                               RHSType->isPointerType() ? CK_BitCast
10897                                 : CK_AnyPointerToBlockPointerCast);
10898     else
10899       RHS = ImpCastExprToType(RHS.get(), LHSType,
10900                               LHSType->isPointerType() ? CK_BitCast
10901                                 : CK_AnyPointerToBlockPointerCast);
10902     return computeResultTy();
10903   }
10904 
10905   if (LHSType->isObjCObjectPointerType() ||
10906       RHSType->isObjCObjectPointerType()) {
10907     const PointerType *LPT = LHSType->getAs<PointerType>();
10908     const PointerType *RPT = RHSType->getAs<PointerType>();
10909     if (LPT || RPT) {
10910       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10911       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10912 
10913       if (!LPtrToVoid && !RPtrToVoid &&
10914           !Context.typesAreCompatible(LHSType, RHSType)) {
10915         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10916                                           /*isError*/false);
10917       }
10918       if (LHSIsNull && !RHSIsNull) {
10919         Expr *E = LHS.get();
10920         if (getLangOpts().ObjCAutoRefCount)
10921           CheckObjCConversion(SourceRange(), RHSType, E,
10922                               CCK_ImplicitConversion);
10923         LHS = ImpCastExprToType(E, RHSType,
10924                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10925       }
10926       else {
10927         Expr *E = RHS.get();
10928         if (getLangOpts().ObjCAutoRefCount)
10929           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10930                               /*Diagnose=*/true,
10931                               /*DiagnoseCFAudited=*/false, Opc);
10932         RHS = ImpCastExprToType(E, LHSType,
10933                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10934       }
10935       return computeResultTy();
10936     }
10937     if (LHSType->isObjCObjectPointerType() &&
10938         RHSType->isObjCObjectPointerType()) {
10939       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10940         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10941                                           /*isError*/false);
10942       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10943         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10944 
10945       if (LHSIsNull && !RHSIsNull)
10946         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10947       else
10948         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10949       return computeResultTy();
10950     }
10951 
10952     if (!IsRelational && LHSType->isBlockPointerType() &&
10953         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10954       LHS = ImpCastExprToType(LHS.get(), RHSType,
10955                               CK_BlockPointerToObjCPointerCast);
10956       return computeResultTy();
10957     } else if (!IsRelational &&
10958                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10959                RHSType->isBlockPointerType()) {
10960       RHS = ImpCastExprToType(RHS.get(), LHSType,
10961                               CK_BlockPointerToObjCPointerCast);
10962       return computeResultTy();
10963     }
10964   }
10965   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10966       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10967     unsigned DiagID = 0;
10968     bool isError = false;
10969     if (LangOpts.DebuggerSupport) {
10970       // Under a debugger, allow the comparison of pointers to integers,
10971       // since users tend to want to compare addresses.
10972     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10973                (RHSIsNull && RHSType->isIntegerType())) {
10974       if (IsRelational) {
10975         isError = getLangOpts().CPlusPlus;
10976         DiagID =
10977           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10978                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10979       }
10980     } else if (getLangOpts().CPlusPlus) {
10981       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10982       isError = true;
10983     } else if (IsRelational)
10984       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10985     else
10986       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10987 
10988     if (DiagID) {
10989       Diag(Loc, DiagID)
10990         << LHSType << RHSType << LHS.get()->getSourceRange()
10991         << RHS.get()->getSourceRange();
10992       if (isError)
10993         return QualType();
10994     }
10995 
10996     if (LHSType->isIntegerType())
10997       LHS = ImpCastExprToType(LHS.get(), RHSType,
10998                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10999     else
11000       RHS = ImpCastExprToType(RHS.get(), LHSType,
11001                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11002     return computeResultTy();
11003   }
11004 
11005   // Handle block pointers.
11006   if (!IsRelational && RHSIsNull
11007       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11008     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11009     return computeResultTy();
11010   }
11011   if (!IsRelational && LHSIsNull
11012       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11013     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11014     return computeResultTy();
11015   }
11016 
11017   if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11018     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11019       return computeResultTy();
11020     }
11021 
11022     if (LHSType->isQueueT() && RHSType->isQueueT()) {
11023       return computeResultTy();
11024     }
11025 
11026     if (LHSIsNull && RHSType->isQueueT()) {
11027       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11028       return computeResultTy();
11029     }
11030 
11031     if (LHSType->isQueueT() && RHSIsNull) {
11032       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11033       return computeResultTy();
11034     }
11035   }
11036 
11037   return InvalidOperands(Loc, LHS, RHS);
11038 }
11039 
11040 // Return a signed ext_vector_type that is of identical size and number of
11041 // elements. For floating point vectors, return an integer type of identical
11042 // size and number of elements. In the non ext_vector_type case, search from
11043 // the largest type to the smallest type to avoid cases where long long == long,
11044 // where long gets picked over long long.
11045 QualType Sema::GetSignedVectorType(QualType V) {
11046   const VectorType *VTy = V->getAs<VectorType>();
11047   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11048 
11049   if (isa<ExtVectorType>(VTy)) {
11050     if (TypeSize == Context.getTypeSize(Context.CharTy))
11051       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11052     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11053       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11054     else if (TypeSize == Context.getTypeSize(Context.IntTy))
11055       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11056     else if (TypeSize == Context.getTypeSize(Context.LongTy))
11057       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11058     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
11059            "Unhandled vector element size in vector compare");
11060     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11061   }
11062 
11063   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11064     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11065                                  VectorType::GenericVector);
11066   else if (TypeSize == Context.getTypeSize(Context.LongTy))
11067     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11068                                  VectorType::GenericVector);
11069   else if (TypeSize == Context.getTypeSize(Context.IntTy))
11070     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11071                                  VectorType::GenericVector);
11072   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11073     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11074                                  VectorType::GenericVector);
11075   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
11076          "Unhandled vector element size in vector compare");
11077   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11078                                VectorType::GenericVector);
11079 }
11080 
11081 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
11082 /// operates on extended vector types.  Instead of producing an IntTy result,
11083 /// like a scalar comparison, a vector comparison produces a vector of integer
11084 /// types.
11085 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11086                                           SourceLocation Loc,
11087                                           BinaryOperatorKind Opc) {
11088   // Check to make sure we're operating on vectors of the same type and width,
11089   // Allowing one side to be a scalar of element type.
11090   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11091                               /*AllowBothBool*/true,
11092                               /*AllowBoolConversions*/getLangOpts().ZVector);
11093   if (vType.isNull())
11094     return vType;
11095 
11096   QualType LHSType = LHS.get()->getType();
11097 
11098   // If AltiVec, the comparison results in a numeric type, i.e.
11099   // bool for C++, int for C
11100   if (getLangOpts().AltiVec &&
11101       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11102     return Context.getLogicalOperationType();
11103 
11104   // For non-floating point types, check for self-comparisons of the form
11105   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
11106   // often indicate logic errors in the program.
11107   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11108 
11109   // Check for comparisons of floating point operands using != and ==.
11110   if (BinaryOperator::isEqualityOp(Opc) &&
11111       LHSType->hasFloatingRepresentation()) {
11112     assert(RHS.get()->getType()->hasFloatingRepresentation());
11113     CheckFloatComparison(Loc, LHS.get(), RHS.get());
11114   }
11115 
11116   // Return a signed type for the vector.
11117   return GetSignedVectorType(vType);
11118 }
11119 
11120 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11121                                     const ExprResult &XorRHS,
11122                                     const SourceLocation Loc) {
11123   // Do not diagnose macros.
11124   if (Loc.isMacroID())
11125     return;
11126 
11127   bool Negative = false;
11128   bool ExplicitPlus = false;
11129   const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11130   const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11131 
11132   if (!LHSInt)
11133     return;
11134   if (!RHSInt) {
11135     // Check negative literals.
11136     if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11137       UnaryOperatorKind Opc = UO->getOpcode();
11138       if (Opc != UO_Minus && Opc != UO_Plus)
11139         return;
11140       RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11141       if (!RHSInt)
11142         return;
11143       Negative = (Opc == UO_Minus);
11144       ExplicitPlus = !Negative;
11145     } else {
11146       return;
11147     }
11148   }
11149 
11150   const llvm::APInt &LeftSideValue = LHSInt->getValue();
11151   llvm::APInt RightSideValue = RHSInt->getValue();
11152   if (LeftSideValue != 2 && LeftSideValue != 10)
11153     return;
11154 
11155   if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11156     return;
11157 
11158   CharSourceRange ExprRange = CharSourceRange::getCharRange(
11159       LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11160   llvm::StringRef ExprStr =
11161       Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11162 
11163   CharSourceRange XorRange =
11164       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11165   llvm::StringRef XorStr =
11166       Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11167   // Do not diagnose if xor keyword/macro is used.
11168   if (XorStr == "xor")
11169     return;
11170 
11171   std::string LHSStr = Lexer::getSourceText(
11172       CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11173       S.getSourceManager(), S.getLangOpts());
11174   std::string RHSStr = Lexer::getSourceText(
11175       CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11176       S.getSourceManager(), S.getLangOpts());
11177 
11178   if (Negative) {
11179     RightSideValue = -RightSideValue;
11180     RHSStr = "-" + RHSStr;
11181   } else if (ExplicitPlus) {
11182     RHSStr = "+" + RHSStr;
11183   }
11184 
11185   StringRef LHSStrRef = LHSStr;
11186   StringRef RHSStrRef = RHSStr;
11187   // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11188   // literals.
11189   if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11190       RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11191       LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11192       RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11193       (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11194       (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11195       LHSStrRef.find('\'') != StringRef::npos ||
11196       RHSStrRef.find('\'') != StringRef::npos)
11197     return;
11198 
11199   bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11200   const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11201   int64_t RightSideIntValue = RightSideValue.getSExtValue();
11202   if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11203     std::string SuggestedExpr = "1 << " + RHSStr;
11204     bool Overflow = false;
11205     llvm::APInt One = (LeftSideValue - 1);
11206     llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11207     if (Overflow) {
11208       if (RightSideIntValue < 64)
11209         S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11210             << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11211             << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11212       else if (RightSideIntValue == 64)
11213         S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11214       else
11215         return;
11216     } else {
11217       S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11218           << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11219           << PowValue.toString(10, true)
11220           << FixItHint::CreateReplacement(
11221                  ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11222     }
11223 
11224     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11225   } else if (LeftSideValue == 10) {
11226     std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11227     S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11228         << ExprStr << XorValue.toString(10, true) << SuggestedValue
11229         << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11230     S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11231   }
11232 }
11233 
11234 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11235                                           SourceLocation Loc) {
11236   // Ensure that either both operands are of the same vector type, or
11237   // one operand is of a vector type and the other is of its element type.
11238   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11239                                        /*AllowBothBool*/true,
11240                                        /*AllowBoolConversions*/false);
11241   if (vType.isNull())
11242     return InvalidOperands(Loc, LHS, RHS);
11243   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11244       !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11245     return InvalidOperands(Loc, LHS, RHS);
11246   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11247   //        usage of the logical operators && and || with vectors in C. This
11248   //        check could be notionally dropped.
11249   if (!getLangOpts().CPlusPlus &&
11250       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11251     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11252 
11253   return GetSignedVectorType(LHS.get()->getType());
11254 }
11255 
11256 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11257                                            SourceLocation Loc,
11258                                            BinaryOperatorKind Opc) {
11259   checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11260 
11261   bool IsCompAssign =
11262       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11263 
11264   if (LHS.get()->getType()->isVectorType() ||
11265       RHS.get()->getType()->isVectorType()) {
11266     if (LHS.get()->getType()->hasIntegerRepresentation() &&
11267         RHS.get()->getType()->hasIntegerRepresentation())
11268       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11269                         /*AllowBothBool*/true,
11270                         /*AllowBoolConversions*/getLangOpts().ZVector);
11271     return InvalidOperands(Loc, LHS, RHS);
11272   }
11273 
11274   if (Opc == BO_And)
11275     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11276 
11277   ExprResult LHSResult = LHS, RHSResult = RHS;
11278   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
11279                                                  IsCompAssign);
11280   if (LHSResult.isInvalid() || RHSResult.isInvalid())
11281     return QualType();
11282   LHS = LHSResult.get();
11283   RHS = RHSResult.get();
11284 
11285   if (Opc == BO_Xor)
11286     diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11287 
11288   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11289     return compType;
11290   return InvalidOperands(Loc, LHS, RHS);
11291 }
11292 
11293 // C99 6.5.[13,14]
11294 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11295                                            SourceLocation Loc,
11296                                            BinaryOperatorKind Opc) {
11297   // Check vector operands differently.
11298   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11299     return CheckVectorLogicalOperands(LHS, RHS, Loc);
11300 
11301   // Diagnose cases where the user write a logical and/or but probably meant a
11302   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
11303   // is a constant.
11304   if (LHS.get()->getType()->isIntegerType() &&
11305       !LHS.get()->getType()->isBooleanType() &&
11306       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11307       // Don't warn in macros or template instantiations.
11308       !Loc.isMacroID() && !inTemplateInstantiation()) {
11309     // If the RHS can be constant folded, and if it constant folds to something
11310     // that isn't 0 or 1 (which indicate a potential logical operation that
11311     // happened to fold to true/false) then warn.
11312     // Parens on the RHS are ignored.
11313     Expr::EvalResult EVResult;
11314     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11315       llvm::APSInt Result = EVResult.Val.getInt();
11316       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11317            !RHS.get()->getExprLoc().isMacroID()) ||
11318           (Result != 0 && Result != 1)) {
11319         Diag(Loc, diag::warn_logical_instead_of_bitwise)
11320           << RHS.get()->getSourceRange()
11321           << (Opc == BO_LAnd ? "&&" : "||");
11322         // Suggest replacing the logical operator with the bitwise version
11323         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11324             << (Opc == BO_LAnd ? "&" : "|")
11325             << FixItHint::CreateReplacement(SourceRange(
11326                                                  Loc, getLocForEndOfToken(Loc)),
11327                                             Opc == BO_LAnd ? "&" : "|");
11328         if (Opc == BO_LAnd)
11329           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11330           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11331               << FixItHint::CreateRemoval(
11332                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11333                                  RHS.get()->getEndLoc()));
11334       }
11335     }
11336   }
11337 
11338   if (!Context.getLangOpts().CPlusPlus) {
11339     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11340     // not operate on the built-in scalar and vector float types.
11341     if (Context.getLangOpts().OpenCL &&
11342         Context.getLangOpts().OpenCLVersion < 120) {
11343       if (LHS.get()->getType()->isFloatingType() ||
11344           RHS.get()->getType()->isFloatingType())
11345         return InvalidOperands(Loc, LHS, RHS);
11346     }
11347 
11348     LHS = UsualUnaryConversions(LHS.get());
11349     if (LHS.isInvalid())
11350       return QualType();
11351 
11352     RHS = UsualUnaryConversions(RHS.get());
11353     if (RHS.isInvalid())
11354       return QualType();
11355 
11356     if (!LHS.get()->getType()->isScalarType() ||
11357         !RHS.get()->getType()->isScalarType())
11358       return InvalidOperands(Loc, LHS, RHS);
11359 
11360     return Context.IntTy;
11361   }
11362 
11363   // The following is safe because we only use this method for
11364   // non-overloadable operands.
11365 
11366   // C++ [expr.log.and]p1
11367   // C++ [expr.log.or]p1
11368   // The operands are both contextually converted to type bool.
11369   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11370   if (LHSRes.isInvalid())
11371     return InvalidOperands(Loc, LHS, RHS);
11372   LHS = LHSRes;
11373 
11374   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11375   if (RHSRes.isInvalid())
11376     return InvalidOperands(Loc, LHS, RHS);
11377   RHS = RHSRes;
11378 
11379   // C++ [expr.log.and]p2
11380   // C++ [expr.log.or]p2
11381   // The result is a bool.
11382   return Context.BoolTy;
11383 }
11384 
11385 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11386   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11387   if (!ME) return false;
11388   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11389   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11390       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11391   if (!Base) return false;
11392   return Base->getMethodDecl() != nullptr;
11393 }
11394 
11395 /// Is the given expression (which must be 'const') a reference to a
11396 /// variable which was originally non-const, but which has become
11397 /// 'const' due to being captured within a block?
11398 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11399 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11400   assert(E->isLValue() && E->getType().isConstQualified());
11401   E = E->IgnoreParens();
11402 
11403   // Must be a reference to a declaration from an enclosing scope.
11404   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11405   if (!DRE) return NCCK_None;
11406   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11407 
11408   // The declaration must be a variable which is not declared 'const'.
11409   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11410   if (!var) return NCCK_None;
11411   if (var->getType().isConstQualified()) return NCCK_None;
11412   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11413 
11414   // Decide whether the first capture was for a block or a lambda.
11415   DeclContext *DC = S.CurContext, *Prev = nullptr;
11416   // Decide whether the first capture was for a block or a lambda.
11417   while (DC) {
11418     // For init-capture, it is possible that the variable belongs to the
11419     // template pattern of the current context.
11420     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11421       if (var->isInitCapture() &&
11422           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11423         break;
11424     if (DC == var->getDeclContext())
11425       break;
11426     Prev = DC;
11427     DC = DC->getParent();
11428   }
11429   // Unless we have an init-capture, we've gone one step too far.
11430   if (!var->isInitCapture())
11431     DC = Prev;
11432   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11433 }
11434 
11435 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11436   Ty = Ty.getNonReferenceType();
11437   if (IsDereference && Ty->isPointerType())
11438     Ty = Ty->getPointeeType();
11439   return !Ty.isConstQualified();
11440 }
11441 
11442 // Update err_typecheck_assign_const and note_typecheck_assign_const
11443 // when this enum is changed.
11444 enum {
11445   ConstFunction,
11446   ConstVariable,
11447   ConstMember,
11448   ConstMethod,
11449   NestedConstMember,
11450   ConstUnknown,  // Keep as last element
11451 };
11452 
11453 /// Emit the "read-only variable not assignable" error and print notes to give
11454 /// more information about why the variable is not assignable, such as pointing
11455 /// to the declaration of a const variable, showing that a method is const, or
11456 /// that the function is returning a const reference.
11457 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11458                                     SourceLocation Loc) {
11459   SourceRange ExprRange = E->getSourceRange();
11460 
11461   // Only emit one error on the first const found.  All other consts will emit
11462   // a note to the error.
11463   bool DiagnosticEmitted = false;
11464 
11465   // Track if the current expression is the result of a dereference, and if the
11466   // next checked expression is the result of a dereference.
11467   bool IsDereference = false;
11468   bool NextIsDereference = false;
11469 
11470   // Loop to process MemberExpr chains.
11471   while (true) {
11472     IsDereference = NextIsDereference;
11473 
11474     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11475     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11476       NextIsDereference = ME->isArrow();
11477       const ValueDecl *VD = ME->getMemberDecl();
11478       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11479         // Mutable fields can be modified even if the class is const.
11480         if (Field->isMutable()) {
11481           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11482           break;
11483         }
11484 
11485         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11486           if (!DiagnosticEmitted) {
11487             S.Diag(Loc, diag::err_typecheck_assign_const)
11488                 << ExprRange << ConstMember << false /*static*/ << Field
11489                 << Field->getType();
11490             DiagnosticEmitted = true;
11491           }
11492           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11493               << ConstMember << false /*static*/ << Field << Field->getType()
11494               << Field->getSourceRange();
11495         }
11496         E = ME->getBase();
11497         continue;
11498       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11499         if (VDecl->getType().isConstQualified()) {
11500           if (!DiagnosticEmitted) {
11501             S.Diag(Loc, diag::err_typecheck_assign_const)
11502                 << ExprRange << ConstMember << true /*static*/ << VDecl
11503                 << VDecl->getType();
11504             DiagnosticEmitted = true;
11505           }
11506           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11507               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11508               << VDecl->getSourceRange();
11509         }
11510         // Static fields do not inherit constness from parents.
11511         break;
11512       }
11513       break; // End MemberExpr
11514     } else if (const ArraySubscriptExpr *ASE =
11515                    dyn_cast<ArraySubscriptExpr>(E)) {
11516       E = ASE->getBase()->IgnoreParenImpCasts();
11517       continue;
11518     } else if (const ExtVectorElementExpr *EVE =
11519                    dyn_cast<ExtVectorElementExpr>(E)) {
11520       E = EVE->getBase()->IgnoreParenImpCasts();
11521       continue;
11522     }
11523     break;
11524   }
11525 
11526   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11527     // Function calls
11528     const FunctionDecl *FD = CE->getDirectCallee();
11529     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11530       if (!DiagnosticEmitted) {
11531         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11532                                                       << ConstFunction << FD;
11533         DiagnosticEmitted = true;
11534       }
11535       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11536              diag::note_typecheck_assign_const)
11537           << ConstFunction << FD << FD->getReturnType()
11538           << FD->getReturnTypeSourceRange();
11539     }
11540   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11541     // Point to variable declaration.
11542     if (const ValueDecl *VD = DRE->getDecl()) {
11543       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11544         if (!DiagnosticEmitted) {
11545           S.Diag(Loc, diag::err_typecheck_assign_const)
11546               << ExprRange << ConstVariable << VD << VD->getType();
11547           DiagnosticEmitted = true;
11548         }
11549         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11550             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11551       }
11552     }
11553   } else if (isa<CXXThisExpr>(E)) {
11554     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11555       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11556         if (MD->isConst()) {
11557           if (!DiagnosticEmitted) {
11558             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11559                                                           << ConstMethod << MD;
11560             DiagnosticEmitted = true;
11561           }
11562           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11563               << ConstMethod << MD << MD->getSourceRange();
11564         }
11565       }
11566     }
11567   }
11568 
11569   if (DiagnosticEmitted)
11570     return;
11571 
11572   // Can't determine a more specific message, so display the generic error.
11573   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11574 }
11575 
11576 enum OriginalExprKind {
11577   OEK_Variable,
11578   OEK_Member,
11579   OEK_LValue
11580 };
11581 
11582 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11583                                          const RecordType *Ty,
11584                                          SourceLocation Loc, SourceRange Range,
11585                                          OriginalExprKind OEK,
11586                                          bool &DiagnosticEmitted) {
11587   std::vector<const RecordType *> RecordTypeList;
11588   RecordTypeList.push_back(Ty);
11589   unsigned NextToCheckIndex = 0;
11590   // We walk the record hierarchy breadth-first to ensure that we print
11591   // diagnostics in field nesting order.
11592   while (RecordTypeList.size() > NextToCheckIndex) {
11593     bool IsNested = NextToCheckIndex > 0;
11594     for (const FieldDecl *Field :
11595          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11596       // First, check every field for constness.
11597       QualType FieldTy = Field->getType();
11598       if (FieldTy.isConstQualified()) {
11599         if (!DiagnosticEmitted) {
11600           S.Diag(Loc, diag::err_typecheck_assign_const)
11601               << Range << NestedConstMember << OEK << VD
11602               << IsNested << Field;
11603           DiagnosticEmitted = true;
11604         }
11605         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11606             << NestedConstMember << IsNested << Field
11607             << FieldTy << Field->getSourceRange();
11608       }
11609 
11610       // Then we append it to the list to check next in order.
11611       FieldTy = FieldTy.getCanonicalType();
11612       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11613         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11614           RecordTypeList.push_back(FieldRecTy);
11615       }
11616     }
11617     ++NextToCheckIndex;
11618   }
11619 }
11620 
11621 /// Emit an error for the case where a record we are trying to assign to has a
11622 /// const-qualified field somewhere in its hierarchy.
11623 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11624                                          SourceLocation Loc) {
11625   QualType Ty = E->getType();
11626   assert(Ty->isRecordType() && "lvalue was not record?");
11627   SourceRange Range = E->getSourceRange();
11628   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11629   bool DiagEmitted = false;
11630 
11631   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11632     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11633             Range, OEK_Member, DiagEmitted);
11634   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11635     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11636             Range, OEK_Variable, DiagEmitted);
11637   else
11638     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11639             Range, OEK_LValue, DiagEmitted);
11640   if (!DiagEmitted)
11641     DiagnoseConstAssignment(S, E, Loc);
11642 }
11643 
11644 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11645 /// emit an error and return true.  If so, return false.
11646 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11647   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11648 
11649   S.CheckShadowingDeclModification(E, Loc);
11650 
11651   SourceLocation OrigLoc = Loc;
11652   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11653                                                               &Loc);
11654   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11655     IsLV = Expr::MLV_InvalidMessageExpression;
11656   if (IsLV == Expr::MLV_Valid)
11657     return false;
11658 
11659   unsigned DiagID = 0;
11660   bool NeedType = false;
11661   switch (IsLV) { // C99 6.5.16p2
11662   case Expr::MLV_ConstQualified:
11663     // Use a specialized diagnostic when we're assigning to an object
11664     // from an enclosing function or block.
11665     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11666       if (NCCK == NCCK_Block)
11667         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11668       else
11669         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11670       break;
11671     }
11672 
11673     // In ARC, use some specialized diagnostics for occasions where we
11674     // infer 'const'.  These are always pseudo-strong variables.
11675     if (S.getLangOpts().ObjCAutoRefCount) {
11676       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11677       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11678         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11679 
11680         // Use the normal diagnostic if it's pseudo-__strong but the
11681         // user actually wrote 'const'.
11682         if (var->isARCPseudoStrong() &&
11683             (!var->getTypeSourceInfo() ||
11684              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11685           // There are three pseudo-strong cases:
11686           //  - self
11687           ObjCMethodDecl *method = S.getCurMethodDecl();
11688           if (method && var == method->getSelfDecl()) {
11689             DiagID = method->isClassMethod()
11690               ? diag::err_typecheck_arc_assign_self_class_method
11691               : diag::err_typecheck_arc_assign_self;
11692 
11693           //  - Objective-C externally_retained attribute.
11694           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11695                      isa<ParmVarDecl>(var)) {
11696             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11697 
11698           //  - fast enumeration variables
11699           } else {
11700             DiagID = diag::err_typecheck_arr_assign_enumeration;
11701           }
11702 
11703           SourceRange Assign;
11704           if (Loc != OrigLoc)
11705             Assign = SourceRange(OrigLoc, OrigLoc);
11706           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11707           // We need to preserve the AST regardless, so migration tool
11708           // can do its job.
11709           return false;
11710         }
11711       }
11712     }
11713 
11714     // If none of the special cases above are triggered, then this is a
11715     // simple const assignment.
11716     if (DiagID == 0) {
11717       DiagnoseConstAssignment(S, E, Loc);
11718       return true;
11719     }
11720 
11721     break;
11722   case Expr::MLV_ConstAddrSpace:
11723     DiagnoseConstAssignment(S, E, Loc);
11724     return true;
11725   case Expr::MLV_ConstQualifiedField:
11726     DiagnoseRecursiveConstFields(S, E, Loc);
11727     return true;
11728   case Expr::MLV_ArrayType:
11729   case Expr::MLV_ArrayTemporary:
11730     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11731     NeedType = true;
11732     break;
11733   case Expr::MLV_NotObjectType:
11734     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11735     NeedType = true;
11736     break;
11737   case Expr::MLV_LValueCast:
11738     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11739     break;
11740   case Expr::MLV_Valid:
11741     llvm_unreachable("did not take early return for MLV_Valid");
11742   case Expr::MLV_InvalidExpression:
11743   case Expr::MLV_MemberFunction:
11744   case Expr::MLV_ClassTemporary:
11745     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11746     break;
11747   case Expr::MLV_IncompleteType:
11748   case Expr::MLV_IncompleteVoidType:
11749     return S.RequireCompleteType(Loc, E->getType(),
11750              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11751   case Expr::MLV_DuplicateVectorComponents:
11752     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11753     break;
11754   case Expr::MLV_NoSetterProperty:
11755     llvm_unreachable("readonly properties should be processed differently");
11756   case Expr::MLV_InvalidMessageExpression:
11757     DiagID = diag::err_readonly_message_assignment;
11758     break;
11759   case Expr::MLV_SubObjCPropertySetting:
11760     DiagID = diag::err_no_subobject_property_setting;
11761     break;
11762   }
11763 
11764   SourceRange Assign;
11765   if (Loc != OrigLoc)
11766     Assign = SourceRange(OrigLoc, OrigLoc);
11767   if (NeedType)
11768     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11769   else
11770     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11771   return true;
11772 }
11773 
11774 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11775                                          SourceLocation Loc,
11776                                          Sema &Sema) {
11777   if (Sema.inTemplateInstantiation())
11778     return;
11779   if (Sema.isUnevaluatedContext())
11780     return;
11781   if (Loc.isInvalid() || Loc.isMacroID())
11782     return;
11783   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11784     return;
11785 
11786   // C / C++ fields
11787   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11788   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11789   if (ML && MR) {
11790     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11791       return;
11792     const ValueDecl *LHSDecl =
11793         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11794     const ValueDecl *RHSDecl =
11795         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11796     if (LHSDecl != RHSDecl)
11797       return;
11798     if (LHSDecl->getType().isVolatileQualified())
11799       return;
11800     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11801       if (RefTy->getPointeeType().isVolatileQualified())
11802         return;
11803 
11804     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11805   }
11806 
11807   // Objective-C instance variables
11808   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11809   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11810   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11811     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11812     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11813     if (RL && RR && RL->getDecl() == RR->getDecl())
11814       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11815   }
11816 }
11817 
11818 // C99 6.5.16.1
11819 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11820                                        SourceLocation Loc,
11821                                        QualType CompoundType) {
11822   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11823 
11824   // Verify that LHS is a modifiable lvalue, and emit error if not.
11825   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11826     return QualType();
11827 
11828   QualType LHSType = LHSExpr->getType();
11829   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11830                                              CompoundType;
11831   // OpenCL v1.2 s6.1.1.1 p2:
11832   // The half data type can only be used to declare a pointer to a buffer that
11833   // contains half values
11834   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11835     LHSType->isHalfType()) {
11836     Diag(Loc, diag::err_opencl_half_load_store) << 1
11837         << LHSType.getUnqualifiedType();
11838     return QualType();
11839   }
11840 
11841   AssignConvertType ConvTy;
11842   if (CompoundType.isNull()) {
11843     Expr *RHSCheck = RHS.get();
11844 
11845     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11846 
11847     QualType LHSTy(LHSType);
11848     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11849     if (RHS.isInvalid())
11850       return QualType();
11851     // Special case of NSObject attributes on c-style pointer types.
11852     if (ConvTy == IncompatiblePointer &&
11853         ((Context.isObjCNSObjectType(LHSType) &&
11854           RHSType->isObjCObjectPointerType()) ||
11855          (Context.isObjCNSObjectType(RHSType) &&
11856           LHSType->isObjCObjectPointerType())))
11857       ConvTy = Compatible;
11858 
11859     if (ConvTy == Compatible &&
11860         LHSType->isObjCObjectType())
11861         Diag(Loc, diag::err_objc_object_assignment)
11862           << LHSType;
11863 
11864     // If the RHS is a unary plus or minus, check to see if they = and + are
11865     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11866     // instead of "x += 4".
11867     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11868       RHSCheck = ICE->getSubExpr();
11869     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11870       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11871           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11872           // Only if the two operators are exactly adjacent.
11873           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11874           // And there is a space or other character before the subexpr of the
11875           // unary +/-.  We don't want to warn on "x=-1".
11876           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11877           UO->getSubExpr()->getBeginLoc().isFileID()) {
11878         Diag(Loc, diag::warn_not_compound_assign)
11879           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11880           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11881       }
11882     }
11883 
11884     if (ConvTy == Compatible) {
11885       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11886         // Warn about retain cycles where a block captures the LHS, but
11887         // not if the LHS is a simple variable into which the block is
11888         // being stored...unless that variable can be captured by reference!
11889         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11890         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11891         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11892           checkRetainCycles(LHSExpr, RHS.get());
11893       }
11894 
11895       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11896           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11897         // It is safe to assign a weak reference into a strong variable.
11898         // Although this code can still have problems:
11899         //   id x = self.weakProp;
11900         //   id y = self.weakProp;
11901         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11902         // paths through the function. This should be revisited if
11903         // -Wrepeated-use-of-weak is made flow-sensitive.
11904         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11905         // variable, which will be valid for the current autorelease scope.
11906         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11907                              RHS.get()->getBeginLoc()))
11908           getCurFunction()->markSafeWeakUse(RHS.get());
11909 
11910       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11911         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11912       }
11913     }
11914   } else {
11915     // Compound assignment "x += y"
11916     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11917   }
11918 
11919   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11920                                RHS.get(), AA_Assigning))
11921     return QualType();
11922 
11923   CheckForNullPointerDereference(*this, LHSExpr);
11924 
11925   // C99 6.5.16p3: The type of an assignment expression is the type of the
11926   // left operand unless the left operand has qualified type, in which case
11927   // it is the unqualified version of the type of the left operand.
11928   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11929   // is converted to the type of the assignment expression (above).
11930   // C++ 5.17p1: the type of the assignment expression is that of its left
11931   // operand.
11932   return (getLangOpts().CPlusPlus
11933           ? LHSType : LHSType.getUnqualifiedType());
11934 }
11935 
11936 // Only ignore explicit casts to void.
11937 static bool IgnoreCommaOperand(const Expr *E) {
11938   E = E->IgnoreParens();
11939 
11940   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11941     if (CE->getCastKind() == CK_ToVoid) {
11942       return true;
11943     }
11944 
11945     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11946     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11947         CE->getSubExpr()->getType()->isDependentType()) {
11948       return true;
11949     }
11950   }
11951 
11952   return false;
11953 }
11954 
11955 // Look for instances where it is likely the comma operator is confused with
11956 // another operator.  There is a whitelist of acceptable expressions for the
11957 // left hand side of the comma operator, otherwise emit a warning.
11958 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11959   // No warnings in macros
11960   if (Loc.isMacroID())
11961     return;
11962 
11963   // Don't warn in template instantiations.
11964   if (inTemplateInstantiation())
11965     return;
11966 
11967   // Scope isn't fine-grained enough to whitelist the specific cases, so
11968   // instead, skip more than needed, then call back into here with the
11969   // CommaVisitor in SemaStmt.cpp.
11970   // The whitelisted locations are the initialization and increment portions
11971   // of a for loop.  The additional checks are on the condition of
11972   // if statements, do/while loops, and for loops.
11973   // Differences in scope flags for C89 mode requires the extra logic.
11974   const unsigned ForIncrementFlags =
11975       getLangOpts().C99 || getLangOpts().CPlusPlus
11976           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11977           : Scope::ContinueScope | Scope::BreakScope;
11978   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11979   const unsigned ScopeFlags = getCurScope()->getFlags();
11980   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11981       (ScopeFlags & ForInitFlags) == ForInitFlags)
11982     return;
11983 
11984   // If there are multiple comma operators used together, get the RHS of the
11985   // of the comma operator as the LHS.
11986   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11987     if (BO->getOpcode() != BO_Comma)
11988       break;
11989     LHS = BO->getRHS();
11990   }
11991 
11992   // Only allow some expressions on LHS to not warn.
11993   if (IgnoreCommaOperand(LHS))
11994     return;
11995 
11996   Diag(Loc, diag::warn_comma_operator);
11997   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11998       << LHS->getSourceRange()
11999       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12000                                     LangOpts.CPlusPlus ? "static_cast<void>("
12001                                                        : "(void)(")
12002       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12003                                     ")");
12004 }
12005 
12006 // C99 6.5.17
12007 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12008                                    SourceLocation Loc) {
12009   LHS = S.CheckPlaceholderExpr(LHS.get());
12010   RHS = S.CheckPlaceholderExpr(RHS.get());
12011   if (LHS.isInvalid() || RHS.isInvalid())
12012     return QualType();
12013 
12014   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12015   // operands, but not unary promotions.
12016   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12017 
12018   // So we treat the LHS as a ignored value, and in C++ we allow the
12019   // containing site to determine what should be done with the RHS.
12020   LHS = S.IgnoredValueConversions(LHS.get());
12021   if (LHS.isInvalid())
12022     return QualType();
12023 
12024   S.DiagnoseUnusedExprResult(LHS.get());
12025 
12026   if (!S.getLangOpts().CPlusPlus) {
12027     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12028     if (RHS.isInvalid())
12029       return QualType();
12030     if (!RHS.get()->getType()->isVoidType())
12031       S.RequireCompleteType(Loc, RHS.get()->getType(),
12032                             diag::err_incomplete_type);
12033   }
12034 
12035   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12036     S.DiagnoseCommaOperator(LHS.get(), Loc);
12037 
12038   return RHS.get()->getType();
12039 }
12040 
12041 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12042 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12043 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12044                                                ExprValueKind &VK,
12045                                                ExprObjectKind &OK,
12046                                                SourceLocation OpLoc,
12047                                                bool IsInc, bool IsPrefix) {
12048   if (Op->isTypeDependent())
12049     return S.Context.DependentTy;
12050 
12051   QualType ResType = Op->getType();
12052   // Atomic types can be used for increment / decrement where the non-atomic
12053   // versions can, so ignore the _Atomic() specifier for the purpose of
12054   // checking.
12055   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12056     ResType = ResAtomicType->getValueType();
12057 
12058   assert(!ResType.isNull() && "no type for increment/decrement expression");
12059 
12060   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12061     // Decrement of bool is not allowed.
12062     if (!IsInc) {
12063       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12064       return QualType();
12065     }
12066     // Increment of bool sets it to true, but is deprecated.
12067     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12068                                               : diag::warn_increment_bool)
12069       << Op->getSourceRange();
12070   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12071     // Error on enum increments and decrements in C++ mode
12072     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12073     return QualType();
12074   } else if (ResType->isRealType()) {
12075     // OK!
12076   } else if (ResType->isPointerType()) {
12077     // C99 6.5.2.4p2, 6.5.6p2
12078     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12079       return QualType();
12080   } else if (ResType->isObjCObjectPointerType()) {
12081     // On modern runtimes, ObjC pointer arithmetic is forbidden.
12082     // Otherwise, we just need a complete type.
12083     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12084         checkArithmeticOnObjCPointer(S, OpLoc, Op))
12085       return QualType();
12086   } else if (ResType->isAnyComplexType()) {
12087     // C99 does not support ++/-- on complex types, we allow as an extension.
12088     S.Diag(OpLoc, diag::ext_integer_increment_complex)
12089       << ResType << Op->getSourceRange();
12090   } else if (ResType->isPlaceholderType()) {
12091     ExprResult PR = S.CheckPlaceholderExpr(Op);
12092     if (PR.isInvalid()) return QualType();
12093     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12094                                           IsInc, IsPrefix);
12095   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12096     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12097   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12098              (ResType->getAs<VectorType>()->getVectorKind() !=
12099               VectorType::AltiVecBool)) {
12100     // The z vector extensions allow ++ and -- for non-bool vectors.
12101   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12102             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
12103     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12104   } else {
12105     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12106       << ResType << int(IsInc) << Op->getSourceRange();
12107     return QualType();
12108   }
12109   // At this point, we know we have a real, complex or pointer type.
12110   // Now make sure the operand is a modifiable lvalue.
12111   if (CheckForModifiableLvalue(Op, OpLoc, S))
12112     return QualType();
12113   // In C++, a prefix increment is the same type as the operand. Otherwise
12114   // (in C or with postfix), the increment is the unqualified type of the
12115   // operand.
12116   if (IsPrefix && S.getLangOpts().CPlusPlus) {
12117     VK = VK_LValue;
12118     OK = Op->getObjectKind();
12119     return ResType;
12120   } else {
12121     VK = VK_RValue;
12122     return ResType.getUnqualifiedType();
12123   }
12124 }
12125 
12126 
12127 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12128 /// This routine allows us to typecheck complex/recursive expressions
12129 /// where the declaration is needed for type checking. We only need to
12130 /// handle cases when the expression references a function designator
12131 /// or is an lvalue. Here are some examples:
12132 ///  - &(x) => x
12133 ///  - &*****f => f for f a function designator.
12134 ///  - &s.xx => s
12135 ///  - &s.zz[1].yy -> s, if zz is an array
12136 ///  - *(x + 1) -> x, if x is an array
12137 ///  - &"123"[2] -> 0
12138 ///  - & __real__ x -> x
12139 static ValueDecl *getPrimaryDecl(Expr *E) {
12140   switch (E->getStmtClass()) {
12141   case Stmt::DeclRefExprClass:
12142     return cast<DeclRefExpr>(E)->getDecl();
12143   case Stmt::MemberExprClass:
12144     // If this is an arrow operator, the address is an offset from
12145     // the base's value, so the object the base refers to is
12146     // irrelevant.
12147     if (cast<MemberExpr>(E)->isArrow())
12148       return nullptr;
12149     // Otherwise, the expression refers to a part of the base
12150     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12151   case Stmt::ArraySubscriptExprClass: {
12152     // FIXME: This code shouldn't be necessary!  We should catch the implicit
12153     // promotion of register arrays earlier.
12154     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12155     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12156       if (ICE->getSubExpr()->getType()->isArrayType())
12157         return getPrimaryDecl(ICE->getSubExpr());
12158     }
12159     return nullptr;
12160   }
12161   case Stmt::UnaryOperatorClass: {
12162     UnaryOperator *UO = cast<UnaryOperator>(E);
12163 
12164     switch(UO->getOpcode()) {
12165     case UO_Real:
12166     case UO_Imag:
12167     case UO_Extension:
12168       return getPrimaryDecl(UO->getSubExpr());
12169     default:
12170       return nullptr;
12171     }
12172   }
12173   case Stmt::ParenExprClass:
12174     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12175   case Stmt::ImplicitCastExprClass:
12176     // If the result of an implicit cast is an l-value, we care about
12177     // the sub-expression; otherwise, the result here doesn't matter.
12178     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12179   default:
12180     return nullptr;
12181   }
12182 }
12183 
12184 namespace {
12185   enum {
12186     AO_Bit_Field = 0,
12187     AO_Vector_Element = 1,
12188     AO_Property_Expansion = 2,
12189     AO_Register_Variable = 3,
12190     AO_No_Error = 4
12191   };
12192 }
12193 /// Diagnose invalid operand for address of operations.
12194 ///
12195 /// \param Type The type of operand which cannot have its address taken.
12196 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12197                                          Expr *E, unsigned Type) {
12198   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12199 }
12200 
12201 /// CheckAddressOfOperand - The operand of & must be either a function
12202 /// designator or an lvalue designating an object. If it is an lvalue, the
12203 /// object cannot be declared with storage class register or be a bit field.
12204 /// Note: The usual conversions are *not* applied to the operand of the &
12205 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12206 /// In C++, the operand might be an overloaded function name, in which case
12207 /// we allow the '&' but retain the overloaded-function type.
12208 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12209   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12210     if (PTy->getKind() == BuiltinType::Overload) {
12211       Expr *E = OrigOp.get()->IgnoreParens();
12212       if (!isa<OverloadExpr>(E)) {
12213         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
12214         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12215           << OrigOp.get()->getSourceRange();
12216         return QualType();
12217       }
12218 
12219       OverloadExpr *Ovl = cast<OverloadExpr>(E);
12220       if (isa<UnresolvedMemberExpr>(Ovl))
12221         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12222           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12223             << OrigOp.get()->getSourceRange();
12224           return QualType();
12225         }
12226 
12227       return Context.OverloadTy;
12228     }
12229 
12230     if (PTy->getKind() == BuiltinType::UnknownAny)
12231       return Context.UnknownAnyTy;
12232 
12233     if (PTy->getKind() == BuiltinType::BoundMember) {
12234       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12235         << OrigOp.get()->getSourceRange();
12236       return QualType();
12237     }
12238 
12239     OrigOp = CheckPlaceholderExpr(OrigOp.get());
12240     if (OrigOp.isInvalid()) return QualType();
12241   }
12242 
12243   if (OrigOp.get()->isTypeDependent())
12244     return Context.DependentTy;
12245 
12246   assert(!OrigOp.get()->getType()->isPlaceholderType());
12247 
12248   // Make sure to ignore parentheses in subsequent checks
12249   Expr *op = OrigOp.get()->IgnoreParens();
12250 
12251   // In OpenCL captures for blocks called as lambda functions
12252   // are located in the private address space. Blocks used in
12253   // enqueue_kernel can be located in a different address space
12254   // depending on a vendor implementation. Thus preventing
12255   // taking an address of the capture to avoid invalid AS casts.
12256   if (LangOpts.OpenCL) {
12257     auto* VarRef = dyn_cast<DeclRefExpr>(op);
12258     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12259       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12260       return QualType();
12261     }
12262   }
12263 
12264   if (getLangOpts().C99) {
12265     // Implement C99-only parts of addressof rules.
12266     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12267       if (uOp->getOpcode() == UO_Deref)
12268         // Per C99 6.5.3.2, the address of a deref always returns a valid result
12269         // (assuming the deref expression is valid).
12270         return uOp->getSubExpr()->getType();
12271     }
12272     // Technically, there should be a check for array subscript
12273     // expressions here, but the result of one is always an lvalue anyway.
12274   }
12275   ValueDecl *dcl = getPrimaryDecl(op);
12276 
12277   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12278     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12279                                            op->getBeginLoc()))
12280       return QualType();
12281 
12282   Expr::LValueClassification lval = op->ClassifyLValue(Context);
12283   unsigned AddressOfError = AO_No_Error;
12284 
12285   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12286     bool sfinae = (bool)isSFINAEContext();
12287     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12288                                   : diag::ext_typecheck_addrof_temporary)
12289       << op->getType() << op->getSourceRange();
12290     if (sfinae)
12291       return QualType();
12292     // Materialize the temporary as an lvalue so that we can take its address.
12293     OrigOp = op =
12294         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12295   } else if (isa<ObjCSelectorExpr>(op)) {
12296     return Context.getPointerType(op->getType());
12297   } else if (lval == Expr::LV_MemberFunction) {
12298     // If it's an instance method, make a member pointer.
12299     // The expression must have exactly the form &A::foo.
12300 
12301     // If the underlying expression isn't a decl ref, give up.
12302     if (!isa<DeclRefExpr>(op)) {
12303       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12304         << OrigOp.get()->getSourceRange();
12305       return QualType();
12306     }
12307     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12308     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12309 
12310     // The id-expression was parenthesized.
12311     if (OrigOp.get() != DRE) {
12312       Diag(OpLoc, diag::err_parens_pointer_member_function)
12313         << OrigOp.get()->getSourceRange();
12314 
12315     // The method was named without a qualifier.
12316     } else if (!DRE->getQualifier()) {
12317       if (MD->getParent()->getName().empty())
12318         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12319           << op->getSourceRange();
12320       else {
12321         SmallString<32> Str;
12322         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12323         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12324           << op->getSourceRange()
12325           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12326       }
12327     }
12328 
12329     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12330     if (isa<CXXDestructorDecl>(MD))
12331       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12332 
12333     QualType MPTy = Context.getMemberPointerType(
12334         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12335     // Under the MS ABI, lock down the inheritance model now.
12336     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12337       (void)isCompleteType(OpLoc, MPTy);
12338     return MPTy;
12339   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12340     // C99 6.5.3.2p1
12341     // The operand must be either an l-value or a function designator
12342     if (!op->getType()->isFunctionType()) {
12343       // Use a special diagnostic for loads from property references.
12344       if (isa<PseudoObjectExpr>(op)) {
12345         AddressOfError = AO_Property_Expansion;
12346       } else {
12347         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12348           << op->getType() << op->getSourceRange();
12349         return QualType();
12350       }
12351     }
12352   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12353     // The operand cannot be a bit-field
12354     AddressOfError = AO_Bit_Field;
12355   } else if (op->getObjectKind() == OK_VectorComponent) {
12356     // The operand cannot be an element of a vector
12357     AddressOfError = AO_Vector_Element;
12358   } else if (dcl) { // C99 6.5.3.2p1
12359     // We have an lvalue with a decl. Make sure the decl is not declared
12360     // with the register storage-class specifier.
12361     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12362       // in C++ it is not error to take address of a register
12363       // variable (c++03 7.1.1P3)
12364       if (vd->getStorageClass() == SC_Register &&
12365           !getLangOpts().CPlusPlus) {
12366         AddressOfError = AO_Register_Variable;
12367       }
12368     } else if (isa<MSPropertyDecl>(dcl)) {
12369       AddressOfError = AO_Property_Expansion;
12370     } else if (isa<FunctionTemplateDecl>(dcl)) {
12371       return Context.OverloadTy;
12372     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12373       // Okay: we can take the address of a field.
12374       // Could be a pointer to member, though, if there is an explicit
12375       // scope qualifier for the class.
12376       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12377         DeclContext *Ctx = dcl->getDeclContext();
12378         if (Ctx && Ctx->isRecord()) {
12379           if (dcl->getType()->isReferenceType()) {
12380             Diag(OpLoc,
12381                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12382               << dcl->getDeclName() << dcl->getType();
12383             return QualType();
12384           }
12385 
12386           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12387             Ctx = Ctx->getParent();
12388 
12389           QualType MPTy = Context.getMemberPointerType(
12390               op->getType(),
12391               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12392           // Under the MS ABI, lock down the inheritance model now.
12393           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12394             (void)isCompleteType(OpLoc, MPTy);
12395           return MPTy;
12396         }
12397       }
12398     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12399                !isa<BindingDecl>(dcl))
12400       llvm_unreachable("Unknown/unexpected decl type");
12401   }
12402 
12403   if (AddressOfError != AO_No_Error) {
12404     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12405     return QualType();
12406   }
12407 
12408   if (lval == Expr::LV_IncompleteVoidType) {
12409     // Taking the address of a void variable is technically illegal, but we
12410     // allow it in cases which are otherwise valid.
12411     // Example: "extern void x; void* y = &x;".
12412     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12413   }
12414 
12415   // If the operand has type "type", the result has type "pointer to type".
12416   if (op->getType()->isObjCObjectType())
12417     return Context.getObjCObjectPointerType(op->getType());
12418 
12419   CheckAddressOfPackedMember(op);
12420 
12421   return Context.getPointerType(op->getType());
12422 }
12423 
12424 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12425   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12426   if (!DRE)
12427     return;
12428   const Decl *D = DRE->getDecl();
12429   if (!D)
12430     return;
12431   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12432   if (!Param)
12433     return;
12434   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12435     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12436       return;
12437   if (FunctionScopeInfo *FD = S.getCurFunction())
12438     if (!FD->ModifiedNonNullParams.count(Param))
12439       FD->ModifiedNonNullParams.insert(Param);
12440 }
12441 
12442 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12443 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12444                                         SourceLocation OpLoc) {
12445   if (Op->isTypeDependent())
12446     return S.Context.DependentTy;
12447 
12448   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12449   if (ConvResult.isInvalid())
12450     return QualType();
12451   Op = ConvResult.get();
12452   QualType OpTy = Op->getType();
12453   QualType Result;
12454 
12455   if (isa<CXXReinterpretCastExpr>(Op)) {
12456     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12457     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12458                                      Op->getSourceRange());
12459   }
12460 
12461   if (const PointerType *PT = OpTy->getAs<PointerType>())
12462   {
12463     Result = PT->getPointeeType();
12464   }
12465   else if (const ObjCObjectPointerType *OPT =
12466              OpTy->getAs<ObjCObjectPointerType>())
12467     Result = OPT->getPointeeType();
12468   else {
12469     ExprResult PR = S.CheckPlaceholderExpr(Op);
12470     if (PR.isInvalid()) return QualType();
12471     if (PR.get() != Op)
12472       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12473   }
12474 
12475   if (Result.isNull()) {
12476     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12477       << OpTy << Op->getSourceRange();
12478     return QualType();
12479   }
12480 
12481   // Note that per both C89 and C99, indirection is always legal, even if Result
12482   // is an incomplete type or void.  It would be possible to warn about
12483   // dereferencing a void pointer, but it's completely well-defined, and such a
12484   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12485   // for pointers to 'void' but is fine for any other pointer type:
12486   //
12487   // C++ [expr.unary.op]p1:
12488   //   [...] the expression to which [the unary * operator] is applied shall
12489   //   be a pointer to an object type, or a pointer to a function type
12490   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12491     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12492       << OpTy << Op->getSourceRange();
12493 
12494   // Dereferences are usually l-values...
12495   VK = VK_LValue;
12496 
12497   // ...except that certain expressions are never l-values in C.
12498   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12499     VK = VK_RValue;
12500 
12501   return Result;
12502 }
12503 
12504 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12505   BinaryOperatorKind Opc;
12506   switch (Kind) {
12507   default: llvm_unreachable("Unknown binop!");
12508   case tok::periodstar:           Opc = BO_PtrMemD; break;
12509   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12510   case tok::star:                 Opc = BO_Mul; break;
12511   case tok::slash:                Opc = BO_Div; break;
12512   case tok::percent:              Opc = BO_Rem; break;
12513   case tok::plus:                 Opc = BO_Add; break;
12514   case tok::minus:                Opc = BO_Sub; break;
12515   case tok::lessless:             Opc = BO_Shl; break;
12516   case tok::greatergreater:       Opc = BO_Shr; break;
12517   case tok::lessequal:            Opc = BO_LE; break;
12518   case tok::less:                 Opc = BO_LT; break;
12519   case tok::greaterequal:         Opc = BO_GE; break;
12520   case tok::greater:              Opc = BO_GT; break;
12521   case tok::exclaimequal:         Opc = BO_NE; break;
12522   case tok::equalequal:           Opc = BO_EQ; break;
12523   case tok::spaceship:            Opc = BO_Cmp; break;
12524   case tok::amp:                  Opc = BO_And; break;
12525   case tok::caret:                Opc = BO_Xor; break;
12526   case tok::pipe:                 Opc = BO_Or; break;
12527   case tok::ampamp:               Opc = BO_LAnd; break;
12528   case tok::pipepipe:             Opc = BO_LOr; break;
12529   case tok::equal:                Opc = BO_Assign; break;
12530   case tok::starequal:            Opc = BO_MulAssign; break;
12531   case tok::slashequal:           Opc = BO_DivAssign; break;
12532   case tok::percentequal:         Opc = BO_RemAssign; break;
12533   case tok::plusequal:            Opc = BO_AddAssign; break;
12534   case tok::minusequal:           Opc = BO_SubAssign; break;
12535   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12536   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12537   case tok::ampequal:             Opc = BO_AndAssign; break;
12538   case tok::caretequal:           Opc = BO_XorAssign; break;
12539   case tok::pipeequal:            Opc = BO_OrAssign; break;
12540   case tok::comma:                Opc = BO_Comma; break;
12541   }
12542   return Opc;
12543 }
12544 
12545 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12546   tok::TokenKind Kind) {
12547   UnaryOperatorKind Opc;
12548   switch (Kind) {
12549   default: llvm_unreachable("Unknown unary op!");
12550   case tok::plusplus:     Opc = UO_PreInc; break;
12551   case tok::minusminus:   Opc = UO_PreDec; break;
12552   case tok::amp:          Opc = UO_AddrOf; break;
12553   case tok::star:         Opc = UO_Deref; break;
12554   case tok::plus:         Opc = UO_Plus; break;
12555   case tok::minus:        Opc = UO_Minus; break;
12556   case tok::tilde:        Opc = UO_Not; break;
12557   case tok::exclaim:      Opc = UO_LNot; break;
12558   case tok::kw___real:    Opc = UO_Real; break;
12559   case tok::kw___imag:    Opc = UO_Imag; break;
12560   case tok::kw___extension__: Opc = UO_Extension; break;
12561   }
12562   return Opc;
12563 }
12564 
12565 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12566 /// This warning suppressed in the event of macro expansions.
12567 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12568                                    SourceLocation OpLoc, bool IsBuiltin) {
12569   if (S.inTemplateInstantiation())
12570     return;
12571   if (S.isUnevaluatedContext())
12572     return;
12573   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12574     return;
12575   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12576   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12577   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12578   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12579   if (!LHSDeclRef || !RHSDeclRef ||
12580       LHSDeclRef->getLocation().isMacroID() ||
12581       RHSDeclRef->getLocation().isMacroID())
12582     return;
12583   const ValueDecl *LHSDecl =
12584     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12585   const ValueDecl *RHSDecl =
12586     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12587   if (LHSDecl != RHSDecl)
12588     return;
12589   if (LHSDecl->getType().isVolatileQualified())
12590     return;
12591   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12592     if (RefTy->getPointeeType().isVolatileQualified())
12593       return;
12594 
12595   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12596                           : diag::warn_self_assignment_overloaded)
12597       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12598       << RHSExpr->getSourceRange();
12599 }
12600 
12601 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12602 /// is usually indicative of introspection within the Objective-C pointer.
12603 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12604                                           SourceLocation OpLoc) {
12605   if (!S.getLangOpts().ObjC)
12606     return;
12607 
12608   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12609   const Expr *LHS = L.get();
12610   const Expr *RHS = R.get();
12611 
12612   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12613     ObjCPointerExpr = LHS;
12614     OtherExpr = RHS;
12615   }
12616   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12617     ObjCPointerExpr = RHS;
12618     OtherExpr = LHS;
12619   }
12620 
12621   // This warning is deliberately made very specific to reduce false
12622   // positives with logic that uses '&' for hashing.  This logic mainly
12623   // looks for code trying to introspect into tagged pointers, which
12624   // code should generally never do.
12625   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12626     unsigned Diag = diag::warn_objc_pointer_masking;
12627     // Determine if we are introspecting the result of performSelectorXXX.
12628     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12629     // Special case messages to -performSelector and friends, which
12630     // can return non-pointer values boxed in a pointer value.
12631     // Some clients may wish to silence warnings in this subcase.
12632     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12633       Selector S = ME->getSelector();
12634       StringRef SelArg0 = S.getNameForSlot(0);
12635       if (SelArg0.startswith("performSelector"))
12636         Diag = diag::warn_objc_pointer_masking_performSelector;
12637     }
12638 
12639     S.Diag(OpLoc, Diag)
12640       << ObjCPointerExpr->getSourceRange();
12641   }
12642 }
12643 
12644 static NamedDecl *getDeclFromExpr(Expr *E) {
12645   if (!E)
12646     return nullptr;
12647   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12648     return DRE->getDecl();
12649   if (auto *ME = dyn_cast<MemberExpr>(E))
12650     return ME->getMemberDecl();
12651   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12652     return IRE->getDecl();
12653   return nullptr;
12654 }
12655 
12656 // This helper function promotes a binary operator's operands (which are of a
12657 // half vector type) to a vector of floats and then truncates the result to
12658 // a vector of either half or short.
12659 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12660                                       BinaryOperatorKind Opc, QualType ResultTy,
12661                                       ExprValueKind VK, ExprObjectKind OK,
12662                                       bool IsCompAssign, SourceLocation OpLoc,
12663                                       FPOptions FPFeatures) {
12664   auto &Context = S.getASTContext();
12665   assert((isVector(ResultTy, Context.HalfTy) ||
12666           isVector(ResultTy, Context.ShortTy)) &&
12667          "Result must be a vector of half or short");
12668   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12669          isVector(RHS.get()->getType(), Context.HalfTy) &&
12670          "both operands expected to be a half vector");
12671 
12672   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12673   QualType BinOpResTy = RHS.get()->getType();
12674 
12675   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12676   // change BinOpResTy to a vector of ints.
12677   if (isVector(ResultTy, Context.ShortTy))
12678     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12679 
12680   if (IsCompAssign)
12681     return new (Context) CompoundAssignOperator(
12682         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12683         OpLoc, FPFeatures);
12684 
12685   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12686   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12687                                           VK, OK, OpLoc, FPFeatures);
12688   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12689 }
12690 
12691 static std::pair<ExprResult, ExprResult>
12692 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12693                            Expr *RHSExpr) {
12694   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12695   if (!S.getLangOpts().CPlusPlus) {
12696     // C cannot handle TypoExpr nodes on either side of a binop because it
12697     // doesn't handle dependent types properly, so make sure any TypoExprs have
12698     // been dealt with before checking the operands.
12699     LHS = S.CorrectDelayedTyposInExpr(LHS);
12700     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12701       if (Opc != BO_Assign)
12702         return ExprResult(E);
12703       // Avoid correcting the RHS to the same Expr as the LHS.
12704       Decl *D = getDeclFromExpr(E);
12705       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12706     });
12707   }
12708   return std::make_pair(LHS, RHS);
12709 }
12710 
12711 /// Returns true if conversion between vectors of halfs and vectors of floats
12712 /// is needed.
12713 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12714                                      QualType SrcType) {
12715   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12716          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12717          isVector(SrcType, Ctx.HalfTy);
12718 }
12719 
12720 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12721 /// operator @p Opc at location @c TokLoc. This routine only supports
12722 /// built-in operations; ActOnBinOp handles overloaded operators.
12723 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12724                                     BinaryOperatorKind Opc,
12725                                     Expr *LHSExpr, Expr *RHSExpr) {
12726   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12727     // The syntax only allows initializer lists on the RHS of assignment,
12728     // so we don't need to worry about accepting invalid code for
12729     // non-assignment operators.
12730     // C++11 5.17p9:
12731     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12732     //   of x = {} is x = T().
12733     InitializationKind Kind = InitializationKind::CreateDirectList(
12734         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12735     InitializedEntity Entity =
12736         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12737     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12738     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12739     if (Init.isInvalid())
12740       return Init;
12741     RHSExpr = Init.get();
12742   }
12743 
12744   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12745   QualType ResultTy;     // Result type of the binary operator.
12746   // The following two variables are used for compound assignment operators
12747   QualType CompLHSTy;    // Type of LHS after promotions for computation
12748   QualType CompResultTy; // Type of computation result
12749   ExprValueKind VK = VK_RValue;
12750   ExprObjectKind OK = OK_Ordinary;
12751   bool ConvertHalfVec = false;
12752 
12753   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12754   if (!LHS.isUsable() || !RHS.isUsable())
12755     return ExprError();
12756 
12757   if (getLangOpts().OpenCL) {
12758     QualType LHSTy = LHSExpr->getType();
12759     QualType RHSTy = RHSExpr->getType();
12760     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12761     // the ATOMIC_VAR_INIT macro.
12762     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12763       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12764       if (BO_Assign == Opc)
12765         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12766       else
12767         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12768       return ExprError();
12769     }
12770 
12771     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12772     // only with a builtin functions and therefore should be disallowed here.
12773     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12774         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12775         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12776         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12777       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12778       return ExprError();
12779     }
12780   }
12781 
12782   // Diagnose operations on the unsupported types for OpenMP device compilation.
12783   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12784     if (Opc != BO_Assign && Opc != BO_Comma) {
12785       checkOpenMPDeviceExpr(LHSExpr);
12786       checkOpenMPDeviceExpr(RHSExpr);
12787     }
12788   }
12789 
12790   switch (Opc) {
12791   case BO_Assign:
12792     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12793     if (getLangOpts().CPlusPlus &&
12794         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12795       VK = LHS.get()->getValueKind();
12796       OK = LHS.get()->getObjectKind();
12797     }
12798     if (!ResultTy.isNull()) {
12799       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12800       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12801 
12802       // Avoid copying a block to the heap if the block is assigned to a local
12803       // auto variable that is declared in the same scope as the block. This
12804       // optimization is unsafe if the local variable is declared in an outer
12805       // scope. For example:
12806       //
12807       // BlockTy b;
12808       // {
12809       //   b = ^{...};
12810       // }
12811       // // It is unsafe to invoke the block here if it wasn't copied to the
12812       // // heap.
12813       // b();
12814 
12815       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12816         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12817           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12818             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12819               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12820 
12821       if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
12822         checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
12823                               NTCUC_Assignment, NTCUK_Copy);
12824     }
12825     RecordModifiableNonNullParam(*this, LHS.get());
12826     break;
12827   case BO_PtrMemD:
12828   case BO_PtrMemI:
12829     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12830                                             Opc == BO_PtrMemI);
12831     break;
12832   case BO_Mul:
12833   case BO_Div:
12834     ConvertHalfVec = true;
12835     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12836                                            Opc == BO_Div);
12837     break;
12838   case BO_Rem:
12839     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12840     break;
12841   case BO_Add:
12842     ConvertHalfVec = true;
12843     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12844     break;
12845   case BO_Sub:
12846     ConvertHalfVec = true;
12847     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12848     break;
12849   case BO_Shl:
12850   case BO_Shr:
12851     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12852     break;
12853   case BO_LE:
12854   case BO_LT:
12855   case BO_GE:
12856   case BO_GT:
12857     ConvertHalfVec = true;
12858     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12859     break;
12860   case BO_EQ:
12861   case BO_NE:
12862     ConvertHalfVec = true;
12863     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12864     break;
12865   case BO_Cmp:
12866     ConvertHalfVec = true;
12867     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12868     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12869     break;
12870   case BO_And:
12871     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12872     LLVM_FALLTHROUGH;
12873   case BO_Xor:
12874   case BO_Or:
12875     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12876     break;
12877   case BO_LAnd:
12878   case BO_LOr:
12879     ConvertHalfVec = true;
12880     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12881     break;
12882   case BO_MulAssign:
12883   case BO_DivAssign:
12884     ConvertHalfVec = true;
12885     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12886                                                Opc == BO_DivAssign);
12887     CompLHSTy = CompResultTy;
12888     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12889       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12890     break;
12891   case BO_RemAssign:
12892     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12893     CompLHSTy = CompResultTy;
12894     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12895       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12896     break;
12897   case BO_AddAssign:
12898     ConvertHalfVec = true;
12899     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12900     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12901       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12902     break;
12903   case BO_SubAssign:
12904     ConvertHalfVec = true;
12905     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12906     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12907       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12908     break;
12909   case BO_ShlAssign:
12910   case BO_ShrAssign:
12911     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12912     CompLHSTy = CompResultTy;
12913     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12914       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12915     break;
12916   case BO_AndAssign:
12917   case BO_OrAssign: // fallthrough
12918     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12919     LLVM_FALLTHROUGH;
12920   case BO_XorAssign:
12921     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12922     CompLHSTy = CompResultTy;
12923     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12924       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12925     break;
12926   case BO_Comma:
12927     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12928     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12929       VK = RHS.get()->getValueKind();
12930       OK = RHS.get()->getObjectKind();
12931     }
12932     break;
12933   }
12934   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12935     return ExprError();
12936 
12937   // Some of the binary operations require promoting operands of half vector to
12938   // float vectors and truncating the result back to half vector. For now, we do
12939   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12940   // arm64).
12941   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12942          isVector(LHS.get()->getType(), Context.HalfTy) &&
12943          "both sides are half vectors or neither sides are");
12944   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12945                                             LHS.get()->getType());
12946 
12947   // Check for array bounds violations for both sides of the BinaryOperator
12948   CheckArrayAccess(LHS.get());
12949   CheckArrayAccess(RHS.get());
12950 
12951   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12952     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12953                                                  &Context.Idents.get("object_setClass"),
12954                                                  SourceLocation(), LookupOrdinaryName);
12955     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12956       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12957       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12958           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12959                                         "object_setClass(")
12960           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12961                                           ",")
12962           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12963     }
12964     else
12965       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12966   }
12967   else if (const ObjCIvarRefExpr *OIRE =
12968            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12969     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12970 
12971   // Opc is not a compound assignment if CompResultTy is null.
12972   if (CompResultTy.isNull()) {
12973     if (ConvertHalfVec)
12974       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12975                                  OpLoc, FPFeatures);
12976     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12977                                         OK, OpLoc, FPFeatures);
12978   }
12979 
12980   // Handle compound assignments.
12981   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12982       OK_ObjCProperty) {
12983     VK = VK_LValue;
12984     OK = LHS.get()->getObjectKind();
12985   }
12986 
12987   if (ConvertHalfVec)
12988     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12989                                OpLoc, FPFeatures);
12990 
12991   return new (Context) CompoundAssignOperator(
12992       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12993       OpLoc, FPFeatures);
12994 }
12995 
12996 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12997 /// operators are mixed in a way that suggests that the programmer forgot that
12998 /// comparison operators have higher precedence. The most typical example of
12999 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13000 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13001                                       SourceLocation OpLoc, Expr *LHSExpr,
13002                                       Expr *RHSExpr) {
13003   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13004   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13005 
13006   // Check that one of the sides is a comparison operator and the other isn't.
13007   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13008   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13009   if (isLeftComp == isRightComp)
13010     return;
13011 
13012   // Bitwise operations are sometimes used as eager logical ops.
13013   // Don't diagnose this.
13014   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13015   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13016   if (isLeftBitwise || isRightBitwise)
13017     return;
13018 
13019   SourceRange DiagRange = isLeftComp
13020                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13021                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
13022   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13023   SourceRange ParensRange =
13024       isLeftComp
13025           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13026           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13027 
13028   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13029     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13030   SuggestParentheses(Self, OpLoc,
13031     Self.PDiag(diag::note_precedence_silence) << OpStr,
13032     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13033   SuggestParentheses(Self, OpLoc,
13034     Self.PDiag(diag::note_precedence_bitwise_first)
13035       << BinaryOperator::getOpcodeStr(Opc),
13036     ParensRange);
13037 }
13038 
13039 /// It accepts a '&&' expr that is inside a '||' one.
13040 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13041 /// in parentheses.
13042 static void
13043 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13044                                        BinaryOperator *Bop) {
13045   assert(Bop->getOpcode() == BO_LAnd);
13046   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13047       << Bop->getSourceRange() << OpLoc;
13048   SuggestParentheses(Self, Bop->getOperatorLoc(),
13049     Self.PDiag(diag::note_precedence_silence)
13050       << Bop->getOpcodeStr(),
13051     Bop->getSourceRange());
13052 }
13053 
13054 /// Returns true if the given expression can be evaluated as a constant
13055 /// 'true'.
13056 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13057   bool Res;
13058   return !E->isValueDependent() &&
13059          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13060 }
13061 
13062 /// Returns true if the given expression can be evaluated as a constant
13063 /// 'false'.
13064 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13065   bool Res;
13066   return !E->isValueDependent() &&
13067          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13068 }
13069 
13070 /// Look for '&&' in the left hand of a '||' expr.
13071 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13072                                              Expr *LHSExpr, Expr *RHSExpr) {
13073   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13074     if (Bop->getOpcode() == BO_LAnd) {
13075       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13076       if (EvaluatesAsFalse(S, RHSExpr))
13077         return;
13078       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13079       if (!EvaluatesAsTrue(S, Bop->getLHS()))
13080         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13081     } else if (Bop->getOpcode() == BO_LOr) {
13082       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13083         // If it's "a || b && 1 || c" we didn't warn earlier for
13084         // "a || b && 1", but warn now.
13085         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13086           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13087       }
13088     }
13089   }
13090 }
13091 
13092 /// Look for '&&' in the right hand of a '||' expr.
13093 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13094                                              Expr *LHSExpr, Expr *RHSExpr) {
13095   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13096     if (Bop->getOpcode() == BO_LAnd) {
13097       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13098       if (EvaluatesAsFalse(S, LHSExpr))
13099         return;
13100       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13101       if (!EvaluatesAsTrue(S, Bop->getRHS()))
13102         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13103     }
13104   }
13105 }
13106 
13107 /// Look for bitwise op in the left or right hand of a bitwise op with
13108 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
13109 /// the '&' expression in parentheses.
13110 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13111                                          SourceLocation OpLoc, Expr *SubExpr) {
13112   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13113     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13114       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13115         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13116         << Bop->getSourceRange() << OpLoc;
13117       SuggestParentheses(S, Bop->getOperatorLoc(),
13118         S.PDiag(diag::note_precedence_silence)
13119           << Bop->getOpcodeStr(),
13120         Bop->getSourceRange());
13121     }
13122   }
13123 }
13124 
13125 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13126                                     Expr *SubExpr, StringRef Shift) {
13127   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13128     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13129       StringRef Op = Bop->getOpcodeStr();
13130       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13131           << Bop->getSourceRange() << OpLoc << Shift << Op;
13132       SuggestParentheses(S, Bop->getOperatorLoc(),
13133           S.PDiag(diag::note_precedence_silence) << Op,
13134           Bop->getSourceRange());
13135     }
13136   }
13137 }
13138 
13139 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13140                                  Expr *LHSExpr, Expr *RHSExpr) {
13141   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13142   if (!OCE)
13143     return;
13144 
13145   FunctionDecl *FD = OCE->getDirectCallee();
13146   if (!FD || !FD->isOverloadedOperator())
13147     return;
13148 
13149   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13150   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13151     return;
13152 
13153   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13154       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13155       << (Kind == OO_LessLess);
13156   SuggestParentheses(S, OCE->getOperatorLoc(),
13157                      S.PDiag(diag::note_precedence_silence)
13158                          << (Kind == OO_LessLess ? "<<" : ">>"),
13159                      OCE->getSourceRange());
13160   SuggestParentheses(
13161       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13162       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13163 }
13164 
13165 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13166 /// precedence.
13167 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13168                                     SourceLocation OpLoc, Expr *LHSExpr,
13169                                     Expr *RHSExpr){
13170   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13171   if (BinaryOperator::isBitwiseOp(Opc))
13172     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13173 
13174   // Diagnose "arg1 & arg2 | arg3"
13175   if ((Opc == BO_Or || Opc == BO_Xor) &&
13176       !OpLoc.isMacroID()/* Don't warn in macros. */) {
13177     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13178     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13179   }
13180 
13181   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13182   // We don't warn for 'assert(a || b && "bad")' since this is safe.
13183   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13184     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13185     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13186   }
13187 
13188   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13189       || Opc == BO_Shr) {
13190     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13191     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13192     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13193   }
13194 
13195   // Warn on overloaded shift operators and comparisons, such as:
13196   // cout << 5 == 4;
13197   if (BinaryOperator::isComparisonOp(Opc))
13198     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13199 }
13200 
13201 // Binary Operators.  'Tok' is the token for the operator.
13202 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13203                             tok::TokenKind Kind,
13204                             Expr *LHSExpr, Expr *RHSExpr) {
13205   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13206   assert(LHSExpr && "ActOnBinOp(): missing left expression");
13207   assert(RHSExpr && "ActOnBinOp(): missing right expression");
13208 
13209   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13210   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13211 
13212   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13213 }
13214 
13215 /// Build an overloaded binary operator expression in the given scope.
13216 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13217                                        BinaryOperatorKind Opc,
13218                                        Expr *LHS, Expr *RHS) {
13219   switch (Opc) {
13220   case BO_Assign:
13221   case BO_DivAssign:
13222   case BO_RemAssign:
13223   case BO_SubAssign:
13224   case BO_AndAssign:
13225   case BO_OrAssign:
13226   case BO_XorAssign:
13227     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13228     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13229     break;
13230   default:
13231     break;
13232   }
13233 
13234   // Find all of the overloaded operators visible from this
13235   // point. We perform both an operator-name lookup from the local
13236   // scope and an argument-dependent lookup based on the types of
13237   // the arguments.
13238   UnresolvedSet<16> Functions;
13239   OverloadedOperatorKind OverOp
13240     = BinaryOperator::getOverloadedOperator(Opc);
13241   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13242     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13243                                    RHS->getType(), Functions);
13244 
13245   // Build the (potentially-overloaded, potentially-dependent)
13246   // binary operation.
13247   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13248 }
13249 
13250 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13251                             BinaryOperatorKind Opc,
13252                             Expr *LHSExpr, Expr *RHSExpr) {
13253   ExprResult LHS, RHS;
13254   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13255   if (!LHS.isUsable() || !RHS.isUsable())
13256     return ExprError();
13257   LHSExpr = LHS.get();
13258   RHSExpr = RHS.get();
13259 
13260   // We want to end up calling one of checkPseudoObjectAssignment
13261   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13262   // both expressions are overloadable or either is type-dependent),
13263   // or CreateBuiltinBinOp (in any other case).  We also want to get
13264   // any placeholder types out of the way.
13265 
13266   // Handle pseudo-objects in the LHS.
13267   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13268     // Assignments with a pseudo-object l-value need special analysis.
13269     if (pty->getKind() == BuiltinType::PseudoObject &&
13270         BinaryOperator::isAssignmentOp(Opc))
13271       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13272 
13273     // Don't resolve overloads if the other type is overloadable.
13274     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13275       // We can't actually test that if we still have a placeholder,
13276       // though.  Fortunately, none of the exceptions we see in that
13277       // code below are valid when the LHS is an overload set.  Note
13278       // that an overload set can be dependently-typed, but it never
13279       // instantiates to having an overloadable type.
13280       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13281       if (resolvedRHS.isInvalid()) return ExprError();
13282       RHSExpr = resolvedRHS.get();
13283 
13284       if (RHSExpr->isTypeDependent() ||
13285           RHSExpr->getType()->isOverloadableType())
13286         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13287     }
13288 
13289     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13290     // template, diagnose the missing 'template' keyword instead of diagnosing
13291     // an invalid use of a bound member function.
13292     //
13293     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13294     // to C++1z [over.over]/1.4, but we already checked for that case above.
13295     if (Opc == BO_LT && inTemplateInstantiation() &&
13296         (pty->getKind() == BuiltinType::BoundMember ||
13297          pty->getKind() == BuiltinType::Overload)) {
13298       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13299       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13300           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13301             return isa<FunctionTemplateDecl>(ND);
13302           })) {
13303         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13304                                 : OE->getNameLoc(),
13305              diag::err_template_kw_missing)
13306           << OE->getName().getAsString() << "";
13307         return ExprError();
13308       }
13309     }
13310 
13311     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13312     if (LHS.isInvalid()) return ExprError();
13313     LHSExpr = LHS.get();
13314   }
13315 
13316   // Handle pseudo-objects in the RHS.
13317   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13318     // An overload in the RHS can potentially be resolved by the type
13319     // being assigned to.
13320     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13321       if (getLangOpts().CPlusPlus &&
13322           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13323            LHSExpr->getType()->isOverloadableType()))
13324         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13325 
13326       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13327     }
13328 
13329     // Don't resolve overloads if the other type is overloadable.
13330     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13331         LHSExpr->getType()->isOverloadableType())
13332       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13333 
13334     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13335     if (!resolvedRHS.isUsable()) return ExprError();
13336     RHSExpr = resolvedRHS.get();
13337   }
13338 
13339   if (getLangOpts().CPlusPlus) {
13340     // If either expression is type-dependent, always build an
13341     // overloaded op.
13342     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13343       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13344 
13345     // Otherwise, build an overloaded op if either expression has an
13346     // overloadable type.
13347     if (LHSExpr->getType()->isOverloadableType() ||
13348         RHSExpr->getType()->isOverloadableType())
13349       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13350   }
13351 
13352   // Build a built-in binary operation.
13353   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13354 }
13355 
13356 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13357   if (T.isNull() || T->isDependentType())
13358     return false;
13359 
13360   if (!T->isPromotableIntegerType())
13361     return true;
13362 
13363   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13364 }
13365 
13366 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13367                                       UnaryOperatorKind Opc,
13368                                       Expr *InputExpr) {
13369   ExprResult Input = InputExpr;
13370   ExprValueKind VK = VK_RValue;
13371   ExprObjectKind OK = OK_Ordinary;
13372   QualType resultType;
13373   bool CanOverflow = false;
13374 
13375   bool ConvertHalfVec = false;
13376   if (getLangOpts().OpenCL) {
13377     QualType Ty = InputExpr->getType();
13378     // The only legal unary operation for atomics is '&'.
13379     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13380     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13381     // only with a builtin functions and therefore should be disallowed here.
13382         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13383         || Ty->isBlockPointerType())) {
13384       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13385                        << InputExpr->getType()
13386                        << Input.get()->getSourceRange());
13387     }
13388   }
13389   // Diagnose operations on the unsupported types for OpenMP device compilation.
13390   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13391     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13392         UnaryOperator::isArithmeticOp(Opc))
13393       checkOpenMPDeviceExpr(InputExpr);
13394   }
13395 
13396   switch (Opc) {
13397   case UO_PreInc:
13398   case UO_PreDec:
13399   case UO_PostInc:
13400   case UO_PostDec:
13401     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13402                                                 OpLoc,
13403                                                 Opc == UO_PreInc ||
13404                                                 Opc == UO_PostInc,
13405                                                 Opc == UO_PreInc ||
13406                                                 Opc == UO_PreDec);
13407     CanOverflow = isOverflowingIntegerType(Context, resultType);
13408     break;
13409   case UO_AddrOf:
13410     resultType = CheckAddressOfOperand(Input, OpLoc);
13411     CheckAddressOfNoDeref(InputExpr);
13412     RecordModifiableNonNullParam(*this, InputExpr);
13413     break;
13414   case UO_Deref: {
13415     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13416     if (Input.isInvalid()) return ExprError();
13417     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13418     break;
13419   }
13420   case UO_Plus:
13421   case UO_Minus:
13422     CanOverflow = Opc == UO_Minus &&
13423                   isOverflowingIntegerType(Context, Input.get()->getType());
13424     Input = UsualUnaryConversions(Input.get());
13425     if (Input.isInvalid()) return ExprError();
13426     // Unary plus and minus require promoting an operand of half vector to a
13427     // float vector and truncating the result back to a half vector. For now, we
13428     // do this only when HalfArgsAndReturns is set (that is, when the target is
13429     // arm or arm64).
13430     ConvertHalfVec =
13431         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13432 
13433     // If the operand is a half vector, promote it to a float vector.
13434     if (ConvertHalfVec)
13435       Input = convertVector(Input.get(), Context.FloatTy, *this);
13436     resultType = Input.get()->getType();
13437     if (resultType->isDependentType())
13438       break;
13439     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13440       break;
13441     else if (resultType->isVectorType() &&
13442              // The z vector extensions don't allow + or - with bool vectors.
13443              (!Context.getLangOpts().ZVector ||
13444               resultType->getAs<VectorType>()->getVectorKind() !=
13445               VectorType::AltiVecBool))
13446       break;
13447     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13448              Opc == UO_Plus &&
13449              resultType->isPointerType())
13450       break;
13451 
13452     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13453       << resultType << Input.get()->getSourceRange());
13454 
13455   case UO_Not: // bitwise complement
13456     Input = UsualUnaryConversions(Input.get());
13457     if (Input.isInvalid())
13458       return ExprError();
13459     resultType = Input.get()->getType();
13460 
13461     if (resultType->isDependentType())
13462       break;
13463     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13464     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13465       // C99 does not support '~' for complex conjugation.
13466       Diag(OpLoc, diag::ext_integer_complement_complex)
13467           << resultType << Input.get()->getSourceRange();
13468     else if (resultType->hasIntegerRepresentation())
13469       break;
13470     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13471       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13472       // on vector float types.
13473       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13474       if (!T->isIntegerType())
13475         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13476                           << resultType << Input.get()->getSourceRange());
13477     } else {
13478       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13479                        << resultType << Input.get()->getSourceRange());
13480     }
13481     break;
13482 
13483   case UO_LNot: // logical negation
13484     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13485     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13486     if (Input.isInvalid()) return ExprError();
13487     resultType = Input.get()->getType();
13488 
13489     // Though we still have to promote half FP to float...
13490     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13491       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13492       resultType = Context.FloatTy;
13493     }
13494 
13495     if (resultType->isDependentType())
13496       break;
13497     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13498       // C99 6.5.3.3p1: ok, fallthrough;
13499       if (Context.getLangOpts().CPlusPlus) {
13500         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13501         // operand contextually converted to bool.
13502         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13503                                   ScalarTypeToBooleanCastKind(resultType));
13504       } else if (Context.getLangOpts().OpenCL &&
13505                  Context.getLangOpts().OpenCLVersion < 120) {
13506         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13507         // operate on scalar float types.
13508         if (!resultType->isIntegerType() && !resultType->isPointerType())
13509           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13510                            << resultType << Input.get()->getSourceRange());
13511       }
13512     } else if (resultType->isExtVectorType()) {
13513       if (Context.getLangOpts().OpenCL &&
13514           Context.getLangOpts().OpenCLVersion < 120 &&
13515           !Context.getLangOpts().OpenCLCPlusPlus) {
13516         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13517         // operate on vector float types.
13518         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13519         if (!T->isIntegerType())
13520           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13521                            << resultType << Input.get()->getSourceRange());
13522       }
13523       // Vector logical not returns the signed variant of the operand type.
13524       resultType = GetSignedVectorType(resultType);
13525       break;
13526     } else {
13527       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13528       //        type in C++. We should allow that here too.
13529       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13530         << resultType << Input.get()->getSourceRange());
13531     }
13532 
13533     // LNot always has type int. C99 6.5.3.3p5.
13534     // In C++, it's bool. C++ 5.3.1p8
13535     resultType = Context.getLogicalOperationType();
13536     break;
13537   case UO_Real:
13538   case UO_Imag:
13539     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13540     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13541     // complex l-values to ordinary l-values and all other values to r-values.
13542     if (Input.isInvalid()) return ExprError();
13543     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13544       if (Input.get()->getValueKind() != VK_RValue &&
13545           Input.get()->getObjectKind() == OK_Ordinary)
13546         VK = Input.get()->getValueKind();
13547     } else if (!getLangOpts().CPlusPlus) {
13548       // In C, a volatile scalar is read by __imag. In C++, it is not.
13549       Input = DefaultLvalueConversion(Input.get());
13550     }
13551     break;
13552   case UO_Extension:
13553     resultType = Input.get()->getType();
13554     VK = Input.get()->getValueKind();
13555     OK = Input.get()->getObjectKind();
13556     break;
13557   case UO_Coawait:
13558     // It's unnecessary to represent the pass-through operator co_await in the
13559     // AST; just return the input expression instead.
13560     assert(!Input.get()->getType()->isDependentType() &&
13561                    "the co_await expression must be non-dependant before "
13562                    "building operator co_await");
13563     return Input;
13564   }
13565   if (resultType.isNull() || Input.isInvalid())
13566     return ExprError();
13567 
13568   // Check for array bounds violations in the operand of the UnaryOperator,
13569   // except for the '*' and '&' operators that have to be handled specially
13570   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13571   // that are explicitly defined as valid by the standard).
13572   if (Opc != UO_AddrOf && Opc != UO_Deref)
13573     CheckArrayAccess(Input.get());
13574 
13575   auto *UO = new (Context)
13576       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13577 
13578   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13579       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13580     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13581 
13582   // Convert the result back to a half vector.
13583   if (ConvertHalfVec)
13584     return convertVector(UO, Context.HalfTy, *this);
13585   return UO;
13586 }
13587 
13588 /// Determine whether the given expression is a qualified member
13589 /// access expression, of a form that could be turned into a pointer to member
13590 /// with the address-of operator.
13591 bool Sema::isQualifiedMemberAccess(Expr *E) {
13592   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13593     if (!DRE->getQualifier())
13594       return false;
13595 
13596     ValueDecl *VD = DRE->getDecl();
13597     if (!VD->isCXXClassMember())
13598       return false;
13599 
13600     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13601       return true;
13602     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13603       return Method->isInstance();
13604 
13605     return false;
13606   }
13607 
13608   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13609     if (!ULE->getQualifier())
13610       return false;
13611 
13612     for (NamedDecl *D : ULE->decls()) {
13613       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13614         if (Method->isInstance())
13615           return true;
13616       } else {
13617         // Overload set does not contain methods.
13618         break;
13619       }
13620     }
13621 
13622     return false;
13623   }
13624 
13625   return false;
13626 }
13627 
13628 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13629                               UnaryOperatorKind Opc, Expr *Input) {
13630   // First things first: handle placeholders so that the
13631   // overloaded-operator check considers the right type.
13632   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13633     // Increment and decrement of pseudo-object references.
13634     if (pty->getKind() == BuiltinType::PseudoObject &&
13635         UnaryOperator::isIncrementDecrementOp(Opc))
13636       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13637 
13638     // extension is always a builtin operator.
13639     if (Opc == UO_Extension)
13640       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13641 
13642     // & gets special logic for several kinds of placeholder.
13643     // The builtin code knows what to do.
13644     if (Opc == UO_AddrOf &&
13645         (pty->getKind() == BuiltinType::Overload ||
13646          pty->getKind() == BuiltinType::UnknownAny ||
13647          pty->getKind() == BuiltinType::BoundMember))
13648       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13649 
13650     // Anything else needs to be handled now.
13651     ExprResult Result = CheckPlaceholderExpr(Input);
13652     if (Result.isInvalid()) return ExprError();
13653     Input = Result.get();
13654   }
13655 
13656   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13657       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13658       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13659     // Find all of the overloaded operators visible from this
13660     // point. We perform both an operator-name lookup from the local
13661     // scope and an argument-dependent lookup based on the types of
13662     // the arguments.
13663     UnresolvedSet<16> Functions;
13664     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13665     if (S && OverOp != OO_None)
13666       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13667                                    Functions);
13668 
13669     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13670   }
13671 
13672   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13673 }
13674 
13675 // Unary Operators.  'Tok' is the token for the operator.
13676 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13677                               tok::TokenKind Op, Expr *Input) {
13678   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13679 }
13680 
13681 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13682 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13683                                 LabelDecl *TheDecl) {
13684   TheDecl->markUsed(Context);
13685   // Create the AST node.  The address of a label always has type 'void*'.
13686   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13687                                      Context.getPointerType(Context.VoidTy));
13688 }
13689 
13690 void Sema::ActOnStartStmtExpr() {
13691   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13692 }
13693 
13694 void Sema::ActOnStmtExprError() {
13695   // Note that function is also called by TreeTransform when leaving a
13696   // StmtExpr scope without rebuilding anything.
13697 
13698   DiscardCleanupsInEvaluationContext();
13699   PopExpressionEvaluationContext();
13700 }
13701 
13702 ExprResult
13703 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13704                     SourceLocation RPLoc) { // "({..})"
13705   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13706   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13707 
13708   if (hasAnyUnrecoverableErrorsInThisFunction())
13709     DiscardCleanupsInEvaluationContext();
13710   assert(!Cleanup.exprNeedsCleanups() &&
13711          "cleanups within StmtExpr not correctly bound!");
13712   PopExpressionEvaluationContext();
13713 
13714   // FIXME: there are a variety of strange constraints to enforce here, for
13715   // example, it is not possible to goto into a stmt expression apparently.
13716   // More semantic analysis is needed.
13717 
13718   // If there are sub-stmts in the compound stmt, take the type of the last one
13719   // as the type of the stmtexpr.
13720   QualType Ty = Context.VoidTy;
13721   bool StmtExprMayBindToTemp = false;
13722   if (!Compound->body_empty()) {
13723     // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13724     if (const auto *LastStmt =
13725             dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13726       if (const Expr *Value = LastStmt->getExprStmt()) {
13727         StmtExprMayBindToTemp = true;
13728         Ty = Value->getType();
13729       }
13730     }
13731   }
13732 
13733   // FIXME: Check that expression type is complete/non-abstract; statement
13734   // expressions are not lvalues.
13735   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13736   if (StmtExprMayBindToTemp)
13737     return MaybeBindToTemporary(ResStmtExpr);
13738   return ResStmtExpr;
13739 }
13740 
13741 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13742   if (ER.isInvalid())
13743     return ExprError();
13744 
13745   // Do function/array conversion on the last expression, but not
13746   // lvalue-to-rvalue.  However, initialize an unqualified type.
13747   ER = DefaultFunctionArrayConversion(ER.get());
13748   if (ER.isInvalid())
13749     return ExprError();
13750   Expr *E = ER.get();
13751 
13752   if (E->isTypeDependent())
13753     return E;
13754 
13755   // In ARC, if the final expression ends in a consume, splice
13756   // the consume out and bind it later.  In the alternate case
13757   // (when dealing with a retainable type), the result
13758   // initialization will create a produce.  In both cases the
13759   // result will be +1, and we'll need to balance that out with
13760   // a bind.
13761   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13762   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13763     return Cast->getSubExpr();
13764 
13765   // FIXME: Provide a better location for the initialization.
13766   return PerformCopyInitialization(
13767       InitializedEntity::InitializeStmtExprResult(
13768           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13769       SourceLocation(), E);
13770 }
13771 
13772 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13773                                       TypeSourceInfo *TInfo,
13774                                       ArrayRef<OffsetOfComponent> Components,
13775                                       SourceLocation RParenLoc) {
13776   QualType ArgTy = TInfo->getType();
13777   bool Dependent = ArgTy->isDependentType();
13778   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13779 
13780   // We must have at least one component that refers to the type, and the first
13781   // one is known to be a field designator.  Verify that the ArgTy represents
13782   // a struct/union/class.
13783   if (!Dependent && !ArgTy->isRecordType())
13784     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13785                        << ArgTy << TypeRange);
13786 
13787   // Type must be complete per C99 7.17p3 because a declaring a variable
13788   // with an incomplete type would be ill-formed.
13789   if (!Dependent
13790       && RequireCompleteType(BuiltinLoc, ArgTy,
13791                              diag::err_offsetof_incomplete_type, TypeRange))
13792     return ExprError();
13793 
13794   bool DidWarnAboutNonPOD = false;
13795   QualType CurrentType = ArgTy;
13796   SmallVector<OffsetOfNode, 4> Comps;
13797   SmallVector<Expr*, 4> Exprs;
13798   for (const OffsetOfComponent &OC : Components) {
13799     if (OC.isBrackets) {
13800       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13801       if (!CurrentType->isDependentType()) {
13802         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13803         if(!AT)
13804           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13805                            << CurrentType);
13806         CurrentType = AT->getElementType();
13807       } else
13808         CurrentType = Context.DependentTy;
13809 
13810       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13811       if (IdxRval.isInvalid())
13812         return ExprError();
13813       Expr *Idx = IdxRval.get();
13814 
13815       // The expression must be an integral expression.
13816       // FIXME: An integral constant expression?
13817       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13818           !Idx->getType()->isIntegerType())
13819         return ExprError(
13820             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13821             << Idx->getSourceRange());
13822 
13823       // Record this array index.
13824       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13825       Exprs.push_back(Idx);
13826       continue;
13827     }
13828 
13829     // Offset of a field.
13830     if (CurrentType->isDependentType()) {
13831       // We have the offset of a field, but we can't look into the dependent
13832       // type. Just record the identifier of the field.
13833       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13834       CurrentType = Context.DependentTy;
13835       continue;
13836     }
13837 
13838     // We need to have a complete type to look into.
13839     if (RequireCompleteType(OC.LocStart, CurrentType,
13840                             diag::err_offsetof_incomplete_type))
13841       return ExprError();
13842 
13843     // Look for the designated field.
13844     const RecordType *RC = CurrentType->getAs<RecordType>();
13845     if (!RC)
13846       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13847                        << CurrentType);
13848     RecordDecl *RD = RC->getDecl();
13849 
13850     // C++ [lib.support.types]p5:
13851     //   The macro offsetof accepts a restricted set of type arguments in this
13852     //   International Standard. type shall be a POD structure or a POD union
13853     //   (clause 9).
13854     // C++11 [support.types]p4:
13855     //   If type is not a standard-layout class (Clause 9), the results are
13856     //   undefined.
13857     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13858       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13859       unsigned DiagID =
13860         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13861                             : diag::ext_offsetof_non_pod_type;
13862 
13863       if (!IsSafe && !DidWarnAboutNonPOD &&
13864           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13865                               PDiag(DiagID)
13866                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13867                               << CurrentType))
13868         DidWarnAboutNonPOD = true;
13869     }
13870 
13871     // Look for the field.
13872     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13873     LookupQualifiedName(R, RD);
13874     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13875     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13876     if (!MemberDecl) {
13877       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13878         MemberDecl = IndirectMemberDecl->getAnonField();
13879     }
13880 
13881     if (!MemberDecl)
13882       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13883                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13884                                                               OC.LocEnd));
13885 
13886     // C99 7.17p3:
13887     //   (If the specified member is a bit-field, the behavior is undefined.)
13888     //
13889     // We diagnose this as an error.
13890     if (MemberDecl->isBitField()) {
13891       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13892         << MemberDecl->getDeclName()
13893         << SourceRange(BuiltinLoc, RParenLoc);
13894       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13895       return ExprError();
13896     }
13897 
13898     RecordDecl *Parent = MemberDecl->getParent();
13899     if (IndirectMemberDecl)
13900       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13901 
13902     // If the member was found in a base class, introduce OffsetOfNodes for
13903     // the base class indirections.
13904     CXXBasePaths Paths;
13905     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13906                       Paths)) {
13907       if (Paths.getDetectedVirtual()) {
13908         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13909           << MemberDecl->getDeclName()
13910           << SourceRange(BuiltinLoc, RParenLoc);
13911         return ExprError();
13912       }
13913 
13914       CXXBasePath &Path = Paths.front();
13915       for (const CXXBasePathElement &B : Path)
13916         Comps.push_back(OffsetOfNode(B.Base));
13917     }
13918 
13919     if (IndirectMemberDecl) {
13920       for (auto *FI : IndirectMemberDecl->chain()) {
13921         assert(isa<FieldDecl>(FI));
13922         Comps.push_back(OffsetOfNode(OC.LocStart,
13923                                      cast<FieldDecl>(FI), OC.LocEnd));
13924       }
13925     } else
13926       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13927 
13928     CurrentType = MemberDecl->getType().getNonReferenceType();
13929   }
13930 
13931   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13932                               Comps, Exprs, RParenLoc);
13933 }
13934 
13935 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13936                                       SourceLocation BuiltinLoc,
13937                                       SourceLocation TypeLoc,
13938                                       ParsedType ParsedArgTy,
13939                                       ArrayRef<OffsetOfComponent> Components,
13940                                       SourceLocation RParenLoc) {
13941 
13942   TypeSourceInfo *ArgTInfo;
13943   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13944   if (ArgTy.isNull())
13945     return ExprError();
13946 
13947   if (!ArgTInfo)
13948     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13949 
13950   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13951 }
13952 
13953 
13954 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13955                                  Expr *CondExpr,
13956                                  Expr *LHSExpr, Expr *RHSExpr,
13957                                  SourceLocation RPLoc) {
13958   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13959 
13960   ExprValueKind VK = VK_RValue;
13961   ExprObjectKind OK = OK_Ordinary;
13962   QualType resType;
13963   bool ValueDependent = false;
13964   bool CondIsTrue = false;
13965   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13966     resType = Context.DependentTy;
13967     ValueDependent = true;
13968   } else {
13969     // The conditional expression is required to be a constant expression.
13970     llvm::APSInt condEval(32);
13971     ExprResult CondICE
13972       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13973           diag::err_typecheck_choose_expr_requires_constant, false);
13974     if (CondICE.isInvalid())
13975       return ExprError();
13976     CondExpr = CondICE.get();
13977     CondIsTrue = condEval.getZExtValue();
13978 
13979     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13980     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13981 
13982     resType = ActiveExpr->getType();
13983     ValueDependent = ActiveExpr->isValueDependent();
13984     VK = ActiveExpr->getValueKind();
13985     OK = ActiveExpr->getObjectKind();
13986   }
13987 
13988   return new (Context)
13989       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13990                  CondIsTrue, resType->isDependentType(), ValueDependent);
13991 }
13992 
13993 //===----------------------------------------------------------------------===//
13994 // Clang Extensions.
13995 //===----------------------------------------------------------------------===//
13996 
13997 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13998 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13999   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14000 
14001   if (LangOpts.CPlusPlus) {
14002     Decl *ManglingContextDecl;
14003     if (MangleNumberingContext *MCtx =
14004             getCurrentMangleNumberContext(Block->getDeclContext(),
14005                                           ManglingContextDecl)) {
14006       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14007       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14008     }
14009   }
14010 
14011   PushBlockScope(CurScope, Block);
14012   CurContext->addDecl(Block);
14013   if (CurScope)
14014     PushDeclContext(CurScope, Block);
14015   else
14016     CurContext = Block;
14017 
14018   getCurBlock()->HasImplicitReturnType = true;
14019 
14020   // Enter a new evaluation context to insulate the block from any
14021   // cleanups from the enclosing full-expression.
14022   PushExpressionEvaluationContext(
14023       ExpressionEvaluationContext::PotentiallyEvaluated);
14024 }
14025 
14026 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14027                                Scope *CurScope) {
14028   assert(ParamInfo.getIdentifier() == nullptr &&
14029          "block-id should have no identifier!");
14030   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
14031   BlockScopeInfo *CurBlock = getCurBlock();
14032 
14033   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14034   QualType T = Sig->getType();
14035 
14036   // FIXME: We should allow unexpanded parameter packs here, but that would,
14037   // in turn, make the block expression contain unexpanded parameter packs.
14038   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14039     // Drop the parameters.
14040     FunctionProtoType::ExtProtoInfo EPI;
14041     EPI.HasTrailingReturn = false;
14042     EPI.TypeQuals.addConst();
14043     T = Context.getFunctionType(Context.DependentTy, None, EPI);
14044     Sig = Context.getTrivialTypeSourceInfo(T);
14045   }
14046 
14047   // GetTypeForDeclarator always produces a function type for a block
14048   // literal signature.  Furthermore, it is always a FunctionProtoType
14049   // unless the function was written with a typedef.
14050   assert(T->isFunctionType() &&
14051          "GetTypeForDeclarator made a non-function block signature");
14052 
14053   // Look for an explicit signature in that function type.
14054   FunctionProtoTypeLoc ExplicitSignature;
14055 
14056   if ((ExplicitSignature = Sig->getTypeLoc()
14057                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
14058 
14059     // Check whether that explicit signature was synthesized by
14060     // GetTypeForDeclarator.  If so, don't save that as part of the
14061     // written signature.
14062     if (ExplicitSignature.getLocalRangeBegin() ==
14063         ExplicitSignature.getLocalRangeEnd()) {
14064       // This would be much cheaper if we stored TypeLocs instead of
14065       // TypeSourceInfos.
14066       TypeLoc Result = ExplicitSignature.getReturnLoc();
14067       unsigned Size = Result.getFullDataSize();
14068       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14069       Sig->getTypeLoc().initializeFullCopy(Result, Size);
14070 
14071       ExplicitSignature = FunctionProtoTypeLoc();
14072     }
14073   }
14074 
14075   CurBlock->TheDecl->setSignatureAsWritten(Sig);
14076   CurBlock->FunctionType = T;
14077 
14078   const FunctionType *Fn = T->getAs<FunctionType>();
14079   QualType RetTy = Fn->getReturnType();
14080   bool isVariadic =
14081     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14082 
14083   CurBlock->TheDecl->setIsVariadic(isVariadic);
14084 
14085   // Context.DependentTy is used as a placeholder for a missing block
14086   // return type.  TODO:  what should we do with declarators like:
14087   //   ^ * { ... }
14088   // If the answer is "apply template argument deduction"....
14089   if (RetTy != Context.DependentTy) {
14090     CurBlock->ReturnType = RetTy;
14091     CurBlock->TheDecl->setBlockMissingReturnType(false);
14092     CurBlock->HasImplicitReturnType = false;
14093   }
14094 
14095   // Push block parameters from the declarator if we had them.
14096   SmallVector<ParmVarDecl*, 8> Params;
14097   if (ExplicitSignature) {
14098     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14099       ParmVarDecl *Param = ExplicitSignature.getParam(I);
14100       if (Param->getIdentifier() == nullptr &&
14101           !Param->isImplicit() &&
14102           !Param->isInvalidDecl() &&
14103           !getLangOpts().CPlusPlus)
14104         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14105       Params.push_back(Param);
14106     }
14107 
14108   // Fake up parameter variables if we have a typedef, like
14109   //   ^ fntype { ... }
14110   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14111     for (const auto &I : Fn->param_types()) {
14112       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14113           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14114       Params.push_back(Param);
14115     }
14116   }
14117 
14118   // Set the parameters on the block decl.
14119   if (!Params.empty()) {
14120     CurBlock->TheDecl->setParams(Params);
14121     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14122                              /*CheckParameterNames=*/false);
14123   }
14124 
14125   // Finally we can process decl attributes.
14126   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14127 
14128   // Put the parameter variables in scope.
14129   for (auto AI : CurBlock->TheDecl->parameters()) {
14130     AI->setOwningFunction(CurBlock->TheDecl);
14131 
14132     // If this has an identifier, add it to the scope stack.
14133     if (AI->getIdentifier()) {
14134       CheckShadow(CurBlock->TheScope, AI);
14135 
14136       PushOnScopeChains(AI, CurBlock->TheScope);
14137     }
14138   }
14139 }
14140 
14141 /// ActOnBlockError - If there is an error parsing a block, this callback
14142 /// is invoked to pop the information about the block from the action impl.
14143 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14144   // Leave the expression-evaluation context.
14145   DiscardCleanupsInEvaluationContext();
14146   PopExpressionEvaluationContext();
14147 
14148   // Pop off CurBlock, handle nested blocks.
14149   PopDeclContext();
14150   PopFunctionScopeInfo();
14151 }
14152 
14153 /// ActOnBlockStmtExpr - This is called when the body of a block statement
14154 /// literal was successfully completed.  ^(int x){...}
14155 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14156                                     Stmt *Body, Scope *CurScope) {
14157   // If blocks are disabled, emit an error.
14158   if (!LangOpts.Blocks)
14159     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14160 
14161   // Leave the expression-evaluation context.
14162   if (hasAnyUnrecoverableErrorsInThisFunction())
14163     DiscardCleanupsInEvaluationContext();
14164   assert(!Cleanup.exprNeedsCleanups() &&
14165          "cleanups within block not correctly bound!");
14166   PopExpressionEvaluationContext();
14167 
14168   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14169   BlockDecl *BD = BSI->TheDecl;
14170 
14171   if (BSI->HasImplicitReturnType)
14172     deduceClosureReturnType(*BSI);
14173 
14174   QualType RetTy = Context.VoidTy;
14175   if (!BSI->ReturnType.isNull())
14176     RetTy = BSI->ReturnType;
14177 
14178   bool NoReturn = BD->hasAttr<NoReturnAttr>();
14179   QualType BlockTy;
14180 
14181   // If the user wrote a function type in some form, try to use that.
14182   if (!BSI->FunctionType.isNull()) {
14183     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
14184 
14185     FunctionType::ExtInfo Ext = FTy->getExtInfo();
14186     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14187 
14188     // Turn protoless block types into nullary block types.
14189     if (isa<FunctionNoProtoType>(FTy)) {
14190       FunctionProtoType::ExtProtoInfo EPI;
14191       EPI.ExtInfo = Ext;
14192       BlockTy = Context.getFunctionType(RetTy, None, EPI);
14193 
14194     // Otherwise, if we don't need to change anything about the function type,
14195     // preserve its sugar structure.
14196     } else if (FTy->getReturnType() == RetTy &&
14197                (!NoReturn || FTy->getNoReturnAttr())) {
14198       BlockTy = BSI->FunctionType;
14199 
14200     // Otherwise, make the minimal modifications to the function type.
14201     } else {
14202       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14203       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14204       EPI.TypeQuals = Qualifiers();
14205       EPI.ExtInfo = Ext;
14206       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14207     }
14208 
14209   // If we don't have a function type, just build one from nothing.
14210   } else {
14211     FunctionProtoType::ExtProtoInfo EPI;
14212     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14213     BlockTy = Context.getFunctionType(RetTy, None, EPI);
14214   }
14215 
14216   DiagnoseUnusedParameters(BD->parameters());
14217   BlockTy = Context.getBlockPointerType(BlockTy);
14218 
14219   // If needed, diagnose invalid gotos and switches in the block.
14220   if (getCurFunction()->NeedsScopeChecking() &&
14221       !PP.isCodeCompletionEnabled())
14222     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14223 
14224   BD->setBody(cast<CompoundStmt>(Body));
14225 
14226   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14227     DiagnoseUnguardedAvailabilityViolations(BD);
14228 
14229   // Try to apply the named return value optimization. We have to check again
14230   // if we can do this, though, because blocks keep return statements around
14231   // to deduce an implicit return type.
14232   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14233       !BD->isDependentContext())
14234     computeNRVO(Body, BSI);
14235 
14236   if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14237       RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14238     checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14239                           NTCUK_Destruct|NTCUK_Copy);
14240 
14241   PopDeclContext();
14242 
14243   // Pop the block scope now but keep it alive to the end of this function.
14244   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14245   PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14246 
14247   // Set the captured variables on the block.
14248   SmallVector<BlockDecl::Capture, 4> Captures;
14249   for (Capture &Cap : BSI->Captures) {
14250     if (Cap.isInvalid() || Cap.isThisCapture())
14251       continue;
14252 
14253     VarDecl *Var = Cap.getVariable();
14254     Expr *CopyExpr = nullptr;
14255     if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14256       if (const RecordType *Record =
14257               Cap.getCaptureType()->getAs<RecordType>()) {
14258         // The capture logic needs the destructor, so make sure we mark it.
14259         // Usually this is unnecessary because most local variables have
14260         // their destructors marked at declaration time, but parameters are
14261         // an exception because it's technically only the call site that
14262         // actually requires the destructor.
14263         if (isa<ParmVarDecl>(Var))
14264           FinalizeVarWithDestructor(Var, Record);
14265 
14266         // Enter a separate potentially-evaluated context while building block
14267         // initializers to isolate their cleanups from those of the block
14268         // itself.
14269         // FIXME: Is this appropriate even when the block itself occurs in an
14270         // unevaluated operand?
14271         EnterExpressionEvaluationContext EvalContext(
14272             *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14273 
14274         SourceLocation Loc = Cap.getLocation();
14275 
14276         ExprResult Result = BuildDeclarationNameExpr(
14277             CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14278 
14279         // According to the blocks spec, the capture of a variable from
14280         // the stack requires a const copy constructor.  This is not true
14281         // of the copy/move done to move a __block variable to the heap.
14282         if (!Result.isInvalid() &&
14283             !Result.get()->getType().isConstQualified()) {
14284           Result = ImpCastExprToType(Result.get(),
14285                                      Result.get()->getType().withConst(),
14286                                      CK_NoOp, VK_LValue);
14287         }
14288 
14289         if (!Result.isInvalid()) {
14290           Result = PerformCopyInitialization(
14291               InitializedEntity::InitializeBlock(Var->getLocation(),
14292                                                  Cap.getCaptureType(), false),
14293               Loc, Result.get());
14294         }
14295 
14296         // Build a full-expression copy expression if initialization
14297         // succeeded and used a non-trivial constructor.  Recover from
14298         // errors by pretending that the copy isn't necessary.
14299         if (!Result.isInvalid() &&
14300             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14301                 ->isTrivial()) {
14302           Result = MaybeCreateExprWithCleanups(Result);
14303           CopyExpr = Result.get();
14304         }
14305       }
14306     }
14307 
14308     BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14309                               CopyExpr);
14310     Captures.push_back(NewCap);
14311   }
14312   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14313 
14314   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14315 
14316   // If the block isn't obviously global, i.e. it captures anything at
14317   // all, then we need to do a few things in the surrounding context:
14318   if (Result->getBlockDecl()->hasCaptures()) {
14319     // First, this expression has a new cleanup object.
14320     ExprCleanupObjects.push_back(Result->getBlockDecl());
14321     Cleanup.setExprNeedsCleanups(true);
14322 
14323     // It also gets a branch-protected scope if any of the captured
14324     // variables needs destruction.
14325     for (const auto &CI : Result->getBlockDecl()->captures()) {
14326       const VarDecl *var = CI.getVariable();
14327       if (var->getType().isDestructedType() != QualType::DK_none) {
14328         setFunctionHasBranchProtectedScope();
14329         break;
14330       }
14331     }
14332   }
14333 
14334   if (getCurFunction())
14335     getCurFunction()->addBlock(BD);
14336 
14337   return Result;
14338 }
14339 
14340 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14341                             SourceLocation RPLoc) {
14342   TypeSourceInfo *TInfo;
14343   GetTypeFromParser(Ty, &TInfo);
14344   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14345 }
14346 
14347 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14348                                 Expr *E, TypeSourceInfo *TInfo,
14349                                 SourceLocation RPLoc) {
14350   Expr *OrigExpr = E;
14351   bool IsMS = false;
14352 
14353   // CUDA device code does not support varargs.
14354   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14355     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14356       CUDAFunctionTarget T = IdentifyCUDATarget(F);
14357       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14358         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14359     }
14360   }
14361 
14362   // NVPTX does not support va_arg expression.
14363   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14364       Context.getTargetInfo().getTriple().isNVPTX())
14365     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14366 
14367   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14368   // as Microsoft ABI on an actual Microsoft platform, where
14369   // __builtin_ms_va_list and __builtin_va_list are the same.)
14370   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14371       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14372     QualType MSVaListType = Context.getBuiltinMSVaListType();
14373     if (Context.hasSameType(MSVaListType, E->getType())) {
14374       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14375         return ExprError();
14376       IsMS = true;
14377     }
14378   }
14379 
14380   // Get the va_list type
14381   QualType VaListType = Context.getBuiltinVaListType();
14382   if (!IsMS) {
14383     if (VaListType->isArrayType()) {
14384       // Deal with implicit array decay; for example, on x86-64,
14385       // va_list is an array, but it's supposed to decay to
14386       // a pointer for va_arg.
14387       VaListType = Context.getArrayDecayedType(VaListType);
14388       // Make sure the input expression also decays appropriately.
14389       ExprResult Result = UsualUnaryConversions(E);
14390       if (Result.isInvalid())
14391         return ExprError();
14392       E = Result.get();
14393     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14394       // If va_list is a record type and we are compiling in C++ mode,
14395       // check the argument using reference binding.
14396       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14397           Context, Context.getLValueReferenceType(VaListType), false);
14398       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14399       if (Init.isInvalid())
14400         return ExprError();
14401       E = Init.getAs<Expr>();
14402     } else {
14403       // Otherwise, the va_list argument must be an l-value because
14404       // it is modified by va_arg.
14405       if (!E->isTypeDependent() &&
14406           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14407         return ExprError();
14408     }
14409   }
14410 
14411   if (!IsMS && !E->isTypeDependent() &&
14412       !Context.hasSameType(VaListType, E->getType()))
14413     return ExprError(
14414         Diag(E->getBeginLoc(),
14415              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14416         << OrigExpr->getType() << E->getSourceRange());
14417 
14418   if (!TInfo->getType()->isDependentType()) {
14419     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14420                             diag::err_second_parameter_to_va_arg_incomplete,
14421                             TInfo->getTypeLoc()))
14422       return ExprError();
14423 
14424     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14425                                TInfo->getType(),
14426                                diag::err_second_parameter_to_va_arg_abstract,
14427                                TInfo->getTypeLoc()))
14428       return ExprError();
14429 
14430     if (!TInfo->getType().isPODType(Context)) {
14431       Diag(TInfo->getTypeLoc().getBeginLoc(),
14432            TInfo->getType()->isObjCLifetimeType()
14433              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14434              : diag::warn_second_parameter_to_va_arg_not_pod)
14435         << TInfo->getType()
14436         << TInfo->getTypeLoc().getSourceRange();
14437     }
14438 
14439     // Check for va_arg where arguments of the given type will be promoted
14440     // (i.e. this va_arg is guaranteed to have undefined behavior).
14441     QualType PromoteType;
14442     if (TInfo->getType()->isPromotableIntegerType()) {
14443       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14444       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14445         PromoteType = QualType();
14446     }
14447     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14448       PromoteType = Context.DoubleTy;
14449     if (!PromoteType.isNull())
14450       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14451                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14452                           << TInfo->getType()
14453                           << PromoteType
14454                           << TInfo->getTypeLoc().getSourceRange());
14455   }
14456 
14457   QualType T = TInfo->getType().getNonLValueExprType(Context);
14458   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14459 }
14460 
14461 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14462   // The type of __null will be int or long, depending on the size of
14463   // pointers on the target.
14464   QualType Ty;
14465   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14466   if (pw == Context.getTargetInfo().getIntWidth())
14467     Ty = Context.IntTy;
14468   else if (pw == Context.getTargetInfo().getLongWidth())
14469     Ty = Context.LongTy;
14470   else if (pw == Context.getTargetInfo().getLongLongWidth())
14471     Ty = Context.LongLongTy;
14472   else {
14473     llvm_unreachable("I don't know size of pointer!");
14474   }
14475 
14476   return new (Context) GNUNullExpr(Ty, TokenLoc);
14477 }
14478 
14479 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14480                                     SourceLocation BuiltinLoc,
14481                                     SourceLocation RPLoc) {
14482   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14483 }
14484 
14485 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14486                                     SourceLocation BuiltinLoc,
14487                                     SourceLocation RPLoc,
14488                                     DeclContext *ParentContext) {
14489   return new (Context)
14490       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14491 }
14492 
14493 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14494                                               bool Diagnose) {
14495   if (!getLangOpts().ObjC)
14496     return false;
14497 
14498   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14499   if (!PT)
14500     return false;
14501 
14502   if (!PT->isObjCIdType()) {
14503     // Check if the destination is the 'NSString' interface.
14504     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14505     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14506       return false;
14507   }
14508 
14509   // Ignore any parens, implicit casts (should only be
14510   // array-to-pointer decays), and not-so-opaque values.  The last is
14511   // important for making this trigger for property assignments.
14512   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14513   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14514     if (OV->getSourceExpr())
14515       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14516 
14517   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14518   if (!SL || !SL->isAscii())
14519     return false;
14520   if (Diagnose) {
14521     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14522         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14523     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14524   }
14525   return true;
14526 }
14527 
14528 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14529                                               const Expr *SrcExpr) {
14530   if (!DstType->isFunctionPointerType() ||
14531       !SrcExpr->getType()->isFunctionType())
14532     return false;
14533 
14534   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14535   if (!DRE)
14536     return false;
14537 
14538   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14539   if (!FD)
14540     return false;
14541 
14542   return !S.checkAddressOfFunctionIsAvailable(FD,
14543                                               /*Complain=*/true,
14544                                               SrcExpr->getBeginLoc());
14545 }
14546 
14547 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14548                                     SourceLocation Loc,
14549                                     QualType DstType, QualType SrcType,
14550                                     Expr *SrcExpr, AssignmentAction Action,
14551                                     bool *Complained) {
14552   if (Complained)
14553     *Complained = false;
14554 
14555   // Decode the result (notice that AST's are still created for extensions).
14556   bool CheckInferredResultType = false;
14557   bool isInvalid = false;
14558   unsigned DiagKind = 0;
14559   FixItHint Hint;
14560   ConversionFixItGenerator ConvHints;
14561   bool MayHaveConvFixit = false;
14562   bool MayHaveFunctionDiff = false;
14563   const ObjCInterfaceDecl *IFace = nullptr;
14564   const ObjCProtocolDecl *PDecl = nullptr;
14565 
14566   switch (ConvTy) {
14567   case Compatible:
14568       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14569       return false;
14570 
14571   case PointerToInt:
14572     DiagKind = diag::ext_typecheck_convert_pointer_int;
14573     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14574     MayHaveConvFixit = true;
14575     break;
14576   case IntToPointer:
14577     DiagKind = diag::ext_typecheck_convert_int_pointer;
14578     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14579     MayHaveConvFixit = true;
14580     break;
14581   case IncompatiblePointer:
14582     if (Action == AA_Passing_CFAudited)
14583       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14584     else if (SrcType->isFunctionPointerType() &&
14585              DstType->isFunctionPointerType())
14586       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14587     else
14588       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14589 
14590     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14591       SrcType->isObjCObjectPointerType();
14592     if (Hint.isNull() && !CheckInferredResultType) {
14593       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14594     }
14595     else if (CheckInferredResultType) {
14596       SrcType = SrcType.getUnqualifiedType();
14597       DstType = DstType.getUnqualifiedType();
14598     }
14599     MayHaveConvFixit = true;
14600     break;
14601   case IncompatiblePointerSign:
14602     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14603     break;
14604   case FunctionVoidPointer:
14605     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14606     break;
14607   case IncompatiblePointerDiscardsQualifiers: {
14608     // Perform array-to-pointer decay if necessary.
14609     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14610 
14611     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14612     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14613     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14614       DiagKind = diag::err_typecheck_incompatible_address_space;
14615       break;
14616 
14617     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14618       DiagKind = diag::err_typecheck_incompatible_ownership;
14619       break;
14620     }
14621 
14622     llvm_unreachable("unknown error case for discarding qualifiers!");
14623     // fallthrough
14624   }
14625   case CompatiblePointerDiscardsQualifiers:
14626     // If the qualifiers lost were because we were applying the
14627     // (deprecated) C++ conversion from a string literal to a char*
14628     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14629     // Ideally, this check would be performed in
14630     // checkPointerTypesForAssignment. However, that would require a
14631     // bit of refactoring (so that the second argument is an
14632     // expression, rather than a type), which should be done as part
14633     // of a larger effort to fix checkPointerTypesForAssignment for
14634     // C++ semantics.
14635     if (getLangOpts().CPlusPlus &&
14636         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14637       return false;
14638     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14639     break;
14640   case IncompatibleNestedPointerQualifiers:
14641     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14642     break;
14643   case IncompatibleNestedPointerAddressSpaceMismatch:
14644     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14645     break;
14646   case IntToBlockPointer:
14647     DiagKind = diag::err_int_to_block_pointer;
14648     break;
14649   case IncompatibleBlockPointer:
14650     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14651     break;
14652   case IncompatibleObjCQualifiedId: {
14653     if (SrcType->isObjCQualifiedIdType()) {
14654       const ObjCObjectPointerType *srcOPT =
14655                 SrcType->getAs<ObjCObjectPointerType>();
14656       for (auto *srcProto : srcOPT->quals()) {
14657         PDecl = srcProto;
14658         break;
14659       }
14660       if (const ObjCInterfaceType *IFaceT =
14661             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14662         IFace = IFaceT->getDecl();
14663     }
14664     else if (DstType->isObjCQualifiedIdType()) {
14665       const ObjCObjectPointerType *dstOPT =
14666         DstType->getAs<ObjCObjectPointerType>();
14667       for (auto *dstProto : dstOPT->quals()) {
14668         PDecl = dstProto;
14669         break;
14670       }
14671       if (const ObjCInterfaceType *IFaceT =
14672             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14673         IFace = IFaceT->getDecl();
14674     }
14675     DiagKind = diag::warn_incompatible_qualified_id;
14676     break;
14677   }
14678   case IncompatibleVectors:
14679     DiagKind = diag::warn_incompatible_vectors;
14680     break;
14681   case IncompatibleObjCWeakRef:
14682     DiagKind = diag::err_arc_weak_unavailable_assign;
14683     break;
14684   case Incompatible:
14685     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14686       if (Complained)
14687         *Complained = true;
14688       return true;
14689     }
14690 
14691     DiagKind = diag::err_typecheck_convert_incompatible;
14692     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14693     MayHaveConvFixit = true;
14694     isInvalid = true;
14695     MayHaveFunctionDiff = true;
14696     break;
14697   }
14698 
14699   QualType FirstType, SecondType;
14700   switch (Action) {
14701   case AA_Assigning:
14702   case AA_Initializing:
14703     // The destination type comes first.
14704     FirstType = DstType;
14705     SecondType = SrcType;
14706     break;
14707 
14708   case AA_Returning:
14709   case AA_Passing:
14710   case AA_Passing_CFAudited:
14711   case AA_Converting:
14712   case AA_Sending:
14713   case AA_Casting:
14714     // The source type comes first.
14715     FirstType = SrcType;
14716     SecondType = DstType;
14717     break;
14718   }
14719 
14720   PartialDiagnostic FDiag = PDiag(DiagKind);
14721   if (Action == AA_Passing_CFAudited)
14722     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14723   else
14724     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14725 
14726   // If we can fix the conversion, suggest the FixIts.
14727   assert(ConvHints.isNull() || Hint.isNull());
14728   if (!ConvHints.isNull()) {
14729     for (FixItHint &H : ConvHints.Hints)
14730       FDiag << H;
14731   } else {
14732     FDiag << Hint;
14733   }
14734   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14735 
14736   if (MayHaveFunctionDiff)
14737     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14738 
14739   Diag(Loc, FDiag);
14740   if (DiagKind == diag::warn_incompatible_qualified_id &&
14741       PDecl && IFace && !IFace->hasDefinition())
14742       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14743         << IFace << PDecl;
14744 
14745   if (SecondType == Context.OverloadTy)
14746     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14747                               FirstType, /*TakingAddress=*/true);
14748 
14749   if (CheckInferredResultType)
14750     EmitRelatedResultTypeNote(SrcExpr);
14751 
14752   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14753     EmitRelatedResultTypeNoteForReturn(DstType);
14754 
14755   if (Complained)
14756     *Complained = true;
14757   return isInvalid;
14758 }
14759 
14760 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14761                                                  llvm::APSInt *Result) {
14762   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14763   public:
14764     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14765       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14766     }
14767   } Diagnoser;
14768 
14769   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14770 }
14771 
14772 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14773                                                  llvm::APSInt *Result,
14774                                                  unsigned DiagID,
14775                                                  bool AllowFold) {
14776   class IDDiagnoser : public VerifyICEDiagnoser {
14777     unsigned DiagID;
14778 
14779   public:
14780     IDDiagnoser(unsigned DiagID)
14781       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14782 
14783     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14784       S.Diag(Loc, DiagID) << SR;
14785     }
14786   } Diagnoser(DiagID);
14787 
14788   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14789 }
14790 
14791 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14792                                             SourceRange SR) {
14793   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14794 }
14795 
14796 ExprResult
14797 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14798                                       VerifyICEDiagnoser &Diagnoser,
14799                                       bool AllowFold) {
14800   SourceLocation DiagLoc = E->getBeginLoc();
14801 
14802   if (getLangOpts().CPlusPlus11) {
14803     // C++11 [expr.const]p5:
14804     //   If an expression of literal class type is used in a context where an
14805     //   integral constant expression is required, then that class type shall
14806     //   have a single non-explicit conversion function to an integral or
14807     //   unscoped enumeration type
14808     ExprResult Converted;
14809     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14810     public:
14811       CXX11ConvertDiagnoser(bool Silent)
14812           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14813                                 Silent, true) {}
14814 
14815       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14816                                            QualType T) override {
14817         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14818       }
14819 
14820       SemaDiagnosticBuilder diagnoseIncomplete(
14821           Sema &S, SourceLocation Loc, QualType T) override {
14822         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14823       }
14824 
14825       SemaDiagnosticBuilder diagnoseExplicitConv(
14826           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14827         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14828       }
14829 
14830       SemaDiagnosticBuilder noteExplicitConv(
14831           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14832         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14833                  << ConvTy->isEnumeralType() << ConvTy;
14834       }
14835 
14836       SemaDiagnosticBuilder diagnoseAmbiguous(
14837           Sema &S, SourceLocation Loc, QualType T) override {
14838         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14839       }
14840 
14841       SemaDiagnosticBuilder noteAmbiguous(
14842           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14843         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14844                  << ConvTy->isEnumeralType() << ConvTy;
14845       }
14846 
14847       SemaDiagnosticBuilder diagnoseConversion(
14848           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14849         llvm_unreachable("conversion functions are permitted");
14850       }
14851     } ConvertDiagnoser(Diagnoser.Suppress);
14852 
14853     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14854                                                     ConvertDiagnoser);
14855     if (Converted.isInvalid())
14856       return Converted;
14857     E = Converted.get();
14858     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14859       return ExprError();
14860   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14861     // An ICE must be of integral or unscoped enumeration type.
14862     if (!Diagnoser.Suppress)
14863       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14864     return ExprError();
14865   }
14866 
14867   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14868   // in the non-ICE case.
14869   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14870     if (Result)
14871       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14872     if (!isa<ConstantExpr>(E))
14873       E = ConstantExpr::Create(Context, E);
14874     return E;
14875   }
14876 
14877   Expr::EvalResult EvalResult;
14878   SmallVector<PartialDiagnosticAt, 8> Notes;
14879   EvalResult.Diag = &Notes;
14880 
14881   // Try to evaluate the expression, and produce diagnostics explaining why it's
14882   // not a constant expression as a side-effect.
14883   bool Folded =
14884       E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
14885       EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14886 
14887   if (!isa<ConstantExpr>(E))
14888     E = ConstantExpr::Create(Context, E, EvalResult.Val);
14889 
14890   // In C++11, we can rely on diagnostics being produced for any expression
14891   // which is not a constant expression. If no diagnostics were produced, then
14892   // this is a constant expression.
14893   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14894     if (Result)
14895       *Result = EvalResult.Val.getInt();
14896     return E;
14897   }
14898 
14899   // If our only note is the usual "invalid subexpression" note, just point
14900   // the caret at its location rather than producing an essentially
14901   // redundant note.
14902   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14903         diag::note_invalid_subexpr_in_const_expr) {
14904     DiagLoc = Notes[0].first;
14905     Notes.clear();
14906   }
14907 
14908   if (!Folded || !AllowFold) {
14909     if (!Diagnoser.Suppress) {
14910       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14911       for (const PartialDiagnosticAt &Note : Notes)
14912         Diag(Note.first, Note.second);
14913     }
14914 
14915     return ExprError();
14916   }
14917 
14918   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14919   for (const PartialDiagnosticAt &Note : Notes)
14920     Diag(Note.first, Note.second);
14921 
14922   if (Result)
14923     *Result = EvalResult.Val.getInt();
14924   return E;
14925 }
14926 
14927 namespace {
14928   // Handle the case where we conclude a expression which we speculatively
14929   // considered to be unevaluated is actually evaluated.
14930   class TransformToPE : public TreeTransform<TransformToPE> {
14931     typedef TreeTransform<TransformToPE> BaseTransform;
14932 
14933   public:
14934     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14935 
14936     // Make sure we redo semantic analysis
14937     bool AlwaysRebuild() { return true; }
14938     bool ReplacingOriginal() { return true; }
14939 
14940     // We need to special-case DeclRefExprs referring to FieldDecls which
14941     // are not part of a member pointer formation; normal TreeTransforming
14942     // doesn't catch this case because of the way we represent them in the AST.
14943     // FIXME: This is a bit ugly; is it really the best way to handle this
14944     // case?
14945     //
14946     // Error on DeclRefExprs referring to FieldDecls.
14947     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14948       if (isa<FieldDecl>(E->getDecl()) &&
14949           !SemaRef.isUnevaluatedContext())
14950         return SemaRef.Diag(E->getLocation(),
14951                             diag::err_invalid_non_static_member_use)
14952             << E->getDecl() << E->getSourceRange();
14953 
14954       return BaseTransform::TransformDeclRefExpr(E);
14955     }
14956 
14957     // Exception: filter out member pointer formation
14958     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14959       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14960         return E;
14961 
14962       return BaseTransform::TransformUnaryOperator(E);
14963     }
14964 
14965     // The body of a lambda-expression is in a separate expression evaluation
14966     // context so never needs to be transformed.
14967     // FIXME: Ideally we wouldn't transform the closure type either, and would
14968     // just recreate the capture expressions and lambda expression.
14969     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
14970       return SkipLambdaBody(E, Body);
14971     }
14972   };
14973 }
14974 
14975 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14976   assert(isUnevaluatedContext() &&
14977          "Should only transform unevaluated expressions");
14978   ExprEvalContexts.back().Context =
14979       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14980   if (isUnevaluatedContext())
14981     return E;
14982   return TransformToPE(*this).TransformExpr(E);
14983 }
14984 
14985 void
14986 Sema::PushExpressionEvaluationContext(
14987     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14988     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14989   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14990                                 LambdaContextDecl, ExprContext);
14991   Cleanup.reset();
14992   if (!MaybeODRUseExprs.empty())
14993     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14994 }
14995 
14996 void
14997 Sema::PushExpressionEvaluationContext(
14998     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14999     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15000   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15001   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15002 }
15003 
15004 namespace {
15005 
15006 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15007   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15008   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15009     if (E->getOpcode() == UO_Deref)
15010       return CheckPossibleDeref(S, E->getSubExpr());
15011   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15012     return CheckPossibleDeref(S, E->getBase());
15013   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15014     return CheckPossibleDeref(S, E->getBase());
15015   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15016     QualType Inner;
15017     QualType Ty = E->getType();
15018     if (const auto *Ptr = Ty->getAs<PointerType>())
15019       Inner = Ptr->getPointeeType();
15020     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15021       Inner = Arr->getElementType();
15022     else
15023       return nullptr;
15024 
15025     if (Inner->hasAttr(attr::NoDeref))
15026       return E;
15027   }
15028   return nullptr;
15029 }
15030 
15031 } // namespace
15032 
15033 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15034   for (const Expr *E : Rec.PossibleDerefs) {
15035     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15036     if (DeclRef) {
15037       const ValueDecl *Decl = DeclRef->getDecl();
15038       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15039           << Decl->getName() << E->getSourceRange();
15040       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15041     } else {
15042       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15043           << E->getSourceRange();
15044     }
15045   }
15046   Rec.PossibleDerefs.clear();
15047 }
15048 
15049 void Sema::PopExpressionEvaluationContext() {
15050   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15051   unsigned NumTypos = Rec.NumTypos;
15052 
15053   if (!Rec.Lambdas.empty()) {
15054     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15055     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15056         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15057       unsigned D;
15058       if (Rec.isUnevaluated()) {
15059         // C++11 [expr.prim.lambda]p2:
15060         //   A lambda-expression shall not appear in an unevaluated operand
15061         //   (Clause 5).
15062         D = diag::err_lambda_unevaluated_operand;
15063       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15064         // C++1y [expr.const]p2:
15065         //   A conditional-expression e is a core constant expression unless the
15066         //   evaluation of e, following the rules of the abstract machine, would
15067         //   evaluate [...] a lambda-expression.
15068         D = diag::err_lambda_in_constant_expression;
15069       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15070         // C++17 [expr.prim.lamda]p2:
15071         // A lambda-expression shall not appear [...] in a template-argument.
15072         D = diag::err_lambda_in_invalid_context;
15073       } else
15074         llvm_unreachable("Couldn't infer lambda error message.");
15075 
15076       for (const auto *L : Rec.Lambdas)
15077         Diag(L->getBeginLoc(), D);
15078     }
15079   }
15080 
15081   WarnOnPendingNoDerefs(Rec);
15082 
15083   // When are coming out of an unevaluated context, clear out any
15084   // temporaries that we may have created as part of the evaluation of
15085   // the expression in that context: they aren't relevant because they
15086   // will never be constructed.
15087   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15088     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15089                              ExprCleanupObjects.end());
15090     Cleanup = Rec.ParentCleanup;
15091     CleanupVarDeclMarking();
15092     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15093   // Otherwise, merge the contexts together.
15094   } else {
15095     Cleanup.mergeFrom(Rec.ParentCleanup);
15096     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15097                             Rec.SavedMaybeODRUseExprs.end());
15098   }
15099 
15100   // Pop the current expression evaluation context off the stack.
15101   ExprEvalContexts.pop_back();
15102 
15103   // The global expression evaluation context record is never popped.
15104   ExprEvalContexts.back().NumTypos += NumTypos;
15105 }
15106 
15107 void Sema::DiscardCleanupsInEvaluationContext() {
15108   ExprCleanupObjects.erase(
15109          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15110          ExprCleanupObjects.end());
15111   Cleanup.reset();
15112   MaybeODRUseExprs.clear();
15113 }
15114 
15115 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15116   ExprResult Result = CheckPlaceholderExpr(E);
15117   if (Result.isInvalid())
15118     return ExprError();
15119   E = Result.get();
15120   if (!E->getType()->isVariablyModifiedType())
15121     return E;
15122   return TransformToPotentiallyEvaluated(E);
15123 }
15124 
15125 /// Are we in a context that is potentially constant evaluated per C++20
15126 /// [expr.const]p12?
15127 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15128   /// C++2a [expr.const]p12:
15129   //   An expression or conversion is potentially constant evaluated if it is
15130   switch (SemaRef.ExprEvalContexts.back().Context) {
15131     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15132       // -- a manifestly constant-evaluated expression,
15133     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15134     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15135     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15136       // -- a potentially-evaluated expression,
15137     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15138       // -- an immediate subexpression of a braced-init-list,
15139 
15140       // -- [FIXME] an expression of the form & cast-expression that occurs
15141       //    within a templated entity
15142       // -- a subexpression of one of the above that is not a subexpression of
15143       // a nested unevaluated operand.
15144       return true;
15145 
15146     case Sema::ExpressionEvaluationContext::Unevaluated:
15147     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15148       // Expressions in this context are never evaluated.
15149       return false;
15150   }
15151   llvm_unreachable("Invalid context");
15152 }
15153 
15154 /// Return true if this function has a calling convention that requires mangling
15155 /// in the size of the parameter pack.
15156 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15157   // These manglings don't do anything on non-Windows or non-x86 platforms, so
15158   // we don't need parameter type sizes.
15159   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15160   if (!TT.isOSWindows() || (TT.getArch() != llvm::Triple::x86 &&
15161                             TT.getArch() != llvm::Triple::x86_64))
15162     return false;
15163 
15164   // If this is C++ and this isn't an extern "C" function, parameters do not
15165   // need to be complete. In this case, C++ mangling will apply, which doesn't
15166   // use the size of the parameters.
15167   if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15168     return false;
15169 
15170   // Stdcall, fastcall, and vectorcall need this special treatment.
15171   CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15172   switch (CC) {
15173   case CC_X86StdCall:
15174   case CC_X86FastCall:
15175   case CC_X86VectorCall:
15176     return true;
15177   default:
15178     break;
15179   }
15180   return false;
15181 }
15182 
15183 /// Require that all of the parameter types of function be complete. Normally,
15184 /// parameter types are only required to be complete when a function is called
15185 /// or defined, but to mangle functions with certain calling conventions, the
15186 /// mangler needs to know the size of the parameter list. In this situation,
15187 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15188 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15189 /// result in a linker error. Clang doesn't implement this behavior, and instead
15190 /// attempts to error at compile time.
15191 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15192                                                   SourceLocation Loc) {
15193   class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15194     FunctionDecl *FD;
15195     ParmVarDecl *Param;
15196 
15197   public:
15198     ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15199         : FD(FD), Param(Param) {}
15200 
15201     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15202       CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15203       StringRef CCName;
15204       switch (CC) {
15205       case CC_X86StdCall:
15206         CCName = "stdcall";
15207         break;
15208       case CC_X86FastCall:
15209         CCName = "fastcall";
15210         break;
15211       case CC_X86VectorCall:
15212         CCName = "vectorcall";
15213         break;
15214       default:
15215         llvm_unreachable("CC does not need mangling");
15216       }
15217 
15218       S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15219           << Param->getDeclName() << FD->getDeclName() << CCName;
15220     }
15221   };
15222 
15223   for (ParmVarDecl *Param : FD->parameters()) {
15224     ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15225     S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15226   }
15227 }
15228 
15229 namespace {
15230 enum class OdrUseContext {
15231   /// Declarations in this context are not odr-used.
15232   None,
15233   /// Declarations in this context are formally odr-used, but this is a
15234   /// dependent context.
15235   Dependent,
15236   /// Declarations in this context are odr-used but not actually used (yet).
15237   FormallyOdrUsed,
15238   /// Declarations in this context are used.
15239   Used
15240 };
15241 }
15242 
15243 /// Are we within a context in which references to resolved functions or to
15244 /// variables result in odr-use?
15245 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15246   OdrUseContext Result;
15247 
15248   switch (SemaRef.ExprEvalContexts.back().Context) {
15249     case Sema::ExpressionEvaluationContext::Unevaluated:
15250     case Sema::ExpressionEvaluationContext::UnevaluatedList:
15251     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15252       return OdrUseContext::None;
15253 
15254     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15255     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15256       Result = OdrUseContext::Used;
15257       break;
15258 
15259     case Sema::ExpressionEvaluationContext::DiscardedStatement:
15260       Result = OdrUseContext::FormallyOdrUsed;
15261       break;
15262 
15263     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15264       // A default argument formally results in odr-use, but doesn't actually
15265       // result in a use in any real sense until it itself is used.
15266       Result = OdrUseContext::FormallyOdrUsed;
15267       break;
15268   }
15269 
15270   if (SemaRef.CurContext->isDependentContext())
15271     return OdrUseContext::Dependent;
15272 
15273   return Result;
15274 }
15275 
15276 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15277   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
15278   return Func->isConstexpr() &&
15279          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
15280 }
15281 
15282 /// Mark a function referenced, and check whether it is odr-used
15283 /// (C++ [basic.def.odr]p2, C99 6.9p3)
15284 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15285                                   bool MightBeOdrUse) {
15286   assert(Func && "No function?");
15287 
15288   Func->setReferenced();
15289 
15290   // Recursive functions aren't really used until they're used from some other
15291   // context.
15292   bool IsRecursiveCall = CurContext == Func;
15293 
15294   // C++11 [basic.def.odr]p3:
15295   //   A function whose name appears as a potentially-evaluated expression is
15296   //   odr-used if it is the unique lookup result or the selected member of a
15297   //   set of overloaded functions [...].
15298   //
15299   // We (incorrectly) mark overload resolution as an unevaluated context, so we
15300   // can just check that here.
15301   OdrUseContext OdrUse =
15302       MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15303   if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15304     OdrUse = OdrUseContext::FormallyOdrUsed;
15305 
15306   // Trivial default constructors and destructors are never actually used.
15307   // FIXME: What about other special members?
15308   if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15309       OdrUse == OdrUseContext::Used) {
15310     if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15311       if (Constructor->isDefaultConstructor())
15312         OdrUse = OdrUseContext::FormallyOdrUsed;
15313     if (isa<CXXDestructorDecl>(Func))
15314       OdrUse = OdrUseContext::FormallyOdrUsed;
15315   }
15316 
15317   // C++20 [expr.const]p12:
15318   //   A function [...] is needed for constant evaluation if it is [...] a
15319   //   constexpr function that is named by an expression that is potentially
15320   //   constant evaluated
15321   bool NeededForConstantEvaluation =
15322       isPotentiallyConstantEvaluatedContext(*this) &&
15323       isImplicitlyDefinableConstexprFunction(Func);
15324 
15325   // Determine whether we require a function definition to exist, per
15326   // C++11 [temp.inst]p3:
15327   //   Unless a function template specialization has been explicitly
15328   //   instantiated or explicitly specialized, the function template
15329   //   specialization is implicitly instantiated when the specialization is
15330   //   referenced in a context that requires a function definition to exist.
15331   // C++20 [temp.inst]p7:
15332   //   The existence of a definition of a [...] function is considered to
15333   //   affect the semantics of the program if the [...] function is needed for
15334   //   constant evaluation by an expression
15335   // C++20 [basic.def.odr]p10:
15336   //   Every program shall contain exactly one definition of every non-inline
15337   //   function or variable that is odr-used in that program outside of a
15338   //   discarded statement
15339   // C++20 [special]p1:
15340   //   The implementation will implicitly define [defaulted special members]
15341   //   if they are odr-used or needed for constant evaluation.
15342   //
15343   // Note that we skip the implicit instantiation of templates that are only
15344   // used in unused default arguments or by recursive calls to themselves.
15345   // This is formally non-conforming, but seems reasonable in practice.
15346   bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15347                                              NeededForConstantEvaluation);
15348 
15349   // C++14 [temp.expl.spec]p6:
15350   //   If a template [...] is explicitly specialized then that specialization
15351   //   shall be declared before the first use of that specialization that would
15352   //   cause an implicit instantiation to take place, in every translation unit
15353   //   in which such a use occurs
15354   if (NeedDefinition &&
15355       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15356        Func->getMemberSpecializationInfo()))
15357     checkSpecializationVisibility(Loc, Func);
15358 
15359   // C++14 [except.spec]p17:
15360   //   An exception-specification is considered to be needed when:
15361   //   - the function is odr-used or, if it appears in an unevaluated operand,
15362   //     would be odr-used if the expression were potentially-evaluated;
15363   //
15364   // Note, we do this even if MightBeOdrUse is false. That indicates that the
15365   // function is a pure virtual function we're calling, and in that case the
15366   // function was selected by overload resolution and we need to resolve its
15367   // exception specification for a different reason.
15368   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15369   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15370     ResolveExceptionSpec(Loc, FPT);
15371 
15372   if (getLangOpts().CUDA)
15373     CheckCUDACall(Loc, Func);
15374 
15375   // If we need a definition, try to create one.
15376   if (NeedDefinition && !Func->getBody()) {
15377     runWithSufficientStackSpace(Loc, [&] {
15378       if (CXXConstructorDecl *Constructor =
15379               dyn_cast<CXXConstructorDecl>(Func)) {
15380         Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15381         if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15382           if (Constructor->isDefaultConstructor()) {
15383             if (Constructor->isTrivial() &&
15384                 !Constructor->hasAttr<DLLExportAttr>())
15385               return;
15386             DefineImplicitDefaultConstructor(Loc, Constructor);
15387           } else if (Constructor->isCopyConstructor()) {
15388             DefineImplicitCopyConstructor(Loc, Constructor);
15389           } else if (Constructor->isMoveConstructor()) {
15390             DefineImplicitMoveConstructor(Loc, Constructor);
15391           }
15392         } else if (Constructor->getInheritedConstructor()) {
15393           DefineInheritingConstructor(Loc, Constructor);
15394         }
15395       } else if (CXXDestructorDecl *Destructor =
15396                      dyn_cast<CXXDestructorDecl>(Func)) {
15397         Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15398         if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15399           if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15400             return;
15401           DefineImplicitDestructor(Loc, Destructor);
15402         }
15403         if (Destructor->isVirtual() && getLangOpts().AppleKext)
15404           MarkVTableUsed(Loc, Destructor->getParent());
15405       } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15406         if (MethodDecl->isOverloadedOperator() &&
15407             MethodDecl->getOverloadedOperator() == OO_Equal) {
15408           MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15409           if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15410             if (MethodDecl->isCopyAssignmentOperator())
15411               DefineImplicitCopyAssignment(Loc, MethodDecl);
15412             else if (MethodDecl->isMoveAssignmentOperator())
15413               DefineImplicitMoveAssignment(Loc, MethodDecl);
15414           }
15415         } else if (isa<CXXConversionDecl>(MethodDecl) &&
15416                    MethodDecl->getParent()->isLambda()) {
15417           CXXConversionDecl *Conversion =
15418               cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15419           if (Conversion->isLambdaToBlockPointerConversion())
15420             DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15421           else
15422             DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15423         } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15424           MarkVTableUsed(Loc, MethodDecl->getParent());
15425       }
15426 
15427       // Implicit instantiation of function templates and member functions of
15428       // class templates.
15429       if (Func->isImplicitlyInstantiable()) {
15430         TemplateSpecializationKind TSK =
15431             Func->getTemplateSpecializationKindForInstantiation();
15432         SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15433         bool FirstInstantiation = PointOfInstantiation.isInvalid();
15434         if (FirstInstantiation) {
15435           PointOfInstantiation = Loc;
15436           Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15437         } else if (TSK != TSK_ImplicitInstantiation) {
15438           // Use the point of use as the point of instantiation, instead of the
15439           // point of explicit instantiation (which we track as the actual point
15440           // of instantiation). This gives better backtraces in diagnostics.
15441           PointOfInstantiation = Loc;
15442         }
15443 
15444         if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15445             Func->isConstexpr()) {
15446           if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15447               cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15448               CodeSynthesisContexts.size())
15449             PendingLocalImplicitInstantiations.push_back(
15450                 std::make_pair(Func, PointOfInstantiation));
15451           else if (Func->isConstexpr())
15452             // Do not defer instantiations of constexpr functions, to avoid the
15453             // expression evaluator needing to call back into Sema if it sees a
15454             // call to such a function.
15455             InstantiateFunctionDefinition(PointOfInstantiation, Func);
15456           else {
15457             Func->setInstantiationIsPending(true);
15458             PendingInstantiations.push_back(
15459                 std::make_pair(Func, PointOfInstantiation));
15460             // Notify the consumer that a function was implicitly instantiated.
15461             Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15462           }
15463         }
15464       } else {
15465         // Walk redefinitions, as some of them may be instantiable.
15466         for (auto i : Func->redecls()) {
15467           if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15468             MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15469         }
15470       }
15471     });
15472   }
15473 
15474   // If this is the first "real" use, act on that.
15475   if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15476     // Keep track of used but undefined functions.
15477     if (!Func->isDefined()) {
15478       if (mightHaveNonExternalLinkage(Func))
15479         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15480       else if (Func->getMostRecentDecl()->isInlined() &&
15481                !LangOpts.GNUInline &&
15482                !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15483         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15484       else if (isExternalWithNoLinkageType(Func))
15485         UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15486     }
15487 
15488     // Some x86 Windows calling conventions mangle the size of the parameter
15489     // pack into the name. Computing the size of the parameters requires the
15490     // parameter types to be complete. Check that now.
15491     if (funcHasParameterSizeMangling(*this, Func))
15492       CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15493 
15494     Func->markUsed(Context);
15495   }
15496 
15497   if (LangOpts.OpenMP) {
15498     if (LangOpts.OpenMPIsDevice)
15499       checkOpenMPDeviceFunction(Loc, Func);
15500     else
15501       checkOpenMPHostFunction(Loc, Func);
15502   }
15503 }
15504 
15505 /// Directly mark a variable odr-used. Given a choice, prefer to use
15506 /// MarkVariableReferenced since it does additional checks and then
15507 /// calls MarkVarDeclODRUsed.
15508 /// If the variable must be captured:
15509 ///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15510 ///  - else capture it in the DeclContext that maps to the
15511 ///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15512 static void
15513 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15514                    const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15515   // Keep track of used but undefined variables.
15516   // FIXME: We shouldn't suppress this warning for static data members.
15517   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15518       (!Var->isExternallyVisible() || Var->isInline() ||
15519        SemaRef.isExternalWithNoLinkageType(Var)) &&
15520       !(Var->isStaticDataMember() && Var->hasInit())) {
15521     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15522     if (old.isInvalid())
15523       old = Loc;
15524   }
15525   QualType CaptureType, DeclRefType;
15526   if (SemaRef.LangOpts.OpenMP)
15527     SemaRef.tryCaptureOpenMPLambdas(Var);
15528   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15529     /*EllipsisLoc*/ SourceLocation(),
15530     /*BuildAndDiagnose*/ true,
15531     CaptureType, DeclRefType,
15532     FunctionScopeIndexToStopAt);
15533 
15534   Var->markUsed(SemaRef.Context);
15535 }
15536 
15537 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
15538                                              SourceLocation Loc,
15539                                              unsigned CapturingScopeIndex) {
15540   MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
15541 }
15542 
15543 static void
15544 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
15545                                    ValueDecl *var, DeclContext *DC) {
15546   DeclContext *VarDC = var->getDeclContext();
15547 
15548   //  If the parameter still belongs to the translation unit, then
15549   //  we're actually just using one parameter in the declaration of
15550   //  the next.
15551   if (isa<ParmVarDecl>(var) &&
15552       isa<TranslationUnitDecl>(VarDC))
15553     return;
15554 
15555   // For C code, don't diagnose about capture if we're not actually in code
15556   // right now; it's impossible to write a non-constant expression outside of
15557   // function context, so we'll get other (more useful) diagnostics later.
15558   //
15559   // For C++, things get a bit more nasty... it would be nice to suppress this
15560   // diagnostic for certain cases like using a local variable in an array bound
15561   // for a member of a local class, but the correct predicate is not obvious.
15562   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
15563     return;
15564 
15565   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
15566   unsigned ContextKind = 3; // unknown
15567   if (isa<CXXMethodDecl>(VarDC) &&
15568       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
15569     ContextKind = 2;
15570   } else if (isa<FunctionDecl>(VarDC)) {
15571     ContextKind = 0;
15572   } else if (isa<BlockDecl>(VarDC)) {
15573     ContextKind = 1;
15574   }
15575 
15576   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15577     << var << ValueKind << ContextKind << VarDC;
15578   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15579       << var;
15580 
15581   // FIXME: Add additional diagnostic info about class etc. which prevents
15582   // capture.
15583 }
15584 
15585 
15586 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15587                                       bool &SubCapturesAreNested,
15588                                       QualType &CaptureType,
15589                                       QualType &DeclRefType) {
15590    // Check whether we've already captured it.
15591   if (CSI->CaptureMap.count(Var)) {
15592     // If we found a capture, any subcaptures are nested.
15593     SubCapturesAreNested = true;
15594 
15595     // Retrieve the capture type for this variable.
15596     CaptureType = CSI->getCapture(Var).getCaptureType();
15597 
15598     // Compute the type of an expression that refers to this variable.
15599     DeclRefType = CaptureType.getNonReferenceType();
15600 
15601     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15602     // are mutable in the sense that user can change their value - they are
15603     // private instances of the captured declarations.
15604     const Capture &Cap = CSI->getCapture(Var);
15605     if (Cap.isCopyCapture() &&
15606         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15607         !(isa<CapturedRegionScopeInfo>(CSI) &&
15608           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15609       DeclRefType.addConst();
15610     return true;
15611   }
15612   return false;
15613 }
15614 
15615 // Only block literals, captured statements, and lambda expressions can
15616 // capture; other scopes don't work.
15617 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15618                                  SourceLocation Loc,
15619                                  const bool Diagnose, Sema &S) {
15620   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15621     return getLambdaAwareParentOfDeclContext(DC);
15622   else if (Var->hasLocalStorage()) {
15623     if (Diagnose)
15624        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15625   }
15626   return nullptr;
15627 }
15628 
15629 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15630 // certain types of variables (unnamed, variably modified types etc.)
15631 // so check for eligibility.
15632 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15633                                  SourceLocation Loc,
15634                                  const bool Diagnose, Sema &S) {
15635 
15636   bool IsBlock = isa<BlockScopeInfo>(CSI);
15637   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15638 
15639   // Lambdas are not allowed to capture unnamed variables
15640   // (e.g. anonymous unions).
15641   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15642   // assuming that's the intent.
15643   if (IsLambda && !Var->getDeclName()) {
15644     if (Diagnose) {
15645       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15646       S.Diag(Var->getLocation(), diag::note_declared_at);
15647     }
15648     return false;
15649   }
15650 
15651   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15652   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15653     if (Diagnose) {
15654       S.Diag(Loc, diag::err_ref_vm_type);
15655       S.Diag(Var->getLocation(), diag::note_previous_decl)
15656         << Var->getDeclName();
15657     }
15658     return false;
15659   }
15660   // Prohibit structs with flexible array members too.
15661   // We cannot capture what is in the tail end of the struct.
15662   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15663     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15664       if (Diagnose) {
15665         if (IsBlock)
15666           S.Diag(Loc, diag::err_ref_flexarray_type);
15667         else
15668           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15669             << Var->getDeclName();
15670         S.Diag(Var->getLocation(), diag::note_previous_decl)
15671           << Var->getDeclName();
15672       }
15673       return false;
15674     }
15675   }
15676   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15677   // Lambdas and captured statements are not allowed to capture __block
15678   // variables; they don't support the expected semantics.
15679   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15680     if (Diagnose) {
15681       S.Diag(Loc, diag::err_capture_block_variable)
15682         << Var->getDeclName() << !IsLambda;
15683       S.Diag(Var->getLocation(), diag::note_previous_decl)
15684         << Var->getDeclName();
15685     }
15686     return false;
15687   }
15688   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15689   if (S.getLangOpts().OpenCL && IsBlock &&
15690       Var->getType()->isBlockPointerType()) {
15691     if (Diagnose)
15692       S.Diag(Loc, diag::err_opencl_block_ref_block);
15693     return false;
15694   }
15695 
15696   return true;
15697 }
15698 
15699 // Returns true if the capture by block was successful.
15700 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15701                                  SourceLocation Loc,
15702                                  const bool BuildAndDiagnose,
15703                                  QualType &CaptureType,
15704                                  QualType &DeclRefType,
15705                                  const bool Nested,
15706                                  Sema &S, bool Invalid) {
15707   bool ByRef = false;
15708 
15709   // Blocks are not allowed to capture arrays, excepting OpenCL.
15710   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15711   // (decayed to pointers).
15712   if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15713     if (BuildAndDiagnose) {
15714       S.Diag(Loc, diag::err_ref_array_type);
15715       S.Diag(Var->getLocation(), diag::note_previous_decl)
15716       << Var->getDeclName();
15717       Invalid = true;
15718     } else {
15719       return false;
15720     }
15721   }
15722 
15723   // Forbid the block-capture of autoreleasing variables.
15724   if (!Invalid &&
15725       CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15726     if (BuildAndDiagnose) {
15727       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15728         << /*block*/ 0;
15729       S.Diag(Var->getLocation(), diag::note_previous_decl)
15730         << Var->getDeclName();
15731       Invalid = true;
15732     } else {
15733       return false;
15734     }
15735   }
15736 
15737   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15738   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15739     QualType PointeeTy = PT->getPointeeType();
15740 
15741     if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
15742         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15743         !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
15744       if (BuildAndDiagnose) {
15745         SourceLocation VarLoc = Var->getLocation();
15746         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15747         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15748       }
15749     }
15750   }
15751 
15752   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15753   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15754       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15755     // Block capture by reference does not change the capture or
15756     // declaration reference types.
15757     ByRef = true;
15758   } else {
15759     // Block capture by copy introduces 'const'.
15760     CaptureType = CaptureType.getNonReferenceType().withConst();
15761     DeclRefType = CaptureType;
15762   }
15763 
15764   // Actually capture the variable.
15765   if (BuildAndDiagnose)
15766     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
15767                     CaptureType, Invalid);
15768 
15769   return !Invalid;
15770 }
15771 
15772 
15773 /// Capture the given variable in the captured region.
15774 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15775                                     VarDecl *Var,
15776                                     SourceLocation Loc,
15777                                     const bool BuildAndDiagnose,
15778                                     QualType &CaptureType,
15779                                     QualType &DeclRefType,
15780                                     const bool RefersToCapturedVariable,
15781                                     Sema &S, bool Invalid) {
15782   // By default, capture variables by reference.
15783   bool ByRef = true;
15784   // Using an LValue reference type is consistent with Lambdas (see below).
15785   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15786     if (S.isOpenMPCapturedDecl(Var)) {
15787       bool HasConst = DeclRefType.isConstQualified();
15788       DeclRefType = DeclRefType.getUnqualifiedType();
15789       // Don't lose diagnostics about assignments to const.
15790       if (HasConst)
15791         DeclRefType.addConst();
15792     }
15793     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
15794                                     RSI->OpenMPCaptureLevel);
15795   }
15796 
15797   if (ByRef)
15798     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15799   else
15800     CaptureType = DeclRefType;
15801 
15802   // Actually capture the variable.
15803   if (BuildAndDiagnose)
15804     RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
15805                     Loc, SourceLocation(), CaptureType, Invalid);
15806 
15807   return !Invalid;
15808 }
15809 
15810 /// Capture the given variable in the lambda.
15811 static bool captureInLambda(LambdaScopeInfo *LSI,
15812                             VarDecl *Var,
15813                             SourceLocation Loc,
15814                             const bool BuildAndDiagnose,
15815                             QualType &CaptureType,
15816                             QualType &DeclRefType,
15817                             const bool RefersToCapturedVariable,
15818                             const Sema::TryCaptureKind Kind,
15819                             SourceLocation EllipsisLoc,
15820                             const bool IsTopScope,
15821                             Sema &S, bool Invalid) {
15822   // Determine whether we are capturing by reference or by value.
15823   bool ByRef = false;
15824   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15825     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15826   } else {
15827     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15828   }
15829 
15830   // Compute the type of the field that will capture this variable.
15831   if (ByRef) {
15832     // C++11 [expr.prim.lambda]p15:
15833     //   An entity is captured by reference if it is implicitly or
15834     //   explicitly captured but not captured by copy. It is
15835     //   unspecified whether additional unnamed non-static data
15836     //   members are declared in the closure type for entities
15837     //   captured by reference.
15838     //
15839     // FIXME: It is not clear whether we want to build an lvalue reference
15840     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15841     // to do the former, while EDG does the latter. Core issue 1249 will
15842     // clarify, but for now we follow GCC because it's a more permissive and
15843     // easily defensible position.
15844     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15845   } else {
15846     // C++11 [expr.prim.lambda]p14:
15847     //   For each entity captured by copy, an unnamed non-static
15848     //   data member is declared in the closure type. The
15849     //   declaration order of these members is unspecified. The type
15850     //   of such a data member is the type of the corresponding
15851     //   captured entity if the entity is not a reference to an
15852     //   object, or the referenced type otherwise. [Note: If the
15853     //   captured entity is a reference to a function, the
15854     //   corresponding data member is also a reference to a
15855     //   function. - end note ]
15856     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15857       if (!RefType->getPointeeType()->isFunctionType())
15858         CaptureType = RefType->getPointeeType();
15859     }
15860 
15861     // Forbid the lambda copy-capture of autoreleasing variables.
15862     if (!Invalid &&
15863         CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15864       if (BuildAndDiagnose) {
15865         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15866         S.Diag(Var->getLocation(), diag::note_previous_decl)
15867           << Var->getDeclName();
15868         Invalid = true;
15869       } else {
15870         return false;
15871       }
15872     }
15873 
15874     // Make sure that by-copy captures are of a complete and non-abstract type.
15875     if (!Invalid && BuildAndDiagnose) {
15876       if (!CaptureType->isDependentType() &&
15877           S.RequireCompleteType(Loc, CaptureType,
15878                                 diag::err_capture_of_incomplete_type,
15879                                 Var->getDeclName()))
15880         Invalid = true;
15881       else if (S.RequireNonAbstractType(Loc, CaptureType,
15882                                         diag::err_capture_of_abstract_type))
15883         Invalid = true;
15884     }
15885   }
15886 
15887   // Compute the type of a reference to this captured variable.
15888   if (ByRef)
15889     DeclRefType = CaptureType.getNonReferenceType();
15890   else {
15891     // C++ [expr.prim.lambda]p5:
15892     //   The closure type for a lambda-expression has a public inline
15893     //   function call operator [...]. This function call operator is
15894     //   declared const (9.3.1) if and only if the lambda-expression's
15895     //   parameter-declaration-clause is not followed by mutable.
15896     DeclRefType = CaptureType.getNonReferenceType();
15897     if (!LSI->Mutable && !CaptureType->isReferenceType())
15898       DeclRefType.addConst();
15899   }
15900 
15901   // Add the capture.
15902   if (BuildAndDiagnose)
15903     LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
15904                     Loc, EllipsisLoc, CaptureType, Invalid);
15905 
15906   return !Invalid;
15907 }
15908 
15909 bool Sema::tryCaptureVariable(
15910     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15911     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15912     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15913   // An init-capture is notionally from the context surrounding its
15914   // declaration, but its parent DC is the lambda class.
15915   DeclContext *VarDC = Var->getDeclContext();
15916   if (Var->isInitCapture())
15917     VarDC = VarDC->getParent();
15918 
15919   DeclContext *DC = CurContext;
15920   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15921       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15922   // We need to sync up the Declaration Context with the
15923   // FunctionScopeIndexToStopAt
15924   if (FunctionScopeIndexToStopAt) {
15925     unsigned FSIndex = FunctionScopes.size() - 1;
15926     while (FSIndex != MaxFunctionScopesIndex) {
15927       DC = getLambdaAwareParentOfDeclContext(DC);
15928       --FSIndex;
15929     }
15930   }
15931 
15932 
15933   // If the variable is declared in the current context, there is no need to
15934   // capture it.
15935   if (VarDC == DC) return true;
15936 
15937   // Capture global variables if it is required to use private copy of this
15938   // variable.
15939   bool IsGlobal = !Var->hasLocalStorage();
15940   if (IsGlobal &&
15941       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
15942                                                 MaxFunctionScopesIndex)))
15943     return true;
15944   Var = Var->getCanonicalDecl();
15945 
15946   // Walk up the stack to determine whether we can capture the variable,
15947   // performing the "simple" checks that don't depend on type. We stop when
15948   // we've either hit the declared scope of the variable or find an existing
15949   // capture of that variable.  We start from the innermost capturing-entity
15950   // (the DC) and ensure that all intervening capturing-entities
15951   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15952   // declcontext can either capture the variable or have already captured
15953   // the variable.
15954   CaptureType = Var->getType();
15955   DeclRefType = CaptureType.getNonReferenceType();
15956   bool Nested = false;
15957   bool Explicit = (Kind != TryCapture_Implicit);
15958   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15959   do {
15960     // Only block literals, captured statements, and lambda expressions can
15961     // capture; other scopes don't work.
15962     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15963                                                               ExprLoc,
15964                                                               BuildAndDiagnose,
15965                                                               *this);
15966     // We need to check for the parent *first* because, if we *have*
15967     // private-captured a global variable, we need to recursively capture it in
15968     // intermediate blocks, lambdas, etc.
15969     if (!ParentDC) {
15970       if (IsGlobal) {
15971         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15972         break;
15973       }
15974       return true;
15975     }
15976 
15977     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15978     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15979 
15980 
15981     // Check whether we've already captured it.
15982     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15983                                              DeclRefType)) {
15984       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15985       break;
15986     }
15987     // If we are instantiating a generic lambda call operator body,
15988     // we do not want to capture new variables.  What was captured
15989     // during either a lambdas transformation or initial parsing
15990     // should be used.
15991     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15992       if (BuildAndDiagnose) {
15993         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15994         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15995           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15996           Diag(Var->getLocation(), diag::note_previous_decl)
15997              << Var->getDeclName();
15998           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15999         } else
16000           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16001       }
16002       return true;
16003     }
16004 
16005     // Try to capture variable-length arrays types.
16006     if (Var->getType()->isVariablyModifiedType()) {
16007       // We're going to walk down into the type and look for VLA
16008       // expressions.
16009       QualType QTy = Var->getType();
16010       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16011         QTy = PVD->getOriginalType();
16012       captureVariablyModifiedType(Context, QTy, CSI);
16013     }
16014 
16015     if (getLangOpts().OpenMP) {
16016       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16017         // OpenMP private variables should not be captured in outer scope, so
16018         // just break here. Similarly, global variables that are captured in a
16019         // target region should not be captured outside the scope of the region.
16020         if (RSI->CapRegionKind == CR_OpenMP) {
16021           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16022           auto IsTargetCap = !IsOpenMPPrivateDecl &&
16023                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
16024           // When we detect target captures we are looking from inside the
16025           // target region, therefore we need to propagate the capture from the
16026           // enclosing region. Therefore, the capture is not initially nested.
16027           if (IsTargetCap)
16028             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16029 
16030           if (IsTargetCap || IsOpenMPPrivateDecl) {
16031             Nested = !IsTargetCap;
16032             DeclRefType = DeclRefType.getUnqualifiedType();
16033             CaptureType = Context.getLValueReferenceType(DeclRefType);
16034             break;
16035           }
16036         }
16037       }
16038     }
16039     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16040       // No capture-default, and this is not an explicit capture
16041       // so cannot capture this variable.
16042       if (BuildAndDiagnose) {
16043         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16044         Diag(Var->getLocation(), diag::note_previous_decl)
16045           << Var->getDeclName();
16046         if (cast<LambdaScopeInfo>(CSI)->Lambda)
16047           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16048                diag::note_lambda_decl);
16049         // FIXME: If we error out because an outer lambda can not implicitly
16050         // capture a variable that an inner lambda explicitly captures, we
16051         // should have the inner lambda do the explicit capture - because
16052         // it makes for cleaner diagnostics later.  This would purely be done
16053         // so that the diagnostic does not misleadingly claim that a variable
16054         // can not be captured by a lambda implicitly even though it is captured
16055         // explicitly.  Suggestion:
16056         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16057         //    at the function head
16058         //  - cache the StartingDeclContext - this must be a lambda
16059         //  - captureInLambda in the innermost lambda the variable.
16060       }
16061       return true;
16062     }
16063 
16064     FunctionScopesIndex--;
16065     DC = ParentDC;
16066     Explicit = false;
16067   } while (!VarDC->Equals(DC));
16068 
16069   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16070   // computing the type of the capture at each step, checking type-specific
16071   // requirements, and adding captures if requested.
16072   // If the variable had already been captured previously, we start capturing
16073   // at the lambda nested within that one.
16074   bool Invalid = false;
16075   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16076        ++I) {
16077     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16078 
16079     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16080     // certain types of variables (unnamed, variably modified types etc.)
16081     // so check for eligibility.
16082     if (!Invalid)
16083       Invalid =
16084           !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16085 
16086     // After encountering an error, if we're actually supposed to capture, keep
16087     // capturing in nested contexts to suppress any follow-on diagnostics.
16088     if (Invalid && !BuildAndDiagnose)
16089       return true;
16090 
16091     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16092       Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16093                                DeclRefType, Nested, *this, Invalid);
16094       Nested = true;
16095     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16096       Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16097                                          CaptureType, DeclRefType, Nested,
16098                                          *this, Invalid);
16099       Nested = true;
16100     } else {
16101       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16102       Invalid =
16103           !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16104                            DeclRefType, Nested, Kind, EllipsisLoc,
16105                            /*IsTopScope*/ I == N - 1, *this, Invalid);
16106       Nested = true;
16107     }
16108 
16109     if (Invalid && !BuildAndDiagnose)
16110       return true;
16111   }
16112   return Invalid;
16113 }
16114 
16115 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16116                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16117   QualType CaptureType;
16118   QualType DeclRefType;
16119   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16120                             /*BuildAndDiagnose=*/true, CaptureType,
16121                             DeclRefType, nullptr);
16122 }
16123 
16124 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16125   QualType CaptureType;
16126   QualType DeclRefType;
16127   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16128                              /*BuildAndDiagnose=*/false, CaptureType,
16129                              DeclRefType, nullptr);
16130 }
16131 
16132 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16133   QualType CaptureType;
16134   QualType DeclRefType;
16135 
16136   // Determine whether we can capture this variable.
16137   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16138                          /*BuildAndDiagnose=*/false, CaptureType,
16139                          DeclRefType, nullptr))
16140     return QualType();
16141 
16142   return DeclRefType;
16143 }
16144 
16145 namespace {
16146 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16147 // The produced TemplateArgumentListInfo* points to data stored within this
16148 // object, so should only be used in contexts where the pointer will not be
16149 // used after the CopiedTemplateArgs object is destroyed.
16150 class CopiedTemplateArgs {
16151   bool HasArgs;
16152   TemplateArgumentListInfo TemplateArgStorage;
16153 public:
16154   template<typename RefExpr>
16155   CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16156     if (HasArgs)
16157       E->copyTemplateArgumentsInto(TemplateArgStorage);
16158   }
16159   operator TemplateArgumentListInfo*()
16160 #ifdef __has_cpp_attribute
16161 #if __has_cpp_attribute(clang::lifetimebound)
16162   [[clang::lifetimebound]]
16163 #endif
16164 #endif
16165   {
16166     return HasArgs ? &TemplateArgStorage : nullptr;
16167   }
16168 };
16169 }
16170 
16171 /// Walk the set of potential results of an expression and mark them all as
16172 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16173 ///
16174 /// \return A new expression if we found any potential results, ExprEmpty() if
16175 ///         not, and ExprError() if we diagnosed an error.
16176 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16177                                                       NonOdrUseReason NOUR) {
16178   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16179   // an object that satisfies the requirements for appearing in a
16180   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16181   // is immediately applied."  This function handles the lvalue-to-rvalue
16182   // conversion part.
16183   //
16184   // If we encounter a node that claims to be an odr-use but shouldn't be, we
16185   // transform it into the relevant kind of non-odr-use node and rebuild the
16186   // tree of nodes leading to it.
16187   //
16188   // This is a mini-TreeTransform that only transforms a restricted subset of
16189   // nodes (and only certain operands of them).
16190 
16191   // Rebuild a subexpression.
16192   auto Rebuild = [&](Expr *Sub) {
16193     return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16194   };
16195 
16196   // Check whether a potential result satisfies the requirements of NOUR.
16197   auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16198     // Any entity other than a VarDecl is always odr-used whenever it's named
16199     // in a potentially-evaluated expression.
16200     auto *VD = dyn_cast<VarDecl>(D);
16201     if (!VD)
16202       return true;
16203 
16204     // C++2a [basic.def.odr]p4:
16205     //   A variable x whose name appears as a potentially-evalauted expression
16206     //   e is odr-used by e unless
16207     //   -- x is a reference that is usable in constant expressions, or
16208     //   -- x is a variable of non-reference type that is usable in constant
16209     //      expressions and has no mutable subobjects, and e is an element of
16210     //      the set of potential results of an expression of
16211     //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16212     //      conversion is applied, or
16213     //   -- x is a variable of non-reference type, and e is an element of the
16214     //      set of potential results of a discarded-value expression to which
16215     //      the lvalue-to-rvalue conversion is not applied
16216     //
16217     // We check the first bullet and the "potentially-evaluated" condition in
16218     // BuildDeclRefExpr. We check the type requirements in the second bullet
16219     // in CheckLValueToRValueConversionOperand below.
16220     switch (NOUR) {
16221     case NOUR_None:
16222     case NOUR_Unevaluated:
16223       llvm_unreachable("unexpected non-odr-use-reason");
16224 
16225     case NOUR_Constant:
16226       // Constant references were handled when they were built.
16227       if (VD->getType()->isReferenceType())
16228         return true;
16229       if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16230         if (RD->hasMutableFields())
16231           return true;
16232       if (!VD->isUsableInConstantExpressions(S.Context))
16233         return true;
16234       break;
16235 
16236     case NOUR_Discarded:
16237       if (VD->getType()->isReferenceType())
16238         return true;
16239       break;
16240     }
16241     return false;
16242   };
16243 
16244   // Mark that this expression does not constitute an odr-use.
16245   auto MarkNotOdrUsed = [&] {
16246     S.MaybeODRUseExprs.erase(E);
16247     if (LambdaScopeInfo *LSI = S.getCurLambda())
16248       LSI->markVariableExprAsNonODRUsed(E);
16249   };
16250 
16251   // C++2a [basic.def.odr]p2:
16252   //   The set of potential results of an expression e is defined as follows:
16253   switch (E->getStmtClass()) {
16254   //   -- If e is an id-expression, ...
16255   case Expr::DeclRefExprClass: {
16256     auto *DRE = cast<DeclRefExpr>(E);
16257     if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16258       break;
16259 
16260     // Rebuild as a non-odr-use DeclRefExpr.
16261     MarkNotOdrUsed();
16262     return DeclRefExpr::Create(
16263         S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16264         DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16265         DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16266         DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16267   }
16268 
16269   case Expr::FunctionParmPackExprClass: {
16270     auto *FPPE = cast<FunctionParmPackExpr>(E);
16271     // If any of the declarations in the pack is odr-used, then the expression
16272     // as a whole constitutes an odr-use.
16273     for (VarDecl *D : *FPPE)
16274       if (IsPotentialResultOdrUsed(D))
16275         return ExprEmpty();
16276 
16277     // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16278     // nothing cares about whether we marked this as an odr-use, but it might
16279     // be useful for non-compiler tools.
16280     MarkNotOdrUsed();
16281     break;
16282   }
16283 
16284   //   -- If e is a subscripting operation with an array operand...
16285   case Expr::ArraySubscriptExprClass: {
16286     auto *ASE = cast<ArraySubscriptExpr>(E);
16287     Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16288     if (!OldBase->getType()->isArrayType())
16289       break;
16290     ExprResult Base = Rebuild(OldBase);
16291     if (!Base.isUsable())
16292       return Base;
16293     Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16294     Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16295     SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16296     return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16297                                      ASE->getRBracketLoc());
16298   }
16299 
16300   case Expr::MemberExprClass: {
16301     auto *ME = cast<MemberExpr>(E);
16302     // -- If e is a class member access expression [...] naming a non-static
16303     //    data member...
16304     if (isa<FieldDecl>(ME->getMemberDecl())) {
16305       ExprResult Base = Rebuild(ME->getBase());
16306       if (!Base.isUsable())
16307         return Base;
16308       return MemberExpr::Create(
16309           S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16310           ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16311           ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16312           CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16313           ME->getObjectKind(), ME->isNonOdrUse());
16314     }
16315 
16316     if (ME->getMemberDecl()->isCXXInstanceMember())
16317       break;
16318 
16319     // -- If e is a class member access expression naming a static data member,
16320     //    ...
16321     if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16322       break;
16323 
16324     // Rebuild as a non-odr-use MemberExpr.
16325     MarkNotOdrUsed();
16326     return MemberExpr::Create(
16327         S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16328         ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16329         ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16330         ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16331     return ExprEmpty();
16332   }
16333 
16334   case Expr::BinaryOperatorClass: {
16335     auto *BO = cast<BinaryOperator>(E);
16336     Expr *LHS = BO->getLHS();
16337     Expr *RHS = BO->getRHS();
16338     // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16339     if (BO->getOpcode() == BO_PtrMemD) {
16340       ExprResult Sub = Rebuild(LHS);
16341       if (!Sub.isUsable())
16342         return Sub;
16343       LHS = Sub.get();
16344     //   -- If e is a comma expression, ...
16345     } else if (BO->getOpcode() == BO_Comma) {
16346       ExprResult Sub = Rebuild(RHS);
16347       if (!Sub.isUsable())
16348         return Sub;
16349       RHS = Sub.get();
16350     } else {
16351       break;
16352     }
16353     return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16354                         LHS, RHS);
16355   }
16356 
16357   //   -- If e has the form (e1)...
16358   case Expr::ParenExprClass: {
16359     auto *PE = cast<ParenExpr>(E);
16360     ExprResult Sub = Rebuild(PE->getSubExpr());
16361     if (!Sub.isUsable())
16362       return Sub;
16363     return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16364   }
16365 
16366   //   -- If e is a glvalue conditional expression, ...
16367   // We don't apply this to a binary conditional operator. FIXME: Should we?
16368   case Expr::ConditionalOperatorClass: {
16369     auto *CO = cast<ConditionalOperator>(E);
16370     ExprResult LHS = Rebuild(CO->getLHS());
16371     if (LHS.isInvalid())
16372       return ExprError();
16373     ExprResult RHS = Rebuild(CO->getRHS());
16374     if (RHS.isInvalid())
16375       return ExprError();
16376     if (!LHS.isUsable() && !RHS.isUsable())
16377       return ExprEmpty();
16378     if (!LHS.isUsable())
16379       LHS = CO->getLHS();
16380     if (!RHS.isUsable())
16381       RHS = CO->getRHS();
16382     return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16383                                 CO->getCond(), LHS.get(), RHS.get());
16384   }
16385 
16386   // [Clang extension]
16387   //   -- If e has the form __extension__ e1...
16388   case Expr::UnaryOperatorClass: {
16389     auto *UO = cast<UnaryOperator>(E);
16390     if (UO->getOpcode() != UO_Extension)
16391       break;
16392     ExprResult Sub = Rebuild(UO->getSubExpr());
16393     if (!Sub.isUsable())
16394       return Sub;
16395     return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16396                           Sub.get());
16397   }
16398 
16399   // [Clang extension]
16400   //   -- If e has the form _Generic(...), the set of potential results is the
16401   //      union of the sets of potential results of the associated expressions.
16402   case Expr::GenericSelectionExprClass: {
16403     auto *GSE = cast<GenericSelectionExpr>(E);
16404 
16405     SmallVector<Expr *, 4> AssocExprs;
16406     bool AnyChanged = false;
16407     for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16408       ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16409       if (AssocExpr.isInvalid())
16410         return ExprError();
16411       if (AssocExpr.isUsable()) {
16412         AssocExprs.push_back(AssocExpr.get());
16413         AnyChanged = true;
16414       } else {
16415         AssocExprs.push_back(OrigAssocExpr);
16416       }
16417     }
16418 
16419     return AnyChanged ? S.CreateGenericSelectionExpr(
16420                             GSE->getGenericLoc(), GSE->getDefaultLoc(),
16421                             GSE->getRParenLoc(), GSE->getControllingExpr(),
16422                             GSE->getAssocTypeSourceInfos(), AssocExprs)
16423                       : ExprEmpty();
16424   }
16425 
16426   // [Clang extension]
16427   //   -- If e has the form __builtin_choose_expr(...), the set of potential
16428   //      results is the union of the sets of potential results of the
16429   //      second and third subexpressions.
16430   case Expr::ChooseExprClass: {
16431     auto *CE = cast<ChooseExpr>(E);
16432 
16433     ExprResult LHS = Rebuild(CE->getLHS());
16434     if (LHS.isInvalid())
16435       return ExprError();
16436 
16437     ExprResult RHS = Rebuild(CE->getLHS());
16438     if (RHS.isInvalid())
16439       return ExprError();
16440 
16441     if (!LHS.get() && !RHS.get())
16442       return ExprEmpty();
16443     if (!LHS.isUsable())
16444       LHS = CE->getLHS();
16445     if (!RHS.isUsable())
16446       RHS = CE->getRHS();
16447 
16448     return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16449                              RHS.get(), CE->getRParenLoc());
16450   }
16451 
16452   // Step through non-syntactic nodes.
16453   case Expr::ConstantExprClass: {
16454     auto *CE = cast<ConstantExpr>(E);
16455     ExprResult Sub = Rebuild(CE->getSubExpr());
16456     if (!Sub.isUsable())
16457       return Sub;
16458     return ConstantExpr::Create(S.Context, Sub.get());
16459   }
16460 
16461   // We could mostly rely on the recursive rebuilding to rebuild implicit
16462   // casts, but not at the top level, so rebuild them here.
16463   case Expr::ImplicitCastExprClass: {
16464     auto *ICE = cast<ImplicitCastExpr>(E);
16465     // Only step through the narrow set of cast kinds we expect to encounter.
16466     // Anything else suggests we've left the region in which potential results
16467     // can be found.
16468     switch (ICE->getCastKind()) {
16469     case CK_NoOp:
16470     case CK_DerivedToBase:
16471     case CK_UncheckedDerivedToBase: {
16472       ExprResult Sub = Rebuild(ICE->getSubExpr());
16473       if (!Sub.isUsable())
16474         return Sub;
16475       CXXCastPath Path(ICE->path());
16476       return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16477                                  ICE->getValueKind(), &Path);
16478     }
16479 
16480     default:
16481       break;
16482     }
16483     break;
16484   }
16485 
16486   default:
16487     break;
16488   }
16489 
16490   // Can't traverse through this node. Nothing to do.
16491   return ExprEmpty();
16492 }
16493 
16494 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16495   // Check whether the operand is or contains an object of non-trivial C union
16496   // type.
16497   if (E->getType().isVolatileQualified() &&
16498       (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16499        E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16500     checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16501                           Sema::NTCUC_LValueToRValueVolatile,
16502                           NTCUK_Destruct|NTCUK_Copy);
16503 
16504   // C++2a [basic.def.odr]p4:
16505   //   [...] an expression of non-volatile-qualified non-class type to which
16506   //   the lvalue-to-rvalue conversion is applied [...]
16507   if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16508     return E;
16509 
16510   ExprResult Result =
16511       rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16512   if (Result.isInvalid())
16513     return ExprError();
16514   return Result.get() ? Result : E;
16515 }
16516 
16517 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
16518   Res = CorrectDelayedTyposInExpr(Res);
16519 
16520   if (!Res.isUsable())
16521     return Res;
16522 
16523   // If a constant-expression is a reference to a variable where we delay
16524   // deciding whether it is an odr-use, just assume we will apply the
16525   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
16526   // (a non-type template argument), we have special handling anyway.
16527   return CheckLValueToRValueConversionOperand(Res.get());
16528 }
16529 
16530 void Sema::CleanupVarDeclMarking() {
16531   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
16532   // call.
16533   MaybeODRUseExprSet LocalMaybeODRUseExprs;
16534   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
16535 
16536   for (Expr *E : LocalMaybeODRUseExprs) {
16537     if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
16538       MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
16539                          DRE->getLocation(), *this);
16540     } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
16541       MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
16542                          *this);
16543     } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
16544       for (VarDecl *VD : *FP)
16545         MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
16546     } else {
16547       llvm_unreachable("Unexpected expression");
16548     }
16549   }
16550 
16551   assert(MaybeODRUseExprs.empty() &&
16552          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
16553 }
16554 
16555 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
16556                                     VarDecl *Var, Expr *E) {
16557   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
16558           isa<FunctionParmPackExpr>(E)) &&
16559          "Invalid Expr argument to DoMarkVarDeclReferenced");
16560   Var->setReferenced();
16561 
16562   if (Var->isInvalidDecl())
16563     return;
16564 
16565   auto *MSI = Var->getMemberSpecializationInfo();
16566   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
16567                                        : Var->getTemplateSpecializationKind();
16568 
16569   OdrUseContext OdrUse = isOdrUseContext(SemaRef);
16570   bool UsableInConstantExpr =
16571       Var->mightBeUsableInConstantExpressions(SemaRef.Context);
16572 
16573   // C++20 [expr.const]p12:
16574   //   A variable [...] is needed for constant evaluation if it is [...] a
16575   //   variable whose name appears as a potentially constant evaluated
16576   //   expression that is either a contexpr variable or is of non-volatile
16577   //   const-qualified integral type or of reference type
16578   bool NeededForConstantEvaluation =
16579       isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
16580 
16581   bool NeedDefinition =
16582       OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
16583 
16584   VarTemplateSpecializationDecl *VarSpec =
16585       dyn_cast<VarTemplateSpecializationDecl>(Var);
16586   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
16587          "Can't instantiate a partial template specialization.");
16588 
16589   // If this might be a member specialization of a static data member, check
16590   // the specialization is visible. We already did the checks for variable
16591   // template specializations when we created them.
16592   if (NeedDefinition && TSK != TSK_Undeclared &&
16593       !isa<VarTemplateSpecializationDecl>(Var))
16594     SemaRef.checkSpecializationVisibility(Loc, Var);
16595 
16596   // Perform implicit instantiation of static data members, static data member
16597   // templates of class templates, and variable template specializations. Delay
16598   // instantiations of variable templates, except for those that could be used
16599   // in a constant expression.
16600   if (NeedDefinition && isTemplateInstantiation(TSK)) {
16601     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
16602     // instantiation declaration if a variable is usable in a constant
16603     // expression (among other cases).
16604     bool TryInstantiating =
16605         TSK == TSK_ImplicitInstantiation ||
16606         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
16607 
16608     if (TryInstantiating) {
16609       SourceLocation PointOfInstantiation =
16610           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
16611       bool FirstInstantiation = PointOfInstantiation.isInvalid();
16612       if (FirstInstantiation) {
16613         PointOfInstantiation = Loc;
16614         if (MSI)
16615           MSI->setPointOfInstantiation(PointOfInstantiation);
16616         else
16617           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16618       }
16619 
16620       bool InstantiationDependent = false;
16621       bool IsNonDependent =
16622           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
16623                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
16624                   : true;
16625 
16626       // Do not instantiate specializations that are still type-dependent.
16627       if (IsNonDependent) {
16628         if (UsableInConstantExpr) {
16629           // Do not defer instantiations of variables that could be used in a
16630           // constant expression.
16631           SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
16632             SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
16633           });
16634         } else if (FirstInstantiation ||
16635                    isa<VarTemplateSpecializationDecl>(Var)) {
16636           // FIXME: For a specialization of a variable template, we don't
16637           // distinguish between "declaration and type implicitly instantiated"
16638           // and "implicit instantiation of definition requested", so we have
16639           // no direct way to avoid enqueueing the pending instantiation
16640           // multiple times.
16641           SemaRef.PendingInstantiations
16642               .push_back(std::make_pair(Var, PointOfInstantiation));
16643         }
16644       }
16645     }
16646   }
16647 
16648   // C++2a [basic.def.odr]p4:
16649   //   A variable x whose name appears as a potentially-evaluated expression e
16650   //   is odr-used by e unless
16651   //   -- x is a reference that is usable in constant expressions
16652   //   -- x is a variable of non-reference type that is usable in constant
16653   //      expressions and has no mutable subobjects [FIXME], and e is an
16654   //      element of the set of potential results of an expression of
16655   //      non-volatile-qualified non-class type to which the lvalue-to-rvalue
16656   //      conversion is applied
16657   //   -- x is a variable of non-reference type, and e is an element of the set
16658   //      of potential results of a discarded-value expression to which the
16659   //      lvalue-to-rvalue conversion is not applied [FIXME]
16660   //
16661   // We check the first part of the second bullet here, and
16662   // Sema::CheckLValueToRValueConversionOperand deals with the second part.
16663   // FIXME: To get the third bullet right, we need to delay this even for
16664   // variables that are not usable in constant expressions.
16665 
16666   // If we already know this isn't an odr-use, there's nothing more to do.
16667   if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
16668     if (DRE->isNonOdrUse())
16669       return;
16670   if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
16671     if (ME->isNonOdrUse())
16672       return;
16673 
16674   switch (OdrUse) {
16675   case OdrUseContext::None:
16676     assert((!E || isa<FunctionParmPackExpr>(E)) &&
16677            "missing non-odr-use marking for unevaluated decl ref");
16678     break;
16679 
16680   case OdrUseContext::FormallyOdrUsed:
16681     // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
16682     // behavior.
16683     break;
16684 
16685   case OdrUseContext::Used:
16686     // If we might later find that this expression isn't actually an odr-use,
16687     // delay the marking.
16688     if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
16689       SemaRef.MaybeODRUseExprs.insert(E);
16690     else
16691       MarkVarDeclODRUsed(Var, Loc, SemaRef);
16692     break;
16693 
16694   case OdrUseContext::Dependent:
16695     // If this is a dependent context, we don't need to mark variables as
16696     // odr-used, but we may still need to track them for lambda capture.
16697     // FIXME: Do we also need to do this inside dependent typeid expressions
16698     // (which are modeled as unevaluated at this point)?
16699     const bool RefersToEnclosingScope =
16700         (SemaRef.CurContext != Var->getDeclContext() &&
16701          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
16702     if (RefersToEnclosingScope) {
16703       LambdaScopeInfo *const LSI =
16704           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
16705       if (LSI && (!LSI->CallOperator ||
16706                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
16707         // If a variable could potentially be odr-used, defer marking it so
16708         // until we finish analyzing the full expression for any
16709         // lvalue-to-rvalue
16710         // or discarded value conversions that would obviate odr-use.
16711         // Add it to the list of potential captures that will be analyzed
16712         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
16713         // unless the variable is a reference that was initialized by a constant
16714         // expression (this will never need to be captured or odr-used).
16715         //
16716         // FIXME: We can simplify this a lot after implementing P0588R1.
16717         assert(E && "Capture variable should be used in an expression.");
16718         if (!Var->getType()->isReferenceType() ||
16719             !Var->isUsableInConstantExpressions(SemaRef.Context))
16720           LSI->addPotentialCapture(E->IgnoreParens());
16721       }
16722     }
16723     break;
16724   }
16725 }
16726 
16727 /// Mark a variable referenced, and check whether it is odr-used
16728 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
16729 /// used directly for normal expressions referring to VarDecl.
16730 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
16731   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
16732 }
16733 
16734 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
16735                                Decl *D, Expr *E, bool MightBeOdrUse) {
16736   if (SemaRef.isInOpenMPDeclareTargetContext())
16737     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
16738 
16739   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
16740     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
16741     return;
16742   }
16743 
16744   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
16745 
16746   // If this is a call to a method via a cast, also mark the method in the
16747   // derived class used in case codegen can devirtualize the call.
16748   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
16749   if (!ME)
16750     return;
16751   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
16752   if (!MD)
16753     return;
16754   // Only attempt to devirtualize if this is truly a virtual call.
16755   bool IsVirtualCall = MD->isVirtual() &&
16756                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
16757   if (!IsVirtualCall)
16758     return;
16759 
16760   // If it's possible to devirtualize the call, mark the called function
16761   // referenced.
16762   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
16763       ME->getBase(), SemaRef.getLangOpts().AppleKext);
16764   if (DM)
16765     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
16766 }
16767 
16768 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
16769 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
16770   // TODO: update this with DR# once a defect report is filed.
16771   // C++11 defect. The address of a pure member should not be an ODR use, even
16772   // if it's a qualified reference.
16773   bool OdrUse = true;
16774   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
16775     if (Method->isVirtual() &&
16776         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
16777       OdrUse = false;
16778   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
16779 }
16780 
16781 /// Perform reference-marking and odr-use handling for a MemberExpr.
16782 void Sema::MarkMemberReferenced(MemberExpr *E) {
16783   // C++11 [basic.def.odr]p2:
16784   //   A non-overloaded function whose name appears as a potentially-evaluated
16785   //   expression or a member of a set of candidate functions, if selected by
16786   //   overload resolution when referred to from a potentially-evaluated
16787   //   expression, is odr-used, unless it is a pure virtual function and its
16788   //   name is not explicitly qualified.
16789   bool MightBeOdrUse = true;
16790   if (E->performsVirtualDispatch(getLangOpts())) {
16791     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
16792       if (Method->isPure())
16793         MightBeOdrUse = false;
16794   }
16795   SourceLocation Loc =
16796       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
16797   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
16798 }
16799 
16800 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
16801 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
16802   for (VarDecl *VD : *E)
16803     MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
16804 }
16805 
16806 /// Perform marking for a reference to an arbitrary declaration.  It
16807 /// marks the declaration referenced, and performs odr-use checking for
16808 /// functions and variables. This method should not be used when building a
16809 /// normal expression which refers to a variable.
16810 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
16811                                  bool MightBeOdrUse) {
16812   if (MightBeOdrUse) {
16813     if (auto *VD = dyn_cast<VarDecl>(D)) {
16814       MarkVariableReferenced(Loc, VD);
16815       return;
16816     }
16817   }
16818   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
16819     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
16820     return;
16821   }
16822   D->setReferenced();
16823 }
16824 
16825 namespace {
16826   // Mark all of the declarations used by a type as referenced.
16827   // FIXME: Not fully implemented yet! We need to have a better understanding
16828   // of when we're entering a context we should not recurse into.
16829   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
16830   // TreeTransforms rebuilding the type in a new context. Rather than
16831   // duplicating the TreeTransform logic, we should consider reusing it here.
16832   // Currently that causes problems when rebuilding LambdaExprs.
16833   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
16834     Sema &S;
16835     SourceLocation Loc;
16836 
16837   public:
16838     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16839 
16840     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16841 
16842     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16843   };
16844 }
16845 
16846 bool MarkReferencedDecls::TraverseTemplateArgument(
16847     const TemplateArgument &Arg) {
16848   {
16849     // A non-type template argument is a constant-evaluated context.
16850     EnterExpressionEvaluationContext Evaluated(
16851         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16852     if (Arg.getKind() == TemplateArgument::Declaration) {
16853       if (Decl *D = Arg.getAsDecl())
16854         S.MarkAnyDeclReferenced(Loc, D, true);
16855     } else if (Arg.getKind() == TemplateArgument::Expression) {
16856       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16857     }
16858   }
16859 
16860   return Inherited::TraverseTemplateArgument(Arg);
16861 }
16862 
16863 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16864   MarkReferencedDecls Marker(*this, Loc);
16865   Marker.TraverseType(T);
16866 }
16867 
16868 namespace {
16869   /// Helper class that marks all of the declarations referenced by
16870   /// potentially-evaluated subexpressions as "referenced".
16871   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16872     Sema &S;
16873     bool SkipLocalVariables;
16874 
16875   public:
16876     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16877 
16878     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16879       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16880 
16881     void VisitDeclRefExpr(DeclRefExpr *E) {
16882       // If we were asked not to visit local variables, don't.
16883       if (SkipLocalVariables) {
16884         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16885           if (VD->hasLocalStorage())
16886             return;
16887       }
16888 
16889       S.MarkDeclRefReferenced(E);
16890     }
16891 
16892     void VisitMemberExpr(MemberExpr *E) {
16893       S.MarkMemberReferenced(E);
16894       Inherited::VisitMemberExpr(E);
16895     }
16896 
16897     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16898       S.MarkFunctionReferenced(
16899           E->getBeginLoc(),
16900           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16901       Visit(E->getSubExpr());
16902     }
16903 
16904     void VisitCXXNewExpr(CXXNewExpr *E) {
16905       if (E->getOperatorNew())
16906         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16907       if (E->getOperatorDelete())
16908         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16909       Inherited::VisitCXXNewExpr(E);
16910     }
16911 
16912     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16913       if (E->getOperatorDelete())
16914         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16915       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16916       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16917         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16918         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16919       }
16920 
16921       Inherited::VisitCXXDeleteExpr(E);
16922     }
16923 
16924     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16925       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16926       Inherited::VisitCXXConstructExpr(E);
16927     }
16928 
16929     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16930       Visit(E->getExpr());
16931     }
16932   };
16933 }
16934 
16935 /// Mark any declarations that appear within this expression or any
16936 /// potentially-evaluated subexpressions as "referenced".
16937 ///
16938 /// \param SkipLocalVariables If true, don't mark local variables as
16939 /// 'referenced'.
16940 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16941                                             bool SkipLocalVariables) {
16942   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16943 }
16944 
16945 /// Emit a diagnostic that describes an effect on the run-time behavior
16946 /// of the program being compiled.
16947 ///
16948 /// This routine emits the given diagnostic when the code currently being
16949 /// type-checked is "potentially evaluated", meaning that there is a
16950 /// possibility that the code will actually be executable. Code in sizeof()
16951 /// expressions, code used only during overload resolution, etc., are not
16952 /// potentially evaluated. This routine will suppress such diagnostics or,
16953 /// in the absolutely nutty case of potentially potentially evaluated
16954 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16955 /// later.
16956 ///
16957 /// This routine should be used for all diagnostics that describe the run-time
16958 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16959 /// Failure to do so will likely result in spurious diagnostics or failures
16960 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16961 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
16962                                const PartialDiagnostic &PD) {
16963   switch (ExprEvalContexts.back().Context) {
16964   case ExpressionEvaluationContext::Unevaluated:
16965   case ExpressionEvaluationContext::UnevaluatedList:
16966   case ExpressionEvaluationContext::UnevaluatedAbstract:
16967   case ExpressionEvaluationContext::DiscardedStatement:
16968     // The argument will never be evaluated, so don't complain.
16969     break;
16970 
16971   case ExpressionEvaluationContext::ConstantEvaluated:
16972     // Relevant diagnostics should be produced by constant evaluation.
16973     break;
16974 
16975   case ExpressionEvaluationContext::PotentiallyEvaluated:
16976   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16977     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
16978       FunctionScopes.back()->PossiblyUnreachableDiags.
16979         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
16980       return true;
16981     }
16982 
16983     // The initializer of a constexpr variable or of the first declaration of a
16984     // static data member is not syntactically a constant evaluated constant,
16985     // but nonetheless is always required to be a constant expression, so we
16986     // can skip diagnosing.
16987     // FIXME: Using the mangling context here is a hack.
16988     if (auto *VD = dyn_cast_or_null<VarDecl>(
16989             ExprEvalContexts.back().ManglingContextDecl)) {
16990       if (VD->isConstexpr() ||
16991           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16992         break;
16993       // FIXME: For any other kind of variable, we should build a CFG for its
16994       // initializer and check whether the context in question is reachable.
16995     }
16996 
16997     Diag(Loc, PD);
16998     return true;
16999   }
17000 
17001   return false;
17002 }
17003 
17004 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17005                                const PartialDiagnostic &PD) {
17006   return DiagRuntimeBehavior(
17007       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17008 }
17009 
17010 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17011                                CallExpr *CE, FunctionDecl *FD) {
17012   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17013     return false;
17014 
17015   // If we're inside a decltype's expression, don't check for a valid return
17016   // type or construct temporaries until we know whether this is the last call.
17017   if (ExprEvalContexts.back().ExprContext ==
17018       ExpressionEvaluationContextRecord::EK_Decltype) {
17019     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17020     return false;
17021   }
17022 
17023   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17024     FunctionDecl *FD;
17025     CallExpr *CE;
17026 
17027   public:
17028     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17029       : FD(FD), CE(CE) { }
17030 
17031     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17032       if (!FD) {
17033         S.Diag(Loc, diag::err_call_incomplete_return)
17034           << T << CE->getSourceRange();
17035         return;
17036       }
17037 
17038       S.Diag(Loc, diag::err_call_function_incomplete_return)
17039         << CE->getSourceRange() << FD->getDeclName() << T;
17040       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17041           << FD->getDeclName();
17042     }
17043   } Diagnoser(FD, CE);
17044 
17045   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17046     return true;
17047 
17048   return false;
17049 }
17050 
17051 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17052 // will prevent this condition from triggering, which is what we want.
17053 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17054   SourceLocation Loc;
17055 
17056   unsigned diagnostic = diag::warn_condition_is_assignment;
17057   bool IsOrAssign = false;
17058 
17059   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17060     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17061       return;
17062 
17063     IsOrAssign = Op->getOpcode() == BO_OrAssign;
17064 
17065     // Greylist some idioms by putting them into a warning subcategory.
17066     if (ObjCMessageExpr *ME
17067           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17068       Selector Sel = ME->getSelector();
17069 
17070       // self = [<foo> init...]
17071       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17072         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17073 
17074       // <foo> = [<bar> nextObject]
17075       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17076         diagnostic = diag::warn_condition_is_idiomatic_assignment;
17077     }
17078 
17079     Loc = Op->getOperatorLoc();
17080   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17081     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17082       return;
17083 
17084     IsOrAssign = Op->getOperator() == OO_PipeEqual;
17085     Loc = Op->getOperatorLoc();
17086   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17087     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17088   else {
17089     // Not an assignment.
17090     return;
17091   }
17092 
17093   Diag(Loc, diagnostic) << E->getSourceRange();
17094 
17095   SourceLocation Open = E->getBeginLoc();
17096   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17097   Diag(Loc, diag::note_condition_assign_silence)
17098         << FixItHint::CreateInsertion(Open, "(")
17099         << FixItHint::CreateInsertion(Close, ")");
17100 
17101   if (IsOrAssign)
17102     Diag(Loc, diag::note_condition_or_assign_to_comparison)
17103       << FixItHint::CreateReplacement(Loc, "!=");
17104   else
17105     Diag(Loc, diag::note_condition_assign_to_comparison)
17106       << FixItHint::CreateReplacement(Loc, "==");
17107 }
17108 
17109 /// Redundant parentheses over an equality comparison can indicate
17110 /// that the user intended an assignment used as condition.
17111 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17112   // Don't warn if the parens came from a macro.
17113   SourceLocation parenLoc = ParenE->getBeginLoc();
17114   if (parenLoc.isInvalid() || parenLoc.isMacroID())
17115     return;
17116   // Don't warn for dependent expressions.
17117   if (ParenE->isTypeDependent())
17118     return;
17119 
17120   Expr *E = ParenE->IgnoreParens();
17121 
17122   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17123     if (opE->getOpcode() == BO_EQ &&
17124         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17125                                                            == Expr::MLV_Valid) {
17126       SourceLocation Loc = opE->getOperatorLoc();
17127 
17128       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17129       SourceRange ParenERange = ParenE->getSourceRange();
17130       Diag(Loc, diag::note_equality_comparison_silence)
17131         << FixItHint::CreateRemoval(ParenERange.getBegin())
17132         << FixItHint::CreateRemoval(ParenERange.getEnd());
17133       Diag(Loc, diag::note_equality_comparison_to_assign)
17134         << FixItHint::CreateReplacement(Loc, "=");
17135     }
17136 }
17137 
17138 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17139                                        bool IsConstexpr) {
17140   DiagnoseAssignmentAsCondition(E);
17141   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17142     DiagnoseEqualityWithExtraParens(parenE);
17143 
17144   ExprResult result = CheckPlaceholderExpr(E);
17145   if (result.isInvalid()) return ExprError();
17146   E = result.get();
17147 
17148   if (!E->isTypeDependent()) {
17149     if (getLangOpts().CPlusPlus)
17150       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17151 
17152     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17153     if (ERes.isInvalid())
17154       return ExprError();
17155     E = ERes.get();
17156 
17157     QualType T = E->getType();
17158     if (!T->isScalarType()) { // C99 6.8.4.1p1
17159       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17160         << T << E->getSourceRange();
17161       return ExprError();
17162     }
17163     CheckBoolLikeConversion(E, Loc);
17164   }
17165 
17166   return E;
17167 }
17168 
17169 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17170                                            Expr *SubExpr, ConditionKind CK) {
17171   // Empty conditions are valid in for-statements.
17172   if (!SubExpr)
17173     return ConditionResult();
17174 
17175   ExprResult Cond;
17176   switch (CK) {
17177   case ConditionKind::Boolean:
17178     Cond = CheckBooleanCondition(Loc, SubExpr);
17179     break;
17180 
17181   case ConditionKind::ConstexprIf:
17182     Cond = CheckBooleanCondition(Loc, SubExpr, true);
17183     break;
17184 
17185   case ConditionKind::Switch:
17186     Cond = CheckSwitchCondition(Loc, SubExpr);
17187     break;
17188   }
17189   if (Cond.isInvalid())
17190     return ConditionError();
17191 
17192   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17193   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17194   if (!FullExpr.get())
17195     return ConditionError();
17196 
17197   return ConditionResult(*this, nullptr, FullExpr,
17198                          CK == ConditionKind::ConstexprIf);
17199 }
17200 
17201 namespace {
17202   /// A visitor for rebuilding a call to an __unknown_any expression
17203   /// to have an appropriate type.
17204   struct RebuildUnknownAnyFunction
17205     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17206 
17207     Sema &S;
17208 
17209     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17210 
17211     ExprResult VisitStmt(Stmt *S) {
17212       llvm_unreachable("unexpected statement!");
17213     }
17214 
17215     ExprResult VisitExpr(Expr *E) {
17216       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17217         << E->getSourceRange();
17218       return ExprError();
17219     }
17220 
17221     /// Rebuild an expression which simply semantically wraps another
17222     /// expression which it shares the type and value kind of.
17223     template <class T> ExprResult rebuildSugarExpr(T *E) {
17224       ExprResult SubResult = Visit(E->getSubExpr());
17225       if (SubResult.isInvalid()) return ExprError();
17226 
17227       Expr *SubExpr = SubResult.get();
17228       E->setSubExpr(SubExpr);
17229       E->setType(SubExpr->getType());
17230       E->setValueKind(SubExpr->getValueKind());
17231       assert(E->getObjectKind() == OK_Ordinary);
17232       return E;
17233     }
17234 
17235     ExprResult VisitParenExpr(ParenExpr *E) {
17236       return rebuildSugarExpr(E);
17237     }
17238 
17239     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17240       return rebuildSugarExpr(E);
17241     }
17242 
17243     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17244       ExprResult SubResult = Visit(E->getSubExpr());
17245       if (SubResult.isInvalid()) return ExprError();
17246 
17247       Expr *SubExpr = SubResult.get();
17248       E->setSubExpr(SubExpr);
17249       E->setType(S.Context.getPointerType(SubExpr->getType()));
17250       assert(E->getValueKind() == VK_RValue);
17251       assert(E->getObjectKind() == OK_Ordinary);
17252       return E;
17253     }
17254 
17255     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17256       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17257 
17258       E->setType(VD->getType());
17259 
17260       assert(E->getValueKind() == VK_RValue);
17261       if (S.getLangOpts().CPlusPlus &&
17262           !(isa<CXXMethodDecl>(VD) &&
17263             cast<CXXMethodDecl>(VD)->isInstance()))
17264         E->setValueKind(VK_LValue);
17265 
17266       return E;
17267     }
17268 
17269     ExprResult VisitMemberExpr(MemberExpr *E) {
17270       return resolveDecl(E, E->getMemberDecl());
17271     }
17272 
17273     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17274       return resolveDecl(E, E->getDecl());
17275     }
17276   };
17277 }
17278 
17279 /// Given a function expression of unknown-any type, try to rebuild it
17280 /// to have a function type.
17281 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17282   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17283   if (Result.isInvalid()) return ExprError();
17284   return S.DefaultFunctionArrayConversion(Result.get());
17285 }
17286 
17287 namespace {
17288   /// A visitor for rebuilding an expression of type __unknown_anytype
17289   /// into one which resolves the type directly on the referring
17290   /// expression.  Strict preservation of the original source
17291   /// structure is not a goal.
17292   struct RebuildUnknownAnyExpr
17293     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17294 
17295     Sema &S;
17296 
17297     /// The current destination type.
17298     QualType DestType;
17299 
17300     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17301       : S(S), DestType(CastType) {}
17302 
17303     ExprResult VisitStmt(Stmt *S) {
17304       llvm_unreachable("unexpected statement!");
17305     }
17306 
17307     ExprResult VisitExpr(Expr *E) {
17308       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17309         << E->getSourceRange();
17310       return ExprError();
17311     }
17312 
17313     ExprResult VisitCallExpr(CallExpr *E);
17314     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17315 
17316     /// Rebuild an expression which simply semantically wraps another
17317     /// expression which it shares the type and value kind of.
17318     template <class T> ExprResult rebuildSugarExpr(T *E) {
17319       ExprResult SubResult = Visit(E->getSubExpr());
17320       if (SubResult.isInvalid()) return ExprError();
17321       Expr *SubExpr = SubResult.get();
17322       E->setSubExpr(SubExpr);
17323       E->setType(SubExpr->getType());
17324       E->setValueKind(SubExpr->getValueKind());
17325       assert(E->getObjectKind() == OK_Ordinary);
17326       return E;
17327     }
17328 
17329     ExprResult VisitParenExpr(ParenExpr *E) {
17330       return rebuildSugarExpr(E);
17331     }
17332 
17333     ExprResult VisitUnaryExtension(UnaryOperator *E) {
17334       return rebuildSugarExpr(E);
17335     }
17336 
17337     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17338       const PointerType *Ptr = DestType->getAs<PointerType>();
17339       if (!Ptr) {
17340         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17341           << E->getSourceRange();
17342         return ExprError();
17343       }
17344 
17345       if (isa<CallExpr>(E->getSubExpr())) {
17346         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17347           << E->getSourceRange();
17348         return ExprError();
17349       }
17350 
17351       assert(E->getValueKind() == VK_RValue);
17352       assert(E->getObjectKind() == OK_Ordinary);
17353       E->setType(DestType);
17354 
17355       // Build the sub-expression as if it were an object of the pointee type.
17356       DestType = Ptr->getPointeeType();
17357       ExprResult SubResult = Visit(E->getSubExpr());
17358       if (SubResult.isInvalid()) return ExprError();
17359       E->setSubExpr(SubResult.get());
17360       return E;
17361     }
17362 
17363     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17364 
17365     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17366 
17367     ExprResult VisitMemberExpr(MemberExpr *E) {
17368       return resolveDecl(E, E->getMemberDecl());
17369     }
17370 
17371     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17372       return resolveDecl(E, E->getDecl());
17373     }
17374   };
17375 }
17376 
17377 /// Rebuilds a call expression which yielded __unknown_anytype.
17378 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17379   Expr *CalleeExpr = E->getCallee();
17380 
17381   enum FnKind {
17382     FK_MemberFunction,
17383     FK_FunctionPointer,
17384     FK_BlockPointer
17385   };
17386 
17387   FnKind Kind;
17388   QualType CalleeType = CalleeExpr->getType();
17389   if (CalleeType == S.Context.BoundMemberTy) {
17390     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
17391     Kind = FK_MemberFunction;
17392     CalleeType = Expr::findBoundMemberType(CalleeExpr);
17393   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17394     CalleeType = Ptr->getPointeeType();
17395     Kind = FK_FunctionPointer;
17396   } else {
17397     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17398     Kind = FK_BlockPointer;
17399   }
17400   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17401 
17402   // Verify that this is a legal result type of a function.
17403   if (DestType->isArrayType() || DestType->isFunctionType()) {
17404     unsigned diagID = diag::err_func_returning_array_function;
17405     if (Kind == FK_BlockPointer)
17406       diagID = diag::err_block_returning_array_function;
17407 
17408     S.Diag(E->getExprLoc(), diagID)
17409       << DestType->isFunctionType() << DestType;
17410     return ExprError();
17411   }
17412 
17413   // Otherwise, go ahead and set DestType as the call's result.
17414   E->setType(DestType.getNonLValueExprType(S.Context));
17415   E->setValueKind(Expr::getValueKindForType(DestType));
17416   assert(E->getObjectKind() == OK_Ordinary);
17417 
17418   // Rebuild the function type, replacing the result type with DestType.
17419   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17420   if (Proto) {
17421     // __unknown_anytype(...) is a special case used by the debugger when
17422     // it has no idea what a function's signature is.
17423     //
17424     // We want to build this call essentially under the K&R
17425     // unprototyped rules, but making a FunctionNoProtoType in C++
17426     // would foul up all sorts of assumptions.  However, we cannot
17427     // simply pass all arguments as variadic arguments, nor can we
17428     // portably just call the function under a non-variadic type; see
17429     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17430     // However, it turns out that in practice it is generally safe to
17431     // call a function declared as "A foo(B,C,D);" under the prototype
17432     // "A foo(B,C,D,...);".  The only known exception is with the
17433     // Windows ABI, where any variadic function is implicitly cdecl
17434     // regardless of its normal CC.  Therefore we change the parameter
17435     // types to match the types of the arguments.
17436     //
17437     // This is a hack, but it is far superior to moving the
17438     // corresponding target-specific code from IR-gen to Sema/AST.
17439 
17440     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17441     SmallVector<QualType, 8> ArgTypes;
17442     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17443       ArgTypes.reserve(E->getNumArgs());
17444       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17445         Expr *Arg = E->getArg(i);
17446         QualType ArgType = Arg->getType();
17447         if (E->isLValue()) {
17448           ArgType = S.Context.getLValueReferenceType(ArgType);
17449         } else if (E->isXValue()) {
17450           ArgType = S.Context.getRValueReferenceType(ArgType);
17451         }
17452         ArgTypes.push_back(ArgType);
17453       }
17454       ParamTypes = ArgTypes;
17455     }
17456     DestType = S.Context.getFunctionType(DestType, ParamTypes,
17457                                          Proto->getExtProtoInfo());
17458   } else {
17459     DestType = S.Context.getFunctionNoProtoType(DestType,
17460                                                 FnType->getExtInfo());
17461   }
17462 
17463   // Rebuild the appropriate pointer-to-function type.
17464   switch (Kind) {
17465   case FK_MemberFunction:
17466     // Nothing to do.
17467     break;
17468 
17469   case FK_FunctionPointer:
17470     DestType = S.Context.getPointerType(DestType);
17471     break;
17472 
17473   case FK_BlockPointer:
17474     DestType = S.Context.getBlockPointerType(DestType);
17475     break;
17476   }
17477 
17478   // Finally, we can recurse.
17479   ExprResult CalleeResult = Visit(CalleeExpr);
17480   if (!CalleeResult.isUsable()) return ExprError();
17481   E->setCallee(CalleeResult.get());
17482 
17483   // Bind a temporary if necessary.
17484   return S.MaybeBindToTemporary(E);
17485 }
17486 
17487 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17488   // Verify that this is a legal result type of a call.
17489   if (DestType->isArrayType() || DestType->isFunctionType()) {
17490     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17491       << DestType->isFunctionType() << DestType;
17492     return ExprError();
17493   }
17494 
17495   // Rewrite the method result type if available.
17496   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17497     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
17498     Method->setReturnType(DestType);
17499   }
17500 
17501   // Change the type of the message.
17502   E->setType(DestType.getNonReferenceType());
17503   E->setValueKind(Expr::getValueKindForType(DestType));
17504 
17505   return S.MaybeBindToTemporary(E);
17506 }
17507 
17508 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
17509   // The only case we should ever see here is a function-to-pointer decay.
17510   if (E->getCastKind() == CK_FunctionToPointerDecay) {
17511     assert(E->getValueKind() == VK_RValue);
17512     assert(E->getObjectKind() == OK_Ordinary);
17513 
17514     E->setType(DestType);
17515 
17516     // Rebuild the sub-expression as the pointee (function) type.
17517     DestType = DestType->castAs<PointerType>()->getPointeeType();
17518 
17519     ExprResult Result = Visit(E->getSubExpr());
17520     if (!Result.isUsable()) return ExprError();
17521 
17522     E->setSubExpr(Result.get());
17523     return E;
17524   } else if (E->getCastKind() == CK_LValueToRValue) {
17525     assert(E->getValueKind() == VK_RValue);
17526     assert(E->getObjectKind() == OK_Ordinary);
17527 
17528     assert(isa<BlockPointerType>(E->getType()));
17529 
17530     E->setType(DestType);
17531 
17532     // The sub-expression has to be a lvalue reference, so rebuild it as such.
17533     DestType = S.Context.getLValueReferenceType(DestType);
17534 
17535     ExprResult Result = Visit(E->getSubExpr());
17536     if (!Result.isUsable()) return ExprError();
17537 
17538     E->setSubExpr(Result.get());
17539     return E;
17540   } else {
17541     llvm_unreachable("Unhandled cast type!");
17542   }
17543 }
17544 
17545 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
17546   ExprValueKind ValueKind = VK_LValue;
17547   QualType Type = DestType;
17548 
17549   // We know how to make this work for certain kinds of decls:
17550 
17551   //  - functions
17552   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
17553     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
17554       DestType = Ptr->getPointeeType();
17555       ExprResult Result = resolveDecl(E, VD);
17556       if (Result.isInvalid()) return ExprError();
17557       return S.ImpCastExprToType(Result.get(), Type,
17558                                  CK_FunctionToPointerDecay, VK_RValue);
17559     }
17560 
17561     if (!Type->isFunctionType()) {
17562       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
17563         << VD << E->getSourceRange();
17564       return ExprError();
17565     }
17566     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
17567       // We must match the FunctionDecl's type to the hack introduced in
17568       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
17569       // type. See the lengthy commentary in that routine.
17570       QualType FDT = FD->getType();
17571       const FunctionType *FnType = FDT->castAs<FunctionType>();
17572       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
17573       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
17574       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
17575         SourceLocation Loc = FD->getLocation();
17576         FunctionDecl *NewFD = FunctionDecl::Create(
17577             S.Context, FD->getDeclContext(), Loc, Loc,
17578             FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
17579             SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
17580             /*ConstexprKind*/ CSK_unspecified);
17581 
17582         if (FD->getQualifier())
17583           NewFD->setQualifierInfo(FD->getQualifierLoc());
17584 
17585         SmallVector<ParmVarDecl*, 16> Params;
17586         for (const auto &AI : FT->param_types()) {
17587           ParmVarDecl *Param =
17588             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
17589           Param->setScopeInfo(0, Params.size());
17590           Params.push_back(Param);
17591         }
17592         NewFD->setParams(Params);
17593         DRE->setDecl(NewFD);
17594         VD = DRE->getDecl();
17595       }
17596     }
17597 
17598     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
17599       if (MD->isInstance()) {
17600         ValueKind = VK_RValue;
17601         Type = S.Context.BoundMemberTy;
17602       }
17603 
17604     // Function references aren't l-values in C.
17605     if (!S.getLangOpts().CPlusPlus)
17606       ValueKind = VK_RValue;
17607 
17608   //  - variables
17609   } else if (isa<VarDecl>(VD)) {
17610     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
17611       Type = RefTy->getPointeeType();
17612     } else if (Type->isFunctionType()) {
17613       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
17614         << VD << E->getSourceRange();
17615       return ExprError();
17616     }
17617 
17618   //  - nothing else
17619   } else {
17620     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
17621       << VD << E->getSourceRange();
17622     return ExprError();
17623   }
17624 
17625   // Modifying the declaration like this is friendly to IR-gen but
17626   // also really dangerous.
17627   VD->setType(DestType);
17628   E->setType(Type);
17629   E->setValueKind(ValueKind);
17630   return E;
17631 }
17632 
17633 /// Check a cast of an unknown-any type.  We intentionally only
17634 /// trigger this for C-style casts.
17635 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
17636                                      Expr *CastExpr, CastKind &CastKind,
17637                                      ExprValueKind &VK, CXXCastPath &Path) {
17638   // The type we're casting to must be either void or complete.
17639   if (!CastType->isVoidType() &&
17640       RequireCompleteType(TypeRange.getBegin(), CastType,
17641                           diag::err_typecheck_cast_to_incomplete))
17642     return ExprError();
17643 
17644   // Rewrite the casted expression from scratch.
17645   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
17646   if (!result.isUsable()) return ExprError();
17647 
17648   CastExpr = result.get();
17649   VK = CastExpr->getValueKind();
17650   CastKind = CK_NoOp;
17651 
17652   return CastExpr;
17653 }
17654 
17655 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
17656   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
17657 }
17658 
17659 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
17660                                     Expr *arg, QualType &paramType) {
17661   // If the syntactic form of the argument is not an explicit cast of
17662   // any sort, just do default argument promotion.
17663   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
17664   if (!castArg) {
17665     ExprResult result = DefaultArgumentPromotion(arg);
17666     if (result.isInvalid()) return ExprError();
17667     paramType = result.get()->getType();
17668     return result;
17669   }
17670 
17671   // Otherwise, use the type that was written in the explicit cast.
17672   assert(!arg->hasPlaceholderType());
17673   paramType = castArg->getTypeAsWritten();
17674 
17675   // Copy-initialize a parameter of that type.
17676   InitializedEntity entity =
17677     InitializedEntity::InitializeParameter(Context, paramType,
17678                                            /*consumed*/ false);
17679   return PerformCopyInitialization(entity, callLoc, arg);
17680 }
17681 
17682 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
17683   Expr *orig = E;
17684   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
17685   while (true) {
17686     E = E->IgnoreParenImpCasts();
17687     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
17688       E = call->getCallee();
17689       diagID = diag::err_uncasted_call_of_unknown_any;
17690     } else {
17691       break;
17692     }
17693   }
17694 
17695   SourceLocation loc;
17696   NamedDecl *d;
17697   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
17698     loc = ref->getLocation();
17699     d = ref->getDecl();
17700   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
17701     loc = mem->getMemberLoc();
17702     d = mem->getMemberDecl();
17703   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
17704     diagID = diag::err_uncasted_call_of_unknown_any;
17705     loc = msg->getSelectorStartLoc();
17706     d = msg->getMethodDecl();
17707     if (!d) {
17708       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
17709         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
17710         << orig->getSourceRange();
17711       return ExprError();
17712     }
17713   } else {
17714     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17715       << E->getSourceRange();
17716     return ExprError();
17717   }
17718 
17719   S.Diag(loc, diagID) << d << orig->getSourceRange();
17720 
17721   // Never recoverable.
17722   return ExprError();
17723 }
17724 
17725 /// Check for operands with placeholder types and complain if found.
17726 /// Returns ExprError() if there was an error and no recovery was possible.
17727 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
17728   if (!getLangOpts().CPlusPlus) {
17729     // C cannot handle TypoExpr nodes on either side of a binop because it
17730     // doesn't handle dependent types properly, so make sure any TypoExprs have
17731     // been dealt with before checking the operands.
17732     ExprResult Result = CorrectDelayedTyposInExpr(E);
17733     if (!Result.isUsable()) return ExprError();
17734     E = Result.get();
17735   }
17736 
17737   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
17738   if (!placeholderType) return E;
17739 
17740   switch (placeholderType->getKind()) {
17741 
17742   // Overloaded expressions.
17743   case BuiltinType::Overload: {
17744     // Try to resolve a single function template specialization.
17745     // This is obligatory.
17746     ExprResult Result = E;
17747     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
17748       return Result;
17749 
17750     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
17751     // leaves Result unchanged on failure.
17752     Result = E;
17753     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
17754       return Result;
17755 
17756     // If that failed, try to recover with a call.
17757     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
17758                          /*complain*/ true);
17759     return Result;
17760   }
17761 
17762   // Bound member functions.
17763   case BuiltinType::BoundMember: {
17764     ExprResult result = E;
17765     const Expr *BME = E->IgnoreParens();
17766     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
17767     // Try to give a nicer diagnostic if it is a bound member that we recognize.
17768     if (isa<CXXPseudoDestructorExpr>(BME)) {
17769       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
17770     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
17771       if (ME->getMemberNameInfo().getName().getNameKind() ==
17772           DeclarationName::CXXDestructorName)
17773         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
17774     }
17775     tryToRecoverWithCall(result, PD,
17776                          /*complain*/ true);
17777     return result;
17778   }
17779 
17780   // ARC unbridged casts.
17781   case BuiltinType::ARCUnbridgedCast: {
17782     Expr *realCast = stripARCUnbridgedCast(E);
17783     diagnoseARCUnbridgedCast(realCast);
17784     return realCast;
17785   }
17786 
17787   // Expressions of unknown type.
17788   case BuiltinType::UnknownAny:
17789     return diagnoseUnknownAnyExpr(*this, E);
17790 
17791   // Pseudo-objects.
17792   case BuiltinType::PseudoObject:
17793     return checkPseudoObjectRValue(E);
17794 
17795   case BuiltinType::BuiltinFn: {
17796     // Accept __noop without parens by implicitly converting it to a call expr.
17797     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
17798     if (DRE) {
17799       auto *FD = cast<FunctionDecl>(DRE->getDecl());
17800       if (FD->getBuiltinID() == Builtin::BI__noop) {
17801         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
17802                               CK_BuiltinFnToFnPtr)
17803                 .get();
17804         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
17805                                 VK_RValue, SourceLocation());
17806       }
17807     }
17808 
17809     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
17810     return ExprError();
17811   }
17812 
17813   // Expressions of unknown type.
17814   case BuiltinType::OMPArraySection:
17815     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
17816     return ExprError();
17817 
17818   // Everything else should be impossible.
17819 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
17820   case BuiltinType::Id:
17821 #include "clang/Basic/OpenCLImageTypes.def"
17822 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
17823   case BuiltinType::Id:
17824 #include "clang/Basic/OpenCLExtensionTypes.def"
17825 #define SVE_TYPE(Name, Id, SingletonId) \
17826   case BuiltinType::Id:
17827 #include "clang/Basic/AArch64SVEACLETypes.def"
17828 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
17829 #define PLACEHOLDER_TYPE(Id, SingletonId)
17830 #include "clang/AST/BuiltinTypes.def"
17831     break;
17832   }
17833 
17834   llvm_unreachable("invalid placeholder type!");
17835 }
17836 
17837 bool Sema::CheckCaseExpression(Expr *E) {
17838   if (E->isTypeDependent())
17839     return true;
17840   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17841     return E->getType()->isIntegralOrEnumerationType();
17842   return false;
17843 }
17844 
17845 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17846 ExprResult
17847 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17848   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17849          "Unknown Objective-C Boolean value!");
17850   QualType BoolT = Context.ObjCBuiltinBoolTy;
17851   if (!Context.getBOOLDecl()) {
17852     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17853                         Sema::LookupOrdinaryName);
17854     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17855       NamedDecl *ND = Result.getFoundDecl();
17856       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17857         Context.setBOOLDecl(TD);
17858     }
17859   }
17860   if (Context.getBOOLDecl())
17861     BoolT = Context.getBOOLType();
17862   return new (Context)
17863       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17864 }
17865 
17866 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17867     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17868     SourceLocation RParen) {
17869 
17870   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17871 
17872   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17873     return Spec.getPlatform() == Platform;
17874   });
17875 
17876   VersionTuple Version;
17877   if (Spec != AvailSpecs.end())
17878     Version = Spec->getVersion();
17879 
17880   // The use of `@available` in the enclosing function should be analyzed to
17881   // warn when it's used inappropriately (i.e. not if(@available)).
17882   if (getCurFunctionOrMethodDecl())
17883     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17884   else if (getCurBlock() || getCurLambda())
17885     getCurFunction()->HasPotentialAvailabilityViolations = true;
17886 
17887   return new (Context)
17888       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
17889 }
17890