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   UpdateMarkingForLValueToRValue(E);
629 
630   // Loading a __weak object implicitly retains the value, so we need a cleanup to
631   // balance that.
632   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
633     Cleanup.setExprNeedsCleanups(true);
634 
635   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
636                                             nullptr, VK_RValue);
637 
638   // C11 6.3.2.1p2:
639   //   ... if the lvalue has atomic type, the value has the non-atomic version
640   //   of the type of the lvalue ...
641   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
642     T = Atomic->getValueType().getUnqualifiedType();
643     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
644                                    nullptr, VK_RValue);
645   }
646 
647   return Res;
648 }
649 
650 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
651   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
652   if (Res.isInvalid())
653     return ExprError();
654   Res = DefaultLvalueConversion(Res.get());
655   if (Res.isInvalid())
656     return ExprError();
657   return Res;
658 }
659 
660 /// CallExprUnaryConversions - a special case of an unary conversion
661 /// performed on a function designator of a call expression.
662 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
663   QualType Ty = E->getType();
664   ExprResult Res = E;
665   // Only do implicit cast for a function type, but not for a pointer
666   // to function type.
667   if (Ty->isFunctionType()) {
668     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
669                             CK_FunctionToPointerDecay).get();
670     if (Res.isInvalid())
671       return ExprError();
672   }
673   Res = DefaultLvalueConversion(Res.get());
674   if (Res.isInvalid())
675     return ExprError();
676   return Res.get();
677 }
678 
679 /// UsualUnaryConversions - Performs various conversions that are common to most
680 /// operators (C99 6.3). The conversions of array and function types are
681 /// sometimes suppressed. For example, the array->pointer conversion doesn't
682 /// apply if the array is an argument to the sizeof or address (&) operators.
683 /// In these instances, this routine should *not* be called.
684 ExprResult Sema::UsualUnaryConversions(Expr *E) {
685   // First, convert to an r-value.
686   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
687   if (Res.isInvalid())
688     return ExprError();
689   E = Res.get();
690 
691   QualType Ty = E->getType();
692   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
693 
694   // Half FP have to be promoted to float unless it is natively supported
695   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
696     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
697 
698   // Try to perform integral promotions if the object has a theoretically
699   // promotable type.
700   if (Ty->isIntegralOrUnscopedEnumerationType()) {
701     // C99 6.3.1.1p2:
702     //
703     //   The following may be used in an expression wherever an int or
704     //   unsigned int may be used:
705     //     - an object or expression with an integer type whose integer
706     //       conversion rank is less than or equal to the rank of int
707     //       and unsigned int.
708     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
709     //
710     //   If an int can represent all values of the original type, the
711     //   value is converted to an int; otherwise, it is converted to an
712     //   unsigned int. These are called the integer promotions. All
713     //   other types are unchanged by the integer promotions.
714 
715     QualType PTy = Context.isPromotableBitField(E);
716     if (!PTy.isNull()) {
717       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
718       return E;
719     }
720     if (Ty->isPromotableIntegerType()) {
721       QualType PT = Context.getPromotedIntegerType(Ty);
722       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
723       return E;
724     }
725   }
726   return E;
727 }
728 
729 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
730 /// do not have a prototype. Arguments that have type float or __fp16
731 /// are promoted to double. All other argument types are converted by
732 /// UsualUnaryConversions().
733 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
734   QualType Ty = E->getType();
735   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
736 
737   ExprResult Res = UsualUnaryConversions(E);
738   if (Res.isInvalid())
739     return ExprError();
740   E = Res.get();
741 
742   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
743   // promote to double.
744   // Note that default argument promotion applies only to float (and
745   // half/fp16); it does not apply to _Float16.
746   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
747   if (BTy && (BTy->getKind() == BuiltinType::Half ||
748               BTy->getKind() == BuiltinType::Float)) {
749     if (getLangOpts().OpenCL &&
750         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
751         if (BTy->getKind() == BuiltinType::Half) {
752             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
753         }
754     } else {
755       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
756     }
757   }
758 
759   // C++ performs lvalue-to-rvalue conversion as a default argument
760   // promotion, even on class types, but note:
761   //   C++11 [conv.lval]p2:
762   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
763   //     operand or a subexpression thereof the value contained in the
764   //     referenced object is not accessed. Otherwise, if the glvalue
765   //     has a class type, the conversion copy-initializes a temporary
766   //     of type T from the glvalue and the result of the conversion
767   //     is a prvalue for the temporary.
768   // FIXME: add some way to gate this entire thing for correctness in
769   // potentially potentially evaluated contexts.
770   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
771     ExprResult Temp = PerformCopyInitialization(
772                        InitializedEntity::InitializeTemporary(E->getType()),
773                                                 E->getExprLoc(), E);
774     if (Temp.isInvalid())
775       return ExprError();
776     E = Temp.get();
777   }
778 
779   return E;
780 }
781 
782 /// Determine the degree of POD-ness for an expression.
783 /// Incomplete types are considered POD, since this check can be performed
784 /// when we're in an unevaluated context.
785 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
786   if (Ty->isIncompleteType()) {
787     // C++11 [expr.call]p7:
788     //   After these conversions, if the argument does not have arithmetic,
789     //   enumeration, pointer, pointer to member, or class type, the program
790     //   is ill-formed.
791     //
792     // Since we've already performed array-to-pointer and function-to-pointer
793     // decay, the only such type in C++ is cv void. This also handles
794     // initializer lists as variadic arguments.
795     if (Ty->isVoidType())
796       return VAK_Invalid;
797 
798     if (Ty->isObjCObjectType())
799       return VAK_Invalid;
800     return VAK_Valid;
801   }
802 
803   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
804     return VAK_Invalid;
805 
806   if (Ty.isCXX98PODType(Context))
807     return VAK_Valid;
808 
809   // C++11 [expr.call]p7:
810   //   Passing a potentially-evaluated argument of class type (Clause 9)
811   //   having a non-trivial copy constructor, a non-trivial move constructor,
812   //   or a non-trivial destructor, with no corresponding parameter,
813   //   is conditionally-supported with implementation-defined semantics.
814   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
815     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
816       if (!Record->hasNonTrivialCopyConstructor() &&
817           !Record->hasNonTrivialMoveConstructor() &&
818           !Record->hasNonTrivialDestructor())
819         return VAK_ValidInCXX11;
820 
821   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
822     return VAK_Valid;
823 
824   if (Ty->isObjCObjectType())
825     return VAK_Invalid;
826 
827   if (getLangOpts().MSVCCompat)
828     return VAK_MSVCUndefined;
829 
830   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
831   // permitted to reject them. We should consider doing so.
832   return VAK_Undefined;
833 }
834 
835 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
836   // Don't allow one to pass an Objective-C interface to a vararg.
837   const QualType &Ty = E->getType();
838   VarArgKind VAK = isValidVarArgType(Ty);
839 
840   // Complain about passing non-POD types through varargs.
841   switch (VAK) {
842   case VAK_ValidInCXX11:
843     DiagRuntimeBehavior(
844         E->getBeginLoc(), nullptr,
845         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
846     LLVM_FALLTHROUGH;
847   case VAK_Valid:
848     if (Ty->isRecordType()) {
849       // This is unlikely to be what the user intended. If the class has a
850       // 'c_str' member function, the user probably meant to call that.
851       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
852                           PDiag(diag::warn_pass_class_arg_to_vararg)
853                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
854     }
855     break;
856 
857   case VAK_Undefined:
858   case VAK_MSVCUndefined:
859     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
860                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
861                             << getLangOpts().CPlusPlus11 << Ty << CT);
862     break;
863 
864   case VAK_Invalid:
865     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
866       Diag(E->getBeginLoc(),
867            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
868           << Ty << CT;
869     else if (Ty->isObjCObjectType())
870       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
871                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
872                               << Ty << CT);
873     else
874       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
875           << isa<InitListExpr>(E) << Ty << CT;
876     break;
877   }
878 }
879 
880 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
881 /// will create a trap if the resulting type is not a POD type.
882 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
883                                                   FunctionDecl *FDecl) {
884   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
885     // Strip the unbridged-cast placeholder expression off, if applicable.
886     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
887         (CT == VariadicMethod ||
888          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
889       E = stripARCUnbridgedCast(E);
890 
891     // Otherwise, do normal placeholder checking.
892     } else {
893       ExprResult ExprRes = CheckPlaceholderExpr(E);
894       if (ExprRes.isInvalid())
895         return ExprError();
896       E = ExprRes.get();
897     }
898   }
899 
900   ExprResult ExprRes = DefaultArgumentPromotion(E);
901   if (ExprRes.isInvalid())
902     return ExprError();
903   E = ExprRes.get();
904 
905   // Diagnostics regarding non-POD argument types are
906   // emitted along with format string checking in Sema::CheckFunctionCall().
907   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
908     // Turn this into a trap.
909     CXXScopeSpec SS;
910     SourceLocation TemplateKWLoc;
911     UnqualifiedId Name;
912     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
913                        E->getBeginLoc());
914     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
915                                           /*HasTrailingLParen=*/true,
916                                           /*IsAddressOfOperand=*/false);
917     if (TrapFn.isInvalid())
918       return ExprError();
919 
920     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
921                                     None, E->getEndLoc());
922     if (Call.isInvalid())
923       return ExprError();
924 
925     ExprResult Comma =
926         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
927     if (Comma.isInvalid())
928       return ExprError();
929     return Comma.get();
930   }
931 
932   if (!getLangOpts().CPlusPlus &&
933       RequireCompleteType(E->getExprLoc(), E->getType(),
934                           diag::err_call_incomplete_argument))
935     return ExprError();
936 
937   return E;
938 }
939 
940 /// Converts an integer to complex float type.  Helper function of
941 /// UsualArithmeticConversions()
942 ///
943 /// \return false if the integer expression is an integer type and is
944 /// successfully converted to the complex type.
945 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
946                                                   ExprResult &ComplexExpr,
947                                                   QualType IntTy,
948                                                   QualType ComplexTy,
949                                                   bool SkipCast) {
950   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
951   if (SkipCast) return false;
952   if (IntTy->isIntegerType()) {
953     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
954     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
955     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
956                                   CK_FloatingRealToComplex);
957   } else {
958     assert(IntTy->isComplexIntegerType());
959     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
960                                   CK_IntegralComplexToFloatingComplex);
961   }
962   return false;
963 }
964 
965 /// Handle arithmetic conversion with complex types.  Helper function of
966 /// UsualArithmeticConversions()
967 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
968                                              ExprResult &RHS, QualType LHSType,
969                                              QualType RHSType,
970                                              bool IsCompAssign) {
971   // if we have an integer operand, the result is the complex type.
972   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
973                                              /*skipCast*/false))
974     return LHSType;
975   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
976                                              /*skipCast*/IsCompAssign))
977     return RHSType;
978 
979   // This handles complex/complex, complex/float, or float/complex.
980   // When both operands are complex, the shorter operand is converted to the
981   // type of the longer, and that is the type of the result. This corresponds
982   // to what is done when combining two real floating-point operands.
983   // The fun begins when size promotion occur across type domains.
984   // From H&S 6.3.4: When one operand is complex and the other is a real
985   // floating-point type, the less precise type is converted, within it's
986   // real or complex domain, to the precision of the other type. For example,
987   // when combining a "long double" with a "double _Complex", the
988   // "double _Complex" is promoted to "long double _Complex".
989 
990   // Compute the rank of the two types, regardless of whether they are complex.
991   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
992 
993   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
994   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
995   QualType LHSElementType =
996       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
997   QualType RHSElementType =
998       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
999 
1000   QualType ResultType = S.Context.getComplexType(LHSElementType);
1001   if (Order < 0) {
1002     // Promote the precision of the LHS if not an assignment.
1003     ResultType = S.Context.getComplexType(RHSElementType);
1004     if (!IsCompAssign) {
1005       if (LHSComplexType)
1006         LHS =
1007             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1008       else
1009         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1010     }
1011   } else if (Order > 0) {
1012     // Promote the precision of the RHS.
1013     if (RHSComplexType)
1014       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1015     else
1016       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1017   }
1018   return ResultType;
1019 }
1020 
1021 /// Handle arithmetic conversion from integer to float.  Helper function
1022 /// of UsualArithmeticConversions()
1023 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1024                                            ExprResult &IntExpr,
1025                                            QualType FloatTy, QualType IntTy,
1026                                            bool ConvertFloat, bool ConvertInt) {
1027   if (IntTy->isIntegerType()) {
1028     if (ConvertInt)
1029       // Convert intExpr to the lhs floating point type.
1030       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1031                                     CK_IntegralToFloating);
1032     return FloatTy;
1033   }
1034 
1035   // Convert both sides to the appropriate complex float.
1036   assert(IntTy->isComplexIntegerType());
1037   QualType result = S.Context.getComplexType(FloatTy);
1038 
1039   // _Complex int -> _Complex float
1040   if (ConvertInt)
1041     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1042                                   CK_IntegralComplexToFloatingComplex);
1043 
1044   // float -> _Complex float
1045   if (ConvertFloat)
1046     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1047                                     CK_FloatingRealToComplex);
1048 
1049   return result;
1050 }
1051 
1052 /// Handle arithmethic conversion with floating point types.  Helper
1053 /// function of UsualArithmeticConversions()
1054 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1055                                       ExprResult &RHS, QualType LHSType,
1056                                       QualType RHSType, bool IsCompAssign) {
1057   bool LHSFloat = LHSType->isRealFloatingType();
1058   bool RHSFloat = RHSType->isRealFloatingType();
1059 
1060   // If we have two real floating types, convert the smaller operand
1061   // to the bigger result.
1062   if (LHSFloat && RHSFloat) {
1063     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1064     if (order > 0) {
1065       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1066       return LHSType;
1067     }
1068 
1069     assert(order < 0 && "illegal float comparison");
1070     if (!IsCompAssign)
1071       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1072     return RHSType;
1073   }
1074 
1075   if (LHSFloat) {
1076     // Half FP has to be promoted to float unless it is natively supported
1077     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1078       LHSType = S.Context.FloatTy;
1079 
1080     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1081                                       /*convertFloat=*/!IsCompAssign,
1082                                       /*convertInt=*/ true);
1083   }
1084   assert(RHSFloat);
1085   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1086                                     /*convertInt=*/ true,
1087                                     /*convertFloat=*/!IsCompAssign);
1088 }
1089 
1090 /// Diagnose attempts to convert between __float128 and long double if
1091 /// there is no support for such conversion. Helper function of
1092 /// UsualArithmeticConversions().
1093 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1094                                       QualType RHSType) {
1095   /*  No issue converting if at least one of the types is not a floating point
1096       type or the two types have the same rank.
1097   */
1098   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1099       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1100     return false;
1101 
1102   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1103          "The remaining types must be floating point types.");
1104 
1105   auto *LHSComplex = LHSType->getAs<ComplexType>();
1106   auto *RHSComplex = RHSType->getAs<ComplexType>();
1107 
1108   QualType LHSElemType = LHSComplex ?
1109     LHSComplex->getElementType() : LHSType;
1110   QualType RHSElemType = RHSComplex ?
1111     RHSComplex->getElementType() : RHSType;
1112 
1113   // No issue if the two types have the same representation
1114   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1115       &S.Context.getFloatTypeSemantics(RHSElemType))
1116     return false;
1117 
1118   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1119                                 RHSElemType == S.Context.LongDoubleTy);
1120   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1121                             RHSElemType == S.Context.Float128Ty);
1122 
1123   // We've handled the situation where __float128 and long double have the same
1124   // representation. We allow all conversions for all possible long double types
1125   // except PPC's double double.
1126   return Float128AndLongDouble &&
1127     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1128      &llvm::APFloat::PPCDoubleDouble());
1129 }
1130 
1131 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1132 
1133 namespace {
1134 /// These helper callbacks are placed in an anonymous namespace to
1135 /// permit their use as function template parameters.
1136 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1137   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1138 }
1139 
1140 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1141   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1142                              CK_IntegralComplexCast);
1143 }
1144 }
1145 
1146 /// Handle integer arithmetic conversions.  Helper function of
1147 /// UsualArithmeticConversions()
1148 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1149 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1150                                         ExprResult &RHS, QualType LHSType,
1151                                         QualType RHSType, bool IsCompAssign) {
1152   // The rules for this case are in C99 6.3.1.8
1153   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1154   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1155   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1156   if (LHSSigned == RHSSigned) {
1157     // Same signedness; use the higher-ranked type
1158     if (order >= 0) {
1159       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1160       return LHSType;
1161     } else if (!IsCompAssign)
1162       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1163     return RHSType;
1164   } else if (order != (LHSSigned ? 1 : -1)) {
1165     // The unsigned type has greater than or equal rank to the
1166     // signed type, so use the unsigned type
1167     if (RHSSigned) {
1168       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1169       return LHSType;
1170     } else if (!IsCompAssign)
1171       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1172     return RHSType;
1173   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1174     // The two types are different widths; if we are here, that
1175     // means the signed type is larger than the unsigned type, so
1176     // use the signed type.
1177     if (LHSSigned) {
1178       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1179       return LHSType;
1180     } else if (!IsCompAssign)
1181       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1182     return RHSType;
1183   } else {
1184     // The signed type is higher-ranked than the unsigned type,
1185     // but isn't actually any bigger (like unsigned int and long
1186     // on most 32-bit systems).  Use the unsigned type corresponding
1187     // to the signed type.
1188     QualType result =
1189       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1190     RHS = (*doRHSCast)(S, RHS.get(), result);
1191     if (!IsCompAssign)
1192       LHS = (*doLHSCast)(S, LHS.get(), result);
1193     return result;
1194   }
1195 }
1196 
1197 /// Handle conversions with GCC complex int extension.  Helper function
1198 /// of UsualArithmeticConversions()
1199 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1200                                            ExprResult &RHS, QualType LHSType,
1201                                            QualType RHSType,
1202                                            bool IsCompAssign) {
1203   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1204   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1205 
1206   if (LHSComplexInt && RHSComplexInt) {
1207     QualType LHSEltType = LHSComplexInt->getElementType();
1208     QualType RHSEltType = RHSComplexInt->getElementType();
1209     QualType ScalarType =
1210       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1211         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1212 
1213     return S.Context.getComplexType(ScalarType);
1214   }
1215 
1216   if (LHSComplexInt) {
1217     QualType LHSEltType = LHSComplexInt->getElementType();
1218     QualType ScalarType =
1219       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1220         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1221     QualType ComplexType = S.Context.getComplexType(ScalarType);
1222     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1223                               CK_IntegralRealToComplex);
1224 
1225     return ComplexType;
1226   }
1227 
1228   assert(RHSComplexInt);
1229 
1230   QualType RHSEltType = RHSComplexInt->getElementType();
1231   QualType ScalarType =
1232     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1233       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1234   QualType ComplexType = S.Context.getComplexType(ScalarType);
1235 
1236   if (!IsCompAssign)
1237     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1238                               CK_IntegralRealToComplex);
1239   return ComplexType;
1240 }
1241 
1242 /// Return the rank of a given fixed point or integer type. The value itself
1243 /// doesn't matter, but the values must be increasing with proper increasing
1244 /// rank as described in N1169 4.1.1.
1245 static unsigned GetFixedPointRank(QualType Ty) {
1246   const auto *BTy = Ty->getAs<BuiltinType>();
1247   assert(BTy && "Expected a builtin type.");
1248 
1249   switch (BTy->getKind()) {
1250   case BuiltinType::ShortFract:
1251   case BuiltinType::UShortFract:
1252   case BuiltinType::SatShortFract:
1253   case BuiltinType::SatUShortFract:
1254     return 1;
1255   case BuiltinType::Fract:
1256   case BuiltinType::UFract:
1257   case BuiltinType::SatFract:
1258   case BuiltinType::SatUFract:
1259     return 2;
1260   case BuiltinType::LongFract:
1261   case BuiltinType::ULongFract:
1262   case BuiltinType::SatLongFract:
1263   case BuiltinType::SatULongFract:
1264     return 3;
1265   case BuiltinType::ShortAccum:
1266   case BuiltinType::UShortAccum:
1267   case BuiltinType::SatShortAccum:
1268   case BuiltinType::SatUShortAccum:
1269     return 4;
1270   case BuiltinType::Accum:
1271   case BuiltinType::UAccum:
1272   case BuiltinType::SatAccum:
1273   case BuiltinType::SatUAccum:
1274     return 5;
1275   case BuiltinType::LongAccum:
1276   case BuiltinType::ULongAccum:
1277   case BuiltinType::SatLongAccum:
1278   case BuiltinType::SatULongAccum:
1279     return 6;
1280   default:
1281     if (BTy->isInteger())
1282       return 0;
1283     llvm_unreachable("Unexpected fixed point or integer type");
1284   }
1285 }
1286 
1287 /// handleFixedPointConversion - Fixed point operations between fixed
1288 /// point types and integers or other fixed point types do not fall under
1289 /// usual arithmetic conversion since these conversions could result in loss
1290 /// of precsision (N1169 4.1.4). These operations should be calculated with
1291 /// the full precision of their result type (N1169 4.1.6.2.1).
1292 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1293                                            QualType RHSTy) {
1294   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1295          "Expected at least one of the operands to be a fixed point type");
1296   assert((LHSTy->isFixedPointOrIntegerType() ||
1297           RHSTy->isFixedPointOrIntegerType()) &&
1298          "Special fixed point arithmetic operation conversions are only "
1299          "applied to ints or other fixed point types");
1300 
1301   // If one operand has signed fixed-point type and the other operand has
1302   // unsigned fixed-point type, then the unsigned fixed-point operand is
1303   // converted to its corresponding signed fixed-point type and the resulting
1304   // type is the type of the converted operand.
1305   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1306     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1307   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1308     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1309 
1310   // The result type is the type with the highest rank, whereby a fixed-point
1311   // conversion rank is always greater than an integer conversion rank; if the
1312   // type of either of the operands is a saturating fixedpoint type, the result
1313   // type shall be the saturating fixed-point type corresponding to the type
1314   // with the highest rank; the resulting value is converted (taking into
1315   // account rounding and overflow) to the precision of the resulting type.
1316   // Same ranks between signed and unsigned types are resolved earlier, so both
1317   // types are either signed or both unsigned at this point.
1318   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1319   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1320 
1321   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1322 
1323   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1324     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1325 
1326   return ResultTy;
1327 }
1328 
1329 /// UsualArithmeticConversions - Performs various conversions that are common to
1330 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1331 /// routine returns the first non-arithmetic type found. The client is
1332 /// responsible for emitting appropriate error diagnostics.
1333 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1334                                           bool IsCompAssign) {
1335   if (!IsCompAssign) {
1336     LHS = UsualUnaryConversions(LHS.get());
1337     if (LHS.isInvalid())
1338       return QualType();
1339   }
1340 
1341   RHS = UsualUnaryConversions(RHS.get());
1342   if (RHS.isInvalid())
1343     return QualType();
1344 
1345   // For conversion purposes, we ignore any qualifiers.
1346   // For example, "const float" and "float" are equivalent.
1347   QualType LHSType =
1348     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1349   QualType RHSType =
1350     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1351 
1352   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1353   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1354     LHSType = AtomicLHS->getValueType();
1355 
1356   // If both types are identical, no conversion is needed.
1357   if (LHSType == RHSType)
1358     return LHSType;
1359 
1360   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1361   // The caller can deal with this (e.g. pointer + int).
1362   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1363     return QualType();
1364 
1365   // Apply unary and bitfield promotions to the LHS's type.
1366   QualType LHSUnpromotedType = LHSType;
1367   if (LHSType->isPromotableIntegerType())
1368     LHSType = Context.getPromotedIntegerType(LHSType);
1369   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1370   if (!LHSBitfieldPromoteTy.isNull())
1371     LHSType = LHSBitfieldPromoteTy;
1372   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1373     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1374 
1375   // If both types are identical, no conversion is needed.
1376   if (LHSType == RHSType)
1377     return LHSType;
1378 
1379   // At this point, we have two different arithmetic types.
1380 
1381   // Diagnose attempts to convert between __float128 and long double where
1382   // such conversions currently can't be handled.
1383   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1384     return QualType();
1385 
1386   // Handle complex types first (C99 6.3.1.8p1).
1387   if (LHSType->isComplexType() || RHSType->isComplexType())
1388     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1389                                         IsCompAssign);
1390 
1391   // Now handle "real" floating types (i.e. float, double, long double).
1392   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1393     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1394                                  IsCompAssign);
1395 
1396   // Handle GCC complex int extension.
1397   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1398     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1399                                       IsCompAssign);
1400 
1401   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1402     return handleFixedPointConversion(*this, LHSType, RHSType);
1403 
1404   // Finally, we have two differing integer types.
1405   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1406            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1407 }
1408 
1409 //===----------------------------------------------------------------------===//
1410 //  Semantic Analysis for various Expression Types
1411 //===----------------------------------------------------------------------===//
1412 
1413 
1414 ExprResult
1415 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1416                                 SourceLocation DefaultLoc,
1417                                 SourceLocation RParenLoc,
1418                                 Expr *ControllingExpr,
1419                                 ArrayRef<ParsedType> ArgTypes,
1420                                 ArrayRef<Expr *> ArgExprs) {
1421   unsigned NumAssocs = ArgTypes.size();
1422   assert(NumAssocs == ArgExprs.size());
1423 
1424   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1425   for (unsigned i = 0; i < NumAssocs; ++i) {
1426     if (ArgTypes[i])
1427       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1428     else
1429       Types[i] = nullptr;
1430   }
1431 
1432   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1433                                              ControllingExpr,
1434                                              llvm::makeArrayRef(Types, NumAssocs),
1435                                              ArgExprs);
1436   delete [] Types;
1437   return ER;
1438 }
1439 
1440 ExprResult
1441 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1442                                  SourceLocation DefaultLoc,
1443                                  SourceLocation RParenLoc,
1444                                  Expr *ControllingExpr,
1445                                  ArrayRef<TypeSourceInfo *> Types,
1446                                  ArrayRef<Expr *> Exprs) {
1447   unsigned NumAssocs = Types.size();
1448   assert(NumAssocs == Exprs.size());
1449 
1450   // Decay and strip qualifiers for the controlling expression type, and handle
1451   // placeholder type replacement. See committee discussion from WG14 DR423.
1452   {
1453     EnterExpressionEvaluationContext Unevaluated(
1454         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1455     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1456     if (R.isInvalid())
1457       return ExprError();
1458     ControllingExpr = R.get();
1459   }
1460 
1461   // The controlling expression is an unevaluated operand, so side effects are
1462   // likely unintended.
1463   if (!inTemplateInstantiation() &&
1464       ControllingExpr->HasSideEffects(Context, false))
1465     Diag(ControllingExpr->getExprLoc(),
1466          diag::warn_side_effects_unevaluated_context);
1467 
1468   bool TypeErrorFound = false,
1469        IsResultDependent = ControllingExpr->isTypeDependent(),
1470        ContainsUnexpandedParameterPack
1471          = ControllingExpr->containsUnexpandedParameterPack();
1472 
1473   for (unsigned i = 0; i < NumAssocs; ++i) {
1474     if (Exprs[i]->containsUnexpandedParameterPack())
1475       ContainsUnexpandedParameterPack = true;
1476 
1477     if (Types[i]) {
1478       if (Types[i]->getType()->containsUnexpandedParameterPack())
1479         ContainsUnexpandedParameterPack = true;
1480 
1481       if (Types[i]->getType()->isDependentType()) {
1482         IsResultDependent = true;
1483       } else {
1484         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1485         // complete object type other than a variably modified type."
1486         unsigned D = 0;
1487         if (Types[i]->getType()->isIncompleteType())
1488           D = diag::err_assoc_type_incomplete;
1489         else if (!Types[i]->getType()->isObjectType())
1490           D = diag::err_assoc_type_nonobject;
1491         else if (Types[i]->getType()->isVariablyModifiedType())
1492           D = diag::err_assoc_type_variably_modified;
1493 
1494         if (D != 0) {
1495           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1496             << Types[i]->getTypeLoc().getSourceRange()
1497             << Types[i]->getType();
1498           TypeErrorFound = true;
1499         }
1500 
1501         // C11 6.5.1.1p2 "No two generic associations in the same generic
1502         // selection shall specify compatible types."
1503         for (unsigned j = i+1; j < NumAssocs; ++j)
1504           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1505               Context.typesAreCompatible(Types[i]->getType(),
1506                                          Types[j]->getType())) {
1507             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1508                  diag::err_assoc_compatible_types)
1509               << Types[j]->getTypeLoc().getSourceRange()
1510               << Types[j]->getType()
1511               << Types[i]->getType();
1512             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1513                  diag::note_compat_assoc)
1514               << Types[i]->getTypeLoc().getSourceRange()
1515               << Types[i]->getType();
1516             TypeErrorFound = true;
1517           }
1518       }
1519     }
1520   }
1521   if (TypeErrorFound)
1522     return ExprError();
1523 
1524   // If we determined that the generic selection is result-dependent, don't
1525   // try to compute the result expression.
1526   if (IsResultDependent)
1527     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1528                                         Exprs, DefaultLoc, RParenLoc,
1529                                         ContainsUnexpandedParameterPack);
1530 
1531   SmallVector<unsigned, 1> CompatIndices;
1532   unsigned DefaultIndex = -1U;
1533   for (unsigned i = 0; i < NumAssocs; ++i) {
1534     if (!Types[i])
1535       DefaultIndex = i;
1536     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1537                                         Types[i]->getType()))
1538       CompatIndices.push_back(i);
1539   }
1540 
1541   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1542   // type compatible with at most one of the types named in its generic
1543   // association list."
1544   if (CompatIndices.size() > 1) {
1545     // We strip parens here because the controlling expression is typically
1546     // parenthesized in macro definitions.
1547     ControllingExpr = ControllingExpr->IgnoreParens();
1548     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1549         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1550         << (unsigned)CompatIndices.size();
1551     for (unsigned I : CompatIndices) {
1552       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1553            diag::note_compat_assoc)
1554         << Types[I]->getTypeLoc().getSourceRange()
1555         << Types[I]->getType();
1556     }
1557     return ExprError();
1558   }
1559 
1560   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1561   // its controlling expression shall have type compatible with exactly one of
1562   // the types named in its generic association list."
1563   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1564     // We strip parens here because the controlling expression is typically
1565     // parenthesized in macro definitions.
1566     ControllingExpr = ControllingExpr->IgnoreParens();
1567     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1568         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1569     return ExprError();
1570   }
1571 
1572   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1573   // type name that is compatible with the type of the controlling expression,
1574   // then the result expression of the generic selection is the expression
1575   // in that generic association. Otherwise, the result expression of the
1576   // generic selection is the expression in the default generic association."
1577   unsigned ResultIndex =
1578     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1579 
1580   return GenericSelectionExpr::Create(
1581       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1582       ContainsUnexpandedParameterPack, ResultIndex);
1583 }
1584 
1585 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1586 /// location of the token and the offset of the ud-suffix within it.
1587 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1588                                      unsigned Offset) {
1589   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1590                                         S.getLangOpts());
1591 }
1592 
1593 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1594 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1595 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1596                                                  IdentifierInfo *UDSuffix,
1597                                                  SourceLocation UDSuffixLoc,
1598                                                  ArrayRef<Expr*> Args,
1599                                                  SourceLocation LitEndLoc) {
1600   assert(Args.size() <= 2 && "too many arguments for literal operator");
1601 
1602   QualType ArgTy[2];
1603   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1604     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1605     if (ArgTy[ArgIdx]->isArrayType())
1606       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1607   }
1608 
1609   DeclarationName OpName =
1610     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1611   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1612   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1613 
1614   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1615   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1616                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1617                               /*AllowStringTemplate*/ false,
1618                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1619     return ExprError();
1620 
1621   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1622 }
1623 
1624 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1625 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1626 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1627 /// multiple tokens.  However, the common case is that StringToks points to one
1628 /// string.
1629 ///
1630 ExprResult
1631 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1632   assert(!StringToks.empty() && "Must have at least one string!");
1633 
1634   StringLiteralParser Literal(StringToks, PP);
1635   if (Literal.hadError)
1636     return ExprError();
1637 
1638   SmallVector<SourceLocation, 4> StringTokLocs;
1639   for (const Token &Tok : StringToks)
1640     StringTokLocs.push_back(Tok.getLocation());
1641 
1642   QualType CharTy = Context.CharTy;
1643   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1644   if (Literal.isWide()) {
1645     CharTy = Context.getWideCharType();
1646     Kind = StringLiteral::Wide;
1647   } else if (Literal.isUTF8()) {
1648     if (getLangOpts().Char8)
1649       CharTy = Context.Char8Ty;
1650     Kind = StringLiteral::UTF8;
1651   } else if (Literal.isUTF16()) {
1652     CharTy = Context.Char16Ty;
1653     Kind = StringLiteral::UTF16;
1654   } else if (Literal.isUTF32()) {
1655     CharTy = Context.Char32Ty;
1656     Kind = StringLiteral::UTF32;
1657   } else if (Literal.isPascal()) {
1658     CharTy = Context.UnsignedCharTy;
1659   }
1660 
1661   // Warn on initializing an array of char from a u8 string literal; this
1662   // becomes ill-formed in C++2a.
1663   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1664       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1665     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1666 
1667     // Create removals for all 'u8' prefixes in the string literal(s). This
1668     // ensures C++2a compatibility (but may change the program behavior when
1669     // built by non-Clang compilers for which the execution character set is
1670     // not always UTF-8).
1671     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1672     SourceLocation RemovalDiagLoc;
1673     for (const Token &Tok : StringToks) {
1674       if (Tok.getKind() == tok::utf8_string_literal) {
1675         if (RemovalDiagLoc.isInvalid())
1676           RemovalDiagLoc = Tok.getLocation();
1677         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1678             Tok.getLocation(),
1679             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1680                                            getSourceManager(), getLangOpts())));
1681       }
1682     }
1683     Diag(RemovalDiagLoc, RemovalDiag);
1684   }
1685 
1686 
1687   QualType CharTyConst = CharTy;
1688   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1689   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1690     CharTyConst.addConst();
1691 
1692   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1693 
1694   // Get an array type for the string, according to C99 6.4.5.  This includes
1695   // the nul terminator character as well as the string length for pascal
1696   // strings.
1697   QualType StrTy = Context.getConstantArrayType(
1698       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1699       ArrayType::Normal, 0);
1700 
1701   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1702   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1703                                              Kind, Literal.Pascal, StrTy,
1704                                              &StringTokLocs[0],
1705                                              StringTokLocs.size());
1706   if (Literal.getUDSuffix().empty())
1707     return Lit;
1708 
1709   // We're building a user-defined literal.
1710   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1711   SourceLocation UDSuffixLoc =
1712     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1713                    Literal.getUDSuffixOffset());
1714 
1715   // Make sure we're allowed user-defined literals here.
1716   if (!UDLScope)
1717     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1718 
1719   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1720   //   operator "" X (str, len)
1721   QualType SizeType = Context.getSizeType();
1722 
1723   DeclarationName OpName =
1724     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1725   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1726   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1727 
1728   QualType ArgTy[] = {
1729     Context.getArrayDecayedType(StrTy), SizeType
1730   };
1731 
1732   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1733   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1734                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1735                                 /*AllowStringTemplate*/ true,
1736                                 /*DiagnoseMissing*/ true)) {
1737 
1738   case LOLR_Cooked: {
1739     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1740     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1741                                                     StringTokLocs[0]);
1742     Expr *Args[] = { Lit, LenArg };
1743 
1744     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1745   }
1746 
1747   case LOLR_StringTemplate: {
1748     TemplateArgumentListInfo ExplicitArgs;
1749 
1750     unsigned CharBits = Context.getIntWidth(CharTy);
1751     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1752     llvm::APSInt Value(CharBits, CharIsUnsigned);
1753 
1754     TemplateArgument TypeArg(CharTy);
1755     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1756     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1757 
1758     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1759       Value = Lit->getCodeUnit(I);
1760       TemplateArgument Arg(Context, Value, CharTy);
1761       TemplateArgumentLocInfo ArgInfo;
1762       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1763     }
1764     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1765                                     &ExplicitArgs);
1766   }
1767   case LOLR_Raw:
1768   case LOLR_Template:
1769   case LOLR_ErrorNoDiagnostic:
1770     llvm_unreachable("unexpected literal operator lookup result");
1771   case LOLR_Error:
1772     return ExprError();
1773   }
1774   llvm_unreachable("unexpected literal operator lookup result");
1775 }
1776 
1777 ExprResult
1778 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1779                        SourceLocation Loc,
1780                        const CXXScopeSpec *SS) {
1781   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1782   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1783 }
1784 
1785 /// BuildDeclRefExpr - Build an expression that references a
1786 /// declaration that does not require a closure capture.
1787 ExprResult
1788 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1789                        const DeclarationNameInfo &NameInfo,
1790                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1791                        const TemplateArgumentListInfo *TemplateArgs) {
1792   bool RefersToCapturedVariable =
1793       isa<VarDecl>(D) &&
1794       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1795 
1796   DeclRefExpr *E;
1797   if (isa<VarTemplateSpecializationDecl>(D)) {
1798     VarTemplateSpecializationDecl *VarSpec =
1799         cast<VarTemplateSpecializationDecl>(D);
1800 
1801     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1802                                         : NestedNameSpecifierLoc(),
1803                             VarSpec->getTemplateKeywordLoc(), D,
1804                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1805                             FoundD, TemplateArgs);
1806   } else {
1807     assert(!TemplateArgs && "No template arguments for non-variable"
1808                             " template specialization references");
1809     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1810                                         : NestedNameSpecifierLoc(),
1811                             SourceLocation(), D, RefersToCapturedVariable,
1812                             NameInfo, Ty, VK, FoundD);
1813   }
1814 
1815   MarkDeclRefReferenced(E);
1816 
1817   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1818       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1819       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1820     getCurFunction()->recordUseOfWeak(E);
1821 
1822   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1823   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1824     FD = IFD->getAnonField();
1825   if (FD) {
1826     UnusedPrivateFields.remove(FD);
1827     // Just in case we're building an illegal pointer-to-member.
1828     if (FD->isBitField())
1829       E->setObjectKind(OK_BitField);
1830   }
1831 
1832   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1833   // designates a bit-field.
1834   if (auto *BD = dyn_cast<BindingDecl>(D))
1835     if (auto *BE = BD->getBinding())
1836       E->setObjectKind(BE->getObjectKind());
1837 
1838   return E;
1839 }
1840 
1841 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1842 /// possibly a list of template arguments.
1843 ///
1844 /// If this produces template arguments, it is permitted to call
1845 /// DecomposeTemplateName.
1846 ///
1847 /// This actually loses a lot of source location information for
1848 /// non-standard name kinds; we should consider preserving that in
1849 /// some way.
1850 void
1851 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1852                              TemplateArgumentListInfo &Buffer,
1853                              DeclarationNameInfo &NameInfo,
1854                              const TemplateArgumentListInfo *&TemplateArgs) {
1855   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1856     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1857     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1858 
1859     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1860                                        Id.TemplateId->NumArgs);
1861     translateTemplateArguments(TemplateArgsPtr, Buffer);
1862 
1863     TemplateName TName = Id.TemplateId->Template.get();
1864     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1865     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1866     TemplateArgs = &Buffer;
1867   } else {
1868     NameInfo = GetNameFromUnqualifiedId(Id);
1869     TemplateArgs = nullptr;
1870   }
1871 }
1872 
1873 static void emitEmptyLookupTypoDiagnostic(
1874     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1875     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1876     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1877   DeclContext *Ctx =
1878       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1879   if (!TC) {
1880     // Emit a special diagnostic for failed member lookups.
1881     // FIXME: computing the declaration context might fail here (?)
1882     if (Ctx)
1883       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1884                                                  << SS.getRange();
1885     else
1886       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1887     return;
1888   }
1889 
1890   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1891   bool DroppedSpecifier =
1892       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1893   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1894                         ? diag::note_implicit_param_decl
1895                         : diag::note_previous_decl;
1896   if (!Ctx)
1897     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1898                          SemaRef.PDiag(NoteID));
1899   else
1900     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1901                                  << Typo << Ctx << DroppedSpecifier
1902                                  << SS.getRange(),
1903                          SemaRef.PDiag(NoteID));
1904 }
1905 
1906 /// Diagnose an empty lookup.
1907 ///
1908 /// \return false if new lookup candidates were found
1909 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1910                                CorrectionCandidateCallback &CCC,
1911                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1912                                ArrayRef<Expr *> Args, TypoExpr **Out) {
1913   DeclarationName Name = R.getLookupName();
1914 
1915   unsigned diagnostic = diag::err_undeclared_var_use;
1916   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1917   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1918       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1919       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1920     diagnostic = diag::err_undeclared_use;
1921     diagnostic_suggest = diag::err_undeclared_use_suggest;
1922   }
1923 
1924   // If the original lookup was an unqualified lookup, fake an
1925   // unqualified lookup.  This is useful when (for example) the
1926   // original lookup would not have found something because it was a
1927   // dependent name.
1928   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1929   while (DC) {
1930     if (isa<CXXRecordDecl>(DC)) {
1931       LookupQualifiedName(R, DC);
1932 
1933       if (!R.empty()) {
1934         // Don't give errors about ambiguities in this lookup.
1935         R.suppressDiagnostics();
1936 
1937         // During a default argument instantiation the CurContext points
1938         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1939         // function parameter list, hence add an explicit check.
1940         bool isDefaultArgument =
1941             !CodeSynthesisContexts.empty() &&
1942             CodeSynthesisContexts.back().Kind ==
1943                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1944         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1945         bool isInstance = CurMethod &&
1946                           CurMethod->isInstance() &&
1947                           DC == CurMethod->getParent() && !isDefaultArgument;
1948 
1949         // Give a code modification hint to insert 'this->'.
1950         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1951         // Actually quite difficult!
1952         if (getLangOpts().MSVCCompat)
1953           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1954         if (isInstance) {
1955           Diag(R.getNameLoc(), diagnostic) << Name
1956             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1957           CheckCXXThisCapture(R.getNameLoc());
1958         } else {
1959           Diag(R.getNameLoc(), diagnostic) << Name;
1960         }
1961 
1962         // Do we really want to note all of these?
1963         for (NamedDecl *D : R)
1964           Diag(D->getLocation(), diag::note_dependent_var_use);
1965 
1966         // Return true if we are inside a default argument instantiation
1967         // and the found name refers to an instance member function, otherwise
1968         // the function calling DiagnoseEmptyLookup will try to create an
1969         // implicit member call and this is wrong for default argument.
1970         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1971           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1972           return true;
1973         }
1974 
1975         // Tell the callee to try to recover.
1976         return false;
1977       }
1978 
1979       R.clear();
1980     }
1981 
1982     // In Microsoft mode, if we are performing lookup from within a friend
1983     // function definition declared at class scope then we must set
1984     // DC to the lexical parent to be able to search into the parent
1985     // class.
1986     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1987         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1988         DC->getLexicalParent()->isRecord())
1989       DC = DC->getLexicalParent();
1990     else
1991       DC = DC->getParent();
1992   }
1993 
1994   // We didn't find anything, so try to correct for a typo.
1995   TypoCorrection Corrected;
1996   if (S && Out) {
1997     SourceLocation TypoLoc = R.getNameLoc();
1998     assert(!ExplicitTemplateArgs &&
1999            "Diagnosing an empty lookup with explicit template args!");
2000     *Out = CorrectTypoDelayed(
2001         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2002         [=](const TypoCorrection &TC) {
2003           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2004                                         diagnostic, diagnostic_suggest);
2005         },
2006         nullptr, CTK_ErrorRecovery);
2007     if (*Out)
2008       return true;
2009   } else if (S &&
2010              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2011                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2012     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2013     bool DroppedSpecifier =
2014         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2015     R.setLookupName(Corrected.getCorrection());
2016 
2017     bool AcceptableWithRecovery = false;
2018     bool AcceptableWithoutRecovery = false;
2019     NamedDecl *ND = Corrected.getFoundDecl();
2020     if (ND) {
2021       if (Corrected.isOverloaded()) {
2022         OverloadCandidateSet OCS(R.getNameLoc(),
2023                                  OverloadCandidateSet::CSK_Normal);
2024         OverloadCandidateSet::iterator Best;
2025         for (NamedDecl *CD : Corrected) {
2026           if (FunctionTemplateDecl *FTD =
2027                    dyn_cast<FunctionTemplateDecl>(CD))
2028             AddTemplateOverloadCandidate(
2029                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2030                 Args, OCS);
2031           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2032             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2033               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2034                                    Args, OCS);
2035         }
2036         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2037         case OR_Success:
2038           ND = Best->FoundDecl;
2039           Corrected.setCorrectionDecl(ND);
2040           break;
2041         default:
2042           // FIXME: Arbitrarily pick the first declaration for the note.
2043           Corrected.setCorrectionDecl(ND);
2044           break;
2045         }
2046       }
2047       R.addDecl(ND);
2048       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2049         CXXRecordDecl *Record = nullptr;
2050         if (Corrected.getCorrectionSpecifier()) {
2051           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2052           Record = Ty->getAsCXXRecordDecl();
2053         }
2054         if (!Record)
2055           Record = cast<CXXRecordDecl>(
2056               ND->getDeclContext()->getRedeclContext());
2057         R.setNamingClass(Record);
2058       }
2059 
2060       auto *UnderlyingND = ND->getUnderlyingDecl();
2061       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2062                                isa<FunctionTemplateDecl>(UnderlyingND);
2063       // FIXME: If we ended up with a typo for a type name or
2064       // Objective-C class name, we're in trouble because the parser
2065       // is in the wrong place to recover. Suggest the typo
2066       // correction, but don't make it a fix-it since we're not going
2067       // to recover well anyway.
2068       AcceptableWithoutRecovery =
2069           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2070     } else {
2071       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2072       // because we aren't able to recover.
2073       AcceptableWithoutRecovery = true;
2074     }
2075 
2076     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2077       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2078                             ? diag::note_implicit_param_decl
2079                             : diag::note_previous_decl;
2080       if (SS.isEmpty())
2081         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2082                      PDiag(NoteID), AcceptableWithRecovery);
2083       else
2084         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2085                                   << Name << computeDeclContext(SS, false)
2086                                   << DroppedSpecifier << SS.getRange(),
2087                      PDiag(NoteID), AcceptableWithRecovery);
2088 
2089       // Tell the callee whether to try to recover.
2090       return !AcceptableWithRecovery;
2091     }
2092   }
2093   R.clear();
2094 
2095   // Emit a special diagnostic for failed member lookups.
2096   // FIXME: computing the declaration context might fail here (?)
2097   if (!SS.isEmpty()) {
2098     Diag(R.getNameLoc(), diag::err_no_member)
2099       << Name << computeDeclContext(SS, false)
2100       << SS.getRange();
2101     return true;
2102   }
2103 
2104   // Give up, we can't recover.
2105   Diag(R.getNameLoc(), diagnostic) << Name;
2106   return true;
2107 }
2108 
2109 /// In Microsoft mode, if we are inside a template class whose parent class has
2110 /// dependent base classes, and we can't resolve an unqualified identifier, then
2111 /// assume the identifier is a member of a dependent base class.  We can only
2112 /// recover successfully in static methods, instance methods, and other contexts
2113 /// where 'this' is available.  This doesn't precisely match MSVC's
2114 /// instantiation model, but it's close enough.
2115 static Expr *
2116 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2117                                DeclarationNameInfo &NameInfo,
2118                                SourceLocation TemplateKWLoc,
2119                                const TemplateArgumentListInfo *TemplateArgs) {
2120   // Only try to recover from lookup into dependent bases in static methods or
2121   // contexts where 'this' is available.
2122   QualType ThisType = S.getCurrentThisType();
2123   const CXXRecordDecl *RD = nullptr;
2124   if (!ThisType.isNull())
2125     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2126   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2127     RD = MD->getParent();
2128   if (!RD || !RD->hasAnyDependentBases())
2129     return nullptr;
2130 
2131   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2132   // is available, suggest inserting 'this->' as a fixit.
2133   SourceLocation Loc = NameInfo.getLoc();
2134   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2135   DB << NameInfo.getName() << RD;
2136 
2137   if (!ThisType.isNull()) {
2138     DB << FixItHint::CreateInsertion(Loc, "this->");
2139     return CXXDependentScopeMemberExpr::Create(
2140         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2141         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2142         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2143   }
2144 
2145   // Synthesize a fake NNS that points to the derived class.  This will
2146   // perform name lookup during template instantiation.
2147   CXXScopeSpec SS;
2148   auto *NNS =
2149       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2150   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2151   return DependentScopeDeclRefExpr::Create(
2152       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2153       TemplateArgs);
2154 }
2155 
2156 ExprResult
2157 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2158                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2159                         bool HasTrailingLParen, bool IsAddressOfOperand,
2160                         CorrectionCandidateCallback *CCC,
2161                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2162   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2163          "cannot be direct & operand and have a trailing lparen");
2164   if (SS.isInvalid())
2165     return ExprError();
2166 
2167   TemplateArgumentListInfo TemplateArgsBuffer;
2168 
2169   // Decompose the UnqualifiedId into the following data.
2170   DeclarationNameInfo NameInfo;
2171   const TemplateArgumentListInfo *TemplateArgs;
2172   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2173 
2174   DeclarationName Name = NameInfo.getName();
2175   IdentifierInfo *II = Name.getAsIdentifierInfo();
2176   SourceLocation NameLoc = NameInfo.getLoc();
2177 
2178   if (II && II->isEditorPlaceholder()) {
2179     // FIXME: When typed placeholders are supported we can create a typed
2180     // placeholder expression node.
2181     return ExprError();
2182   }
2183 
2184   // C++ [temp.dep.expr]p3:
2185   //   An id-expression is type-dependent if it contains:
2186   //     -- an identifier that was declared with a dependent type,
2187   //        (note: handled after lookup)
2188   //     -- a template-id that is dependent,
2189   //        (note: handled in BuildTemplateIdExpr)
2190   //     -- a conversion-function-id that specifies a dependent type,
2191   //     -- a nested-name-specifier that contains a class-name that
2192   //        names a dependent type.
2193   // Determine whether this is a member of an unknown specialization;
2194   // we need to handle these differently.
2195   bool DependentID = false;
2196   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2197       Name.getCXXNameType()->isDependentType()) {
2198     DependentID = true;
2199   } else if (SS.isSet()) {
2200     if (DeclContext *DC = computeDeclContext(SS, false)) {
2201       if (RequireCompleteDeclContext(SS, DC))
2202         return ExprError();
2203     } else {
2204       DependentID = true;
2205     }
2206   }
2207 
2208   if (DependentID)
2209     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2210                                       IsAddressOfOperand, TemplateArgs);
2211 
2212   // Perform the required lookup.
2213   LookupResult R(*this, NameInfo,
2214                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2215                      ? LookupObjCImplicitSelfParam
2216                      : LookupOrdinaryName);
2217   if (TemplateKWLoc.isValid() || TemplateArgs) {
2218     // Lookup the template name again to correctly establish the context in
2219     // which it was found. This is really unfortunate as we already did the
2220     // lookup to determine that it was a template name in the first place. If
2221     // this becomes a performance hit, we can work harder to preserve those
2222     // results until we get here but it's likely not worth it.
2223     bool MemberOfUnknownSpecialization;
2224     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2225                            MemberOfUnknownSpecialization, TemplateKWLoc))
2226       return ExprError();
2227 
2228     if (MemberOfUnknownSpecialization ||
2229         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2230       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2231                                         IsAddressOfOperand, TemplateArgs);
2232   } else {
2233     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2234     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2235 
2236     // If the result might be in a dependent base class, this is a dependent
2237     // id-expression.
2238     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2239       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2240                                         IsAddressOfOperand, TemplateArgs);
2241 
2242     // If this reference is in an Objective-C method, then we need to do
2243     // some special Objective-C lookup, too.
2244     if (IvarLookupFollowUp) {
2245       ExprResult E(LookupInObjCMethod(R, S, II, true));
2246       if (E.isInvalid())
2247         return ExprError();
2248 
2249       if (Expr *Ex = E.getAs<Expr>())
2250         return Ex;
2251     }
2252   }
2253 
2254   if (R.isAmbiguous())
2255     return ExprError();
2256 
2257   // This could be an implicitly declared function reference (legal in C90,
2258   // extension in C99, forbidden in C++).
2259   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2260     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2261     if (D) R.addDecl(D);
2262   }
2263 
2264   // Determine whether this name might be a candidate for
2265   // argument-dependent lookup.
2266   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2267 
2268   if (R.empty() && !ADL) {
2269     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2270       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2271                                                    TemplateKWLoc, TemplateArgs))
2272         return E;
2273     }
2274 
2275     // Don't diagnose an empty lookup for inline assembly.
2276     if (IsInlineAsmIdentifier)
2277       return ExprError();
2278 
2279     // If this name wasn't predeclared and if this is not a function
2280     // call, diagnose the problem.
2281     TypoExpr *TE = nullptr;
2282     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2283                                                        : nullptr);
2284     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2285     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2286            "Typo correction callback misconfigured");
2287     if (CCC) {
2288       // Make sure the callback knows what the typo being diagnosed is.
2289       CCC->setTypoName(II);
2290       if (SS.isValid())
2291         CCC->setTypoNNS(SS.getScopeRep());
2292     }
2293     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2294     // a template name, but we happen to have always already looked up the name
2295     // before we get here if it must be a template name.
2296     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2297                             None, &TE)) {
2298       if (TE && KeywordReplacement) {
2299         auto &State = getTypoExprState(TE);
2300         auto BestTC = State.Consumer->getNextCorrection();
2301         if (BestTC.isKeyword()) {
2302           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2303           if (State.DiagHandler)
2304             State.DiagHandler(BestTC);
2305           KeywordReplacement->startToken();
2306           KeywordReplacement->setKind(II->getTokenID());
2307           KeywordReplacement->setIdentifierInfo(II);
2308           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2309           // Clean up the state associated with the TypoExpr, since it has
2310           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2311           clearDelayedTypo(TE);
2312           // Signal that a correction to a keyword was performed by returning a
2313           // valid-but-null ExprResult.
2314           return (Expr*)nullptr;
2315         }
2316         State.Consumer->resetCorrectionStream();
2317       }
2318       return TE ? TE : ExprError();
2319     }
2320 
2321     assert(!R.empty() &&
2322            "DiagnoseEmptyLookup returned false but added no results");
2323 
2324     // If we found an Objective-C instance variable, let
2325     // LookupInObjCMethod build the appropriate expression to
2326     // reference the ivar.
2327     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2328       R.clear();
2329       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2330       // In a hopelessly buggy code, Objective-C instance variable
2331       // lookup fails and no expression will be built to reference it.
2332       if (!E.isInvalid() && !E.get())
2333         return ExprError();
2334       return E;
2335     }
2336   }
2337 
2338   // This is guaranteed from this point on.
2339   assert(!R.empty() || ADL);
2340 
2341   // Check whether this might be a C++ implicit instance member access.
2342   // C++ [class.mfct.non-static]p3:
2343   //   When an id-expression that is not part of a class member access
2344   //   syntax and not used to form a pointer to member is used in the
2345   //   body of a non-static member function of class X, if name lookup
2346   //   resolves the name in the id-expression to a non-static non-type
2347   //   member of some class C, the id-expression is transformed into a
2348   //   class member access expression using (*this) as the
2349   //   postfix-expression to the left of the . operator.
2350   //
2351   // But we don't actually need to do this for '&' operands if R
2352   // resolved to a function or overloaded function set, because the
2353   // expression is ill-formed if it actually works out to be a
2354   // non-static member function:
2355   //
2356   // C++ [expr.ref]p4:
2357   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2358   //   [t]he expression can be used only as the left-hand operand of a
2359   //   member function call.
2360   //
2361   // There are other safeguards against such uses, but it's important
2362   // to get this right here so that we don't end up making a
2363   // spuriously dependent expression if we're inside a dependent
2364   // instance method.
2365   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2366     bool MightBeImplicitMember;
2367     if (!IsAddressOfOperand)
2368       MightBeImplicitMember = true;
2369     else if (!SS.isEmpty())
2370       MightBeImplicitMember = false;
2371     else if (R.isOverloadedResult())
2372       MightBeImplicitMember = false;
2373     else if (R.isUnresolvableResult())
2374       MightBeImplicitMember = true;
2375     else
2376       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2377                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2378                               isa<MSPropertyDecl>(R.getFoundDecl());
2379 
2380     if (MightBeImplicitMember)
2381       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2382                                              R, TemplateArgs, S);
2383   }
2384 
2385   if (TemplateArgs || TemplateKWLoc.isValid()) {
2386 
2387     // In C++1y, if this is a variable template id, then check it
2388     // in BuildTemplateIdExpr().
2389     // The single lookup result must be a variable template declaration.
2390     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2391         Id.TemplateId->Kind == TNK_Var_template) {
2392       assert(R.getAsSingle<VarTemplateDecl>() &&
2393              "There should only be one declaration found.");
2394     }
2395 
2396     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2397   }
2398 
2399   return BuildDeclarationNameExpr(SS, R, ADL);
2400 }
2401 
2402 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2403 /// declaration name, generally during template instantiation.
2404 /// There's a large number of things which don't need to be done along
2405 /// this path.
2406 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2407     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2408     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2409   DeclContext *DC = computeDeclContext(SS, false);
2410   if (!DC)
2411     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2412                                      NameInfo, /*TemplateArgs=*/nullptr);
2413 
2414   if (RequireCompleteDeclContext(SS, DC))
2415     return ExprError();
2416 
2417   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2418   LookupQualifiedName(R, DC);
2419 
2420   if (R.isAmbiguous())
2421     return ExprError();
2422 
2423   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2424     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2425                                      NameInfo, /*TemplateArgs=*/nullptr);
2426 
2427   if (R.empty()) {
2428     Diag(NameInfo.getLoc(), diag::err_no_member)
2429       << NameInfo.getName() << DC << SS.getRange();
2430     return ExprError();
2431   }
2432 
2433   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2434     // Diagnose a missing typename if this resolved unambiguously to a type in
2435     // a dependent context.  If we can recover with a type, downgrade this to
2436     // a warning in Microsoft compatibility mode.
2437     unsigned DiagID = diag::err_typename_missing;
2438     if (RecoveryTSI && getLangOpts().MSVCCompat)
2439       DiagID = diag::ext_typename_missing;
2440     SourceLocation Loc = SS.getBeginLoc();
2441     auto D = Diag(Loc, DiagID);
2442     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2443       << SourceRange(Loc, NameInfo.getEndLoc());
2444 
2445     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2446     // context.
2447     if (!RecoveryTSI)
2448       return ExprError();
2449 
2450     // Only issue the fixit if we're prepared to recover.
2451     D << FixItHint::CreateInsertion(Loc, "typename ");
2452 
2453     // Recover by pretending this was an elaborated type.
2454     QualType Ty = Context.getTypeDeclType(TD);
2455     TypeLocBuilder TLB;
2456     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2457 
2458     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2459     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2460     QTL.setElaboratedKeywordLoc(SourceLocation());
2461     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2462 
2463     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2464 
2465     return ExprEmpty();
2466   }
2467 
2468   // Defend against this resolving to an implicit member access. We usually
2469   // won't get here if this might be a legitimate a class member (we end up in
2470   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2471   // a pointer-to-member or in an unevaluated context in C++11.
2472   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2473     return BuildPossibleImplicitMemberExpr(SS,
2474                                            /*TemplateKWLoc=*/SourceLocation(),
2475                                            R, /*TemplateArgs=*/nullptr, S);
2476 
2477   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2478 }
2479 
2480 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2481 /// detected that we're currently inside an ObjC method.  Perform some
2482 /// additional lookup.
2483 ///
2484 /// Ideally, most of this would be done by lookup, but there's
2485 /// actually quite a lot of extra work involved.
2486 ///
2487 /// Returns a null sentinel to indicate trivial success.
2488 ExprResult
2489 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2490                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2491   SourceLocation Loc = Lookup.getNameLoc();
2492   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2493 
2494   // Check for error condition which is already reported.
2495   if (!CurMethod)
2496     return ExprError();
2497 
2498   // There are two cases to handle here.  1) scoped lookup could have failed,
2499   // in which case we should look for an ivar.  2) scoped lookup could have
2500   // found a decl, but that decl is outside the current instance method (i.e.
2501   // a global variable).  In these two cases, we do a lookup for an ivar with
2502   // this name, if the lookup sucedes, we replace it our current decl.
2503 
2504   // If we're in a class method, we don't normally want to look for
2505   // ivars.  But if we don't find anything else, and there's an
2506   // ivar, that's an error.
2507   bool IsClassMethod = CurMethod->isClassMethod();
2508 
2509   bool LookForIvars;
2510   if (Lookup.empty())
2511     LookForIvars = true;
2512   else if (IsClassMethod)
2513     LookForIvars = false;
2514   else
2515     LookForIvars = (Lookup.isSingleResult() &&
2516                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2517   ObjCInterfaceDecl *IFace = nullptr;
2518   if (LookForIvars) {
2519     IFace = CurMethod->getClassInterface();
2520     ObjCInterfaceDecl *ClassDeclared;
2521     ObjCIvarDecl *IV = nullptr;
2522     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2523       // Diagnose using an ivar in a class method.
2524       if (IsClassMethod)
2525         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2526                          << IV->getDeclName());
2527 
2528       // If we're referencing an invalid decl, just return this as a silent
2529       // error node.  The error diagnostic was already emitted on the decl.
2530       if (IV->isInvalidDecl())
2531         return ExprError();
2532 
2533       // Check if referencing a field with __attribute__((deprecated)).
2534       if (DiagnoseUseOfDecl(IV, Loc))
2535         return ExprError();
2536 
2537       // Diagnose the use of an ivar outside of the declaring class.
2538       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2539           !declaresSameEntity(ClassDeclared, IFace) &&
2540           !getLangOpts().DebuggerSupport)
2541         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2542 
2543       // FIXME: This should use a new expr for a direct reference, don't
2544       // turn this into Self->ivar, just return a BareIVarExpr or something.
2545       IdentifierInfo &II = Context.Idents.get("self");
2546       UnqualifiedId SelfName;
2547       SelfName.setIdentifier(&II, SourceLocation());
2548       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2549       CXXScopeSpec SelfScopeSpec;
2550       SourceLocation TemplateKWLoc;
2551       ExprResult SelfExpr =
2552           ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2553                             /*HasTrailingLParen=*/false,
2554                             /*IsAddressOfOperand=*/false);
2555       if (SelfExpr.isInvalid())
2556         return ExprError();
2557 
2558       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2559       if (SelfExpr.isInvalid())
2560         return ExprError();
2561 
2562       MarkAnyDeclReferenced(Loc, IV, true);
2563 
2564       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2565       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2566           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2567         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2568 
2569       ObjCIvarRefExpr *Result = new (Context)
2570           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2571                           IV->getLocation(), SelfExpr.get(), true, true);
2572 
2573       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2574         if (!isUnevaluatedContext() &&
2575             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2576           getCurFunction()->recordUseOfWeak(Result);
2577       }
2578       if (getLangOpts().ObjCAutoRefCount) {
2579         if (CurContext->isClosure())
2580           Diag(Loc, diag::warn_implicitly_retains_self)
2581             << FixItHint::CreateInsertion(Loc, "self->");
2582       }
2583 
2584       return Result;
2585     }
2586   } else if (CurMethod->isInstanceMethod()) {
2587     // We should warn if a local variable hides an ivar.
2588     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2589       ObjCInterfaceDecl *ClassDeclared;
2590       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2591         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2592             declaresSameEntity(IFace, ClassDeclared))
2593           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2594       }
2595     }
2596   } else if (Lookup.isSingleResult() &&
2597              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2598     // If accessing a stand-alone ivar in a class method, this is an error.
2599     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2600       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2601                        << IV->getDeclName());
2602   }
2603 
2604   if (Lookup.empty() && II && AllowBuiltinCreation) {
2605     // FIXME. Consolidate this with similar code in LookupName.
2606     if (unsigned BuiltinID = II->getBuiltinID()) {
2607       if (!(getLangOpts().CPlusPlus &&
2608             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2609         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2610                                            S, Lookup.isForRedeclaration(),
2611                                            Lookup.getNameLoc());
2612         if (D) Lookup.addDecl(D);
2613       }
2614     }
2615   }
2616   // Sentinel value saying that we didn't do anything special.
2617   return ExprResult((Expr *)nullptr);
2618 }
2619 
2620 /// Cast a base object to a member's actual type.
2621 ///
2622 /// Logically this happens in three phases:
2623 ///
2624 /// * First we cast from the base type to the naming class.
2625 ///   The naming class is the class into which we were looking
2626 ///   when we found the member;  it's the qualifier type if a
2627 ///   qualifier was provided, and otherwise it's the base type.
2628 ///
2629 /// * Next we cast from the naming class to the declaring class.
2630 ///   If the member we found was brought into a class's scope by
2631 ///   a using declaration, this is that class;  otherwise it's
2632 ///   the class declaring the member.
2633 ///
2634 /// * Finally we cast from the declaring class to the "true"
2635 ///   declaring class of the member.  This conversion does not
2636 ///   obey access control.
2637 ExprResult
2638 Sema::PerformObjectMemberConversion(Expr *From,
2639                                     NestedNameSpecifier *Qualifier,
2640                                     NamedDecl *FoundDecl,
2641                                     NamedDecl *Member) {
2642   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2643   if (!RD)
2644     return From;
2645 
2646   QualType DestRecordType;
2647   QualType DestType;
2648   QualType FromRecordType;
2649   QualType FromType = From->getType();
2650   bool PointerConversions = false;
2651   if (isa<FieldDecl>(Member)) {
2652     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2653     auto FromPtrType = FromType->getAs<PointerType>();
2654     DestRecordType = Context.getAddrSpaceQualType(
2655         DestRecordType, FromPtrType
2656                             ? FromType->getPointeeType().getAddressSpace()
2657                             : FromType.getAddressSpace());
2658 
2659     if (FromPtrType) {
2660       DestType = Context.getPointerType(DestRecordType);
2661       FromRecordType = FromPtrType->getPointeeType();
2662       PointerConversions = true;
2663     } else {
2664       DestType = DestRecordType;
2665       FromRecordType = FromType;
2666     }
2667   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2668     if (Method->isStatic())
2669       return From;
2670 
2671     DestType = Method->getThisType();
2672     DestRecordType = DestType->getPointeeType();
2673 
2674     if (FromType->getAs<PointerType>()) {
2675       FromRecordType = FromType->getPointeeType();
2676       PointerConversions = true;
2677     } else {
2678       FromRecordType = FromType;
2679       DestType = DestRecordType;
2680     }
2681   } else {
2682     // No conversion necessary.
2683     return From;
2684   }
2685 
2686   if (DestType->isDependentType() || FromType->isDependentType())
2687     return From;
2688 
2689   // If the unqualified types are the same, no conversion is necessary.
2690   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2691     return From;
2692 
2693   SourceRange FromRange = From->getSourceRange();
2694   SourceLocation FromLoc = FromRange.getBegin();
2695 
2696   ExprValueKind VK = From->getValueKind();
2697 
2698   // C++ [class.member.lookup]p8:
2699   //   [...] Ambiguities can often be resolved by qualifying a name with its
2700   //   class name.
2701   //
2702   // If the member was a qualified name and the qualified referred to a
2703   // specific base subobject type, we'll cast to that intermediate type
2704   // first and then to the object in which the member is declared. That allows
2705   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2706   //
2707   //   class Base { public: int x; };
2708   //   class Derived1 : public Base { };
2709   //   class Derived2 : public Base { };
2710   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2711   //
2712   //   void VeryDerived::f() {
2713   //     x = 17; // error: ambiguous base subobjects
2714   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2715   //   }
2716   if (Qualifier && Qualifier->getAsType()) {
2717     QualType QType = QualType(Qualifier->getAsType(), 0);
2718     assert(QType->isRecordType() && "lookup done with non-record type");
2719 
2720     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2721 
2722     // In C++98, the qualifier type doesn't actually have to be a base
2723     // type of the object type, in which case we just ignore it.
2724     // Otherwise build the appropriate casts.
2725     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2726       CXXCastPath BasePath;
2727       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2728                                        FromLoc, FromRange, &BasePath))
2729         return ExprError();
2730 
2731       if (PointerConversions)
2732         QType = Context.getPointerType(QType);
2733       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2734                                VK, &BasePath).get();
2735 
2736       FromType = QType;
2737       FromRecordType = QRecordType;
2738 
2739       // If the qualifier type was the same as the destination type,
2740       // we're done.
2741       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2742         return From;
2743     }
2744   }
2745 
2746   bool IgnoreAccess = false;
2747 
2748   // If we actually found the member through a using declaration, cast
2749   // down to the using declaration's type.
2750   //
2751   // Pointer equality is fine here because only one declaration of a
2752   // class ever has member declarations.
2753   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2754     assert(isa<UsingShadowDecl>(FoundDecl));
2755     QualType URecordType = Context.getTypeDeclType(
2756                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2757 
2758     // We only need to do this if the naming-class to declaring-class
2759     // conversion is non-trivial.
2760     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2761       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2762       CXXCastPath BasePath;
2763       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2764                                        FromLoc, FromRange, &BasePath))
2765         return ExprError();
2766 
2767       QualType UType = URecordType;
2768       if (PointerConversions)
2769         UType = Context.getPointerType(UType);
2770       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2771                                VK, &BasePath).get();
2772       FromType = UType;
2773       FromRecordType = URecordType;
2774     }
2775 
2776     // We don't do access control for the conversion from the
2777     // declaring class to the true declaring class.
2778     IgnoreAccess = true;
2779   }
2780 
2781   CXXCastPath BasePath;
2782   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2783                                    FromLoc, FromRange, &BasePath,
2784                                    IgnoreAccess))
2785     return ExprError();
2786 
2787   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2788                            VK, &BasePath);
2789 }
2790 
2791 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2792                                       const LookupResult &R,
2793                                       bool HasTrailingLParen) {
2794   // Only when used directly as the postfix-expression of a call.
2795   if (!HasTrailingLParen)
2796     return false;
2797 
2798   // Never if a scope specifier was provided.
2799   if (SS.isSet())
2800     return false;
2801 
2802   // Only in C++ or ObjC++.
2803   if (!getLangOpts().CPlusPlus)
2804     return false;
2805 
2806   // Turn off ADL when we find certain kinds of declarations during
2807   // normal lookup:
2808   for (NamedDecl *D : R) {
2809     // C++0x [basic.lookup.argdep]p3:
2810     //     -- a declaration of a class member
2811     // Since using decls preserve this property, we check this on the
2812     // original decl.
2813     if (D->isCXXClassMember())
2814       return false;
2815 
2816     // C++0x [basic.lookup.argdep]p3:
2817     //     -- a block-scope function declaration that is not a
2818     //        using-declaration
2819     // NOTE: we also trigger this for function templates (in fact, we
2820     // don't check the decl type at all, since all other decl types
2821     // turn off ADL anyway).
2822     if (isa<UsingShadowDecl>(D))
2823       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2824     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2825       return false;
2826 
2827     // C++0x [basic.lookup.argdep]p3:
2828     //     -- a declaration that is neither a function or a function
2829     //        template
2830     // And also for builtin functions.
2831     if (isa<FunctionDecl>(D)) {
2832       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2833 
2834       // But also builtin functions.
2835       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2836         return false;
2837     } else if (!isa<FunctionTemplateDecl>(D))
2838       return false;
2839   }
2840 
2841   return true;
2842 }
2843 
2844 
2845 /// Diagnoses obvious problems with the use of the given declaration
2846 /// as an expression.  This is only actually called for lookups that
2847 /// were not overloaded, and it doesn't promise that the declaration
2848 /// will in fact be used.
2849 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2850   if (D->isInvalidDecl())
2851     return true;
2852 
2853   if (isa<TypedefNameDecl>(D)) {
2854     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2855     return true;
2856   }
2857 
2858   if (isa<ObjCInterfaceDecl>(D)) {
2859     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2860     return true;
2861   }
2862 
2863   if (isa<NamespaceDecl>(D)) {
2864     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2865     return true;
2866   }
2867 
2868   return false;
2869 }
2870 
2871 // Certain multiversion types should be treated as overloaded even when there is
2872 // only one result.
2873 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2874   assert(R.isSingleResult() && "Expected only a single result");
2875   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2876   return FD &&
2877          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2878 }
2879 
2880 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2881                                           LookupResult &R, bool NeedsADL,
2882                                           bool AcceptInvalidDecl) {
2883   // If this is a single, fully-resolved result and we don't need ADL,
2884   // just build an ordinary singleton decl ref.
2885   if (!NeedsADL && R.isSingleResult() &&
2886       !R.getAsSingle<FunctionTemplateDecl>() &&
2887       !ShouldLookupResultBeMultiVersionOverload(R))
2888     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2889                                     R.getRepresentativeDecl(), nullptr,
2890                                     AcceptInvalidDecl);
2891 
2892   // We only need to check the declaration if there's exactly one
2893   // result, because in the overloaded case the results can only be
2894   // functions and function templates.
2895   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2896       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2897     return ExprError();
2898 
2899   // Otherwise, just build an unresolved lookup expression.  Suppress
2900   // any lookup-related diagnostics; we'll hash these out later, when
2901   // we've picked a target.
2902   R.suppressDiagnostics();
2903 
2904   UnresolvedLookupExpr *ULE
2905     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2906                                    SS.getWithLocInContext(Context),
2907                                    R.getLookupNameInfo(),
2908                                    NeedsADL, R.isOverloadedResult(),
2909                                    R.begin(), R.end());
2910 
2911   return ULE;
2912 }
2913 
2914 static void
2915 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2916                                    ValueDecl *var, DeclContext *DC);
2917 
2918 /// Complete semantic analysis for a reference to the given declaration.
2919 ExprResult Sema::BuildDeclarationNameExpr(
2920     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2921     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2922     bool AcceptInvalidDecl) {
2923   assert(D && "Cannot refer to a NULL declaration");
2924   assert(!isa<FunctionTemplateDecl>(D) &&
2925          "Cannot refer unambiguously to a function template");
2926 
2927   SourceLocation Loc = NameInfo.getLoc();
2928   if (CheckDeclInExpr(*this, Loc, D))
2929     return ExprError();
2930 
2931   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2932     // Specifically diagnose references to class templates that are missing
2933     // a template argument list.
2934     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2935     return ExprError();
2936   }
2937 
2938   // Make sure that we're referring to a value.
2939   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2940   if (!VD) {
2941     Diag(Loc, diag::err_ref_non_value)
2942       << D << SS.getRange();
2943     Diag(D->getLocation(), diag::note_declared_at);
2944     return ExprError();
2945   }
2946 
2947   // Check whether this declaration can be used. Note that we suppress
2948   // this check when we're going to perform argument-dependent lookup
2949   // on this function name, because this might not be the function
2950   // that overload resolution actually selects.
2951   if (DiagnoseUseOfDecl(VD, Loc))
2952     return ExprError();
2953 
2954   // Only create DeclRefExpr's for valid Decl's.
2955   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2956     return ExprError();
2957 
2958   // Handle members of anonymous structs and unions.  If we got here,
2959   // and the reference is to a class member indirect field, then this
2960   // must be the subject of a pointer-to-member expression.
2961   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2962     if (!indirectField->isCXXClassMember())
2963       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2964                                                       indirectField);
2965 
2966   {
2967     QualType type = VD->getType();
2968     if (type.isNull())
2969       return ExprError();
2970     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2971       // C++ [except.spec]p17:
2972       //   An exception-specification is considered to be needed when:
2973       //   - in an expression, the function is the unique lookup result or
2974       //     the selected member of a set of overloaded functions.
2975       ResolveExceptionSpec(Loc, FPT);
2976       type = VD->getType();
2977     }
2978     ExprValueKind valueKind = VK_RValue;
2979 
2980     switch (D->getKind()) {
2981     // Ignore all the non-ValueDecl kinds.
2982 #define ABSTRACT_DECL(kind)
2983 #define VALUE(type, base)
2984 #define DECL(type, base) \
2985     case Decl::type:
2986 #include "clang/AST/DeclNodes.inc"
2987       llvm_unreachable("invalid value decl kind");
2988 
2989     // These shouldn't make it here.
2990     case Decl::ObjCAtDefsField:
2991       llvm_unreachable("forming non-member reference to ivar?");
2992 
2993     // Enum constants are always r-values and never references.
2994     // Unresolved using declarations are dependent.
2995     case Decl::EnumConstant:
2996     case Decl::UnresolvedUsingValue:
2997     case Decl::OMPDeclareReduction:
2998     case Decl::OMPDeclareMapper:
2999       valueKind = VK_RValue;
3000       break;
3001 
3002     // Fields and indirect fields that got here must be for
3003     // pointer-to-member expressions; we just call them l-values for
3004     // internal consistency, because this subexpression doesn't really
3005     // exist in the high-level semantics.
3006     case Decl::Field:
3007     case Decl::IndirectField:
3008     case Decl::ObjCIvar:
3009       assert(getLangOpts().CPlusPlus &&
3010              "building reference to field in C?");
3011 
3012       // These can't have reference type in well-formed programs, but
3013       // for internal consistency we do this anyway.
3014       type = type.getNonReferenceType();
3015       valueKind = VK_LValue;
3016       break;
3017 
3018     // Non-type template parameters are either l-values or r-values
3019     // depending on the type.
3020     case Decl::NonTypeTemplateParm: {
3021       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3022         type = reftype->getPointeeType();
3023         valueKind = VK_LValue; // even if the parameter is an r-value reference
3024         break;
3025       }
3026 
3027       // For non-references, we need to strip qualifiers just in case
3028       // the template parameter was declared as 'const int' or whatever.
3029       valueKind = VK_RValue;
3030       type = type.getUnqualifiedType();
3031       break;
3032     }
3033 
3034     case Decl::Var:
3035     case Decl::VarTemplateSpecialization:
3036     case Decl::VarTemplatePartialSpecialization:
3037     case Decl::Decomposition:
3038     case Decl::OMPCapturedExpr:
3039       // In C, "extern void blah;" is valid and is an r-value.
3040       if (!getLangOpts().CPlusPlus &&
3041           !type.hasQualifiers() &&
3042           type->isVoidType()) {
3043         valueKind = VK_RValue;
3044         break;
3045       }
3046       LLVM_FALLTHROUGH;
3047 
3048     case Decl::ImplicitParam:
3049     case Decl::ParmVar: {
3050       // These are always l-values.
3051       valueKind = VK_LValue;
3052       type = type.getNonReferenceType();
3053 
3054       // FIXME: Does the addition of const really only apply in
3055       // potentially-evaluated contexts? Since the variable isn't actually
3056       // captured in an unevaluated context, it seems that the answer is no.
3057       if (!isUnevaluatedContext()) {
3058         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3059         if (!CapturedType.isNull())
3060           type = CapturedType;
3061       }
3062 
3063       break;
3064     }
3065 
3066     case Decl::Binding: {
3067       // These are always lvalues.
3068       valueKind = VK_LValue;
3069       type = type.getNonReferenceType();
3070       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3071       // decides how that's supposed to work.
3072       auto *BD = cast<BindingDecl>(VD);
3073       if (BD->getDeclContext()->isFunctionOrMethod() &&
3074           BD->getDeclContext() != CurContext)
3075         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3076       break;
3077     }
3078 
3079     case Decl::Function: {
3080       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3081         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3082           type = Context.BuiltinFnTy;
3083           valueKind = VK_RValue;
3084           break;
3085         }
3086       }
3087 
3088       const FunctionType *fty = type->castAs<FunctionType>();
3089 
3090       // If we're referring to a function with an __unknown_anytype
3091       // result type, make the entire expression __unknown_anytype.
3092       if (fty->getReturnType() == Context.UnknownAnyTy) {
3093         type = Context.UnknownAnyTy;
3094         valueKind = VK_RValue;
3095         break;
3096       }
3097 
3098       // Functions are l-values in C++.
3099       if (getLangOpts().CPlusPlus) {
3100         valueKind = VK_LValue;
3101         break;
3102       }
3103 
3104       // C99 DR 316 says that, if a function type comes from a
3105       // function definition (without a prototype), that type is only
3106       // used for checking compatibility. Therefore, when referencing
3107       // the function, we pretend that we don't have the full function
3108       // type.
3109       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3110           isa<FunctionProtoType>(fty))
3111         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3112                                               fty->getExtInfo());
3113 
3114       // Functions are r-values in C.
3115       valueKind = VK_RValue;
3116       break;
3117     }
3118 
3119     case Decl::CXXDeductionGuide:
3120       llvm_unreachable("building reference to deduction guide");
3121 
3122     case Decl::MSProperty:
3123       valueKind = VK_LValue;
3124       break;
3125 
3126     case Decl::CXXMethod:
3127       // If we're referring to a method with an __unknown_anytype
3128       // result type, make the entire expression __unknown_anytype.
3129       // This should only be possible with a type written directly.
3130       if (const FunctionProtoType *proto
3131             = dyn_cast<FunctionProtoType>(VD->getType()))
3132         if (proto->getReturnType() == Context.UnknownAnyTy) {
3133           type = Context.UnknownAnyTy;
3134           valueKind = VK_RValue;
3135           break;
3136         }
3137 
3138       // C++ methods are l-values if static, r-values if non-static.
3139       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3140         valueKind = VK_LValue;
3141         break;
3142       }
3143       LLVM_FALLTHROUGH;
3144 
3145     case Decl::CXXConversion:
3146     case Decl::CXXDestructor:
3147     case Decl::CXXConstructor:
3148       valueKind = VK_RValue;
3149       break;
3150     }
3151 
3152     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3153                             TemplateArgs);
3154   }
3155 }
3156 
3157 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3158                                     SmallString<32> &Target) {
3159   Target.resize(CharByteWidth * (Source.size() + 1));
3160   char *ResultPtr = &Target[0];
3161   const llvm::UTF8 *ErrorPtr;
3162   bool success =
3163       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3164   (void)success;
3165   assert(success);
3166   Target.resize(ResultPtr - &Target[0]);
3167 }
3168 
3169 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3170                                      PredefinedExpr::IdentKind IK) {
3171   // Pick the current block, lambda, captured statement or function.
3172   Decl *currentDecl = nullptr;
3173   if (const BlockScopeInfo *BSI = getCurBlock())
3174     currentDecl = BSI->TheDecl;
3175   else if (const LambdaScopeInfo *LSI = getCurLambda())
3176     currentDecl = LSI->CallOperator;
3177   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3178     currentDecl = CSI->TheCapturedDecl;
3179   else
3180     currentDecl = getCurFunctionOrMethodDecl();
3181 
3182   if (!currentDecl) {
3183     Diag(Loc, diag::ext_predef_outside_function);
3184     currentDecl = Context.getTranslationUnitDecl();
3185   }
3186 
3187   QualType ResTy;
3188   StringLiteral *SL = nullptr;
3189   if (cast<DeclContext>(currentDecl)->isDependentContext())
3190     ResTy = Context.DependentTy;
3191   else {
3192     // Pre-defined identifiers are of type char[x], where x is the length of
3193     // the string.
3194     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3195     unsigned Length = Str.length();
3196 
3197     llvm::APInt LengthI(32, Length + 1);
3198     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3199       ResTy =
3200           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3201       SmallString<32> RawChars;
3202       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3203                               Str, RawChars);
3204       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3205                                            /*IndexTypeQuals*/ 0);
3206       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3207                                  /*Pascal*/ false, ResTy, Loc);
3208     } else {
3209       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3210       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3211                                            /*IndexTypeQuals*/ 0);
3212       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3213                                  /*Pascal*/ false, ResTy, Loc);
3214     }
3215   }
3216 
3217   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3218 }
3219 
3220 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3221   PredefinedExpr::IdentKind IK;
3222 
3223   switch (Kind) {
3224   default: llvm_unreachable("Unknown simple primary expr!");
3225   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3226   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3227   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3228   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3229   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3230   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3231   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3232   }
3233 
3234   return BuildPredefinedExpr(Loc, IK);
3235 }
3236 
3237 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3238   SmallString<16> CharBuffer;
3239   bool Invalid = false;
3240   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3241   if (Invalid)
3242     return ExprError();
3243 
3244   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3245                             PP, Tok.getKind());
3246   if (Literal.hadError())
3247     return ExprError();
3248 
3249   QualType Ty;
3250   if (Literal.isWide())
3251     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3252   else if (Literal.isUTF8() && getLangOpts().Char8)
3253     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3254   else if (Literal.isUTF16())
3255     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3256   else if (Literal.isUTF32())
3257     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3258   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3259     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3260   else
3261     Ty = Context.CharTy;  // 'x' -> char in C++
3262 
3263   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3264   if (Literal.isWide())
3265     Kind = CharacterLiteral::Wide;
3266   else if (Literal.isUTF16())
3267     Kind = CharacterLiteral::UTF16;
3268   else if (Literal.isUTF32())
3269     Kind = CharacterLiteral::UTF32;
3270   else if (Literal.isUTF8())
3271     Kind = CharacterLiteral::UTF8;
3272 
3273   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3274                                              Tok.getLocation());
3275 
3276   if (Literal.getUDSuffix().empty())
3277     return Lit;
3278 
3279   // We're building a user-defined literal.
3280   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3281   SourceLocation UDSuffixLoc =
3282     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3283 
3284   // Make sure we're allowed user-defined literals here.
3285   if (!UDLScope)
3286     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3287 
3288   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3289   //   operator "" X (ch)
3290   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3291                                         Lit, Tok.getLocation());
3292 }
3293 
3294 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3295   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3296   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3297                                 Context.IntTy, Loc);
3298 }
3299 
3300 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3301                                   QualType Ty, SourceLocation Loc) {
3302   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3303 
3304   using llvm::APFloat;
3305   APFloat Val(Format);
3306 
3307   APFloat::opStatus result = Literal.GetFloatValue(Val);
3308 
3309   // Overflow is always an error, but underflow is only an error if
3310   // we underflowed to zero (APFloat reports denormals as underflow).
3311   if ((result & APFloat::opOverflow) ||
3312       ((result & APFloat::opUnderflow) && Val.isZero())) {
3313     unsigned diagnostic;
3314     SmallString<20> buffer;
3315     if (result & APFloat::opOverflow) {
3316       diagnostic = diag::warn_float_overflow;
3317       APFloat::getLargest(Format).toString(buffer);
3318     } else {
3319       diagnostic = diag::warn_float_underflow;
3320       APFloat::getSmallest(Format).toString(buffer);
3321     }
3322 
3323     S.Diag(Loc, diagnostic)
3324       << Ty
3325       << StringRef(buffer.data(), buffer.size());
3326   }
3327 
3328   bool isExact = (result == APFloat::opOK);
3329   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3330 }
3331 
3332 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3333   assert(E && "Invalid expression");
3334 
3335   if (E->isValueDependent())
3336     return false;
3337 
3338   QualType QT = E->getType();
3339   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3340     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3341     return true;
3342   }
3343 
3344   llvm::APSInt ValueAPS;
3345   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3346 
3347   if (R.isInvalid())
3348     return true;
3349 
3350   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3351   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3352     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3353         << ValueAPS.toString(10) << ValueIsPositive;
3354     return true;
3355   }
3356 
3357   return false;
3358 }
3359 
3360 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3361   // Fast path for a single digit (which is quite common).  A single digit
3362   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3363   if (Tok.getLength() == 1) {
3364     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3365     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3366   }
3367 
3368   SmallString<128> SpellingBuffer;
3369   // NumericLiteralParser wants to overread by one character.  Add padding to
3370   // the buffer in case the token is copied to the buffer.  If getSpelling()
3371   // returns a StringRef to the memory buffer, it should have a null char at
3372   // the EOF, so it is also safe.
3373   SpellingBuffer.resize(Tok.getLength() + 1);
3374 
3375   // Get the spelling of the token, which eliminates trigraphs, etc.
3376   bool Invalid = false;
3377   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3378   if (Invalid)
3379     return ExprError();
3380 
3381   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3382   if (Literal.hadError)
3383     return ExprError();
3384 
3385   if (Literal.hasUDSuffix()) {
3386     // We're building a user-defined literal.
3387     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3388     SourceLocation UDSuffixLoc =
3389       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3390 
3391     // Make sure we're allowed user-defined literals here.
3392     if (!UDLScope)
3393       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3394 
3395     QualType CookedTy;
3396     if (Literal.isFloatingLiteral()) {
3397       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3398       // long double, the literal is treated as a call of the form
3399       //   operator "" X (f L)
3400       CookedTy = Context.LongDoubleTy;
3401     } else {
3402       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3403       // unsigned long long, the literal is treated as a call of the form
3404       //   operator "" X (n ULL)
3405       CookedTy = Context.UnsignedLongLongTy;
3406     }
3407 
3408     DeclarationName OpName =
3409       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3410     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3411     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3412 
3413     SourceLocation TokLoc = Tok.getLocation();
3414 
3415     // Perform literal operator lookup to determine if we're building a raw
3416     // literal or a cooked one.
3417     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3418     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3419                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3420                                   /*AllowStringTemplate*/ false,
3421                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3422     case LOLR_ErrorNoDiagnostic:
3423       // Lookup failure for imaginary constants isn't fatal, there's still the
3424       // GNU extension producing _Complex types.
3425       break;
3426     case LOLR_Error:
3427       return ExprError();
3428     case LOLR_Cooked: {
3429       Expr *Lit;
3430       if (Literal.isFloatingLiteral()) {
3431         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3432       } else {
3433         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3434         if (Literal.GetIntegerValue(ResultVal))
3435           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3436               << /* Unsigned */ 1;
3437         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3438                                      Tok.getLocation());
3439       }
3440       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3441     }
3442 
3443     case LOLR_Raw: {
3444       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3445       // literal is treated as a call of the form
3446       //   operator "" X ("n")
3447       unsigned Length = Literal.getUDSuffixOffset();
3448       QualType StrTy = Context.getConstantArrayType(
3449           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3450           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3451       Expr *Lit = StringLiteral::Create(
3452           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3453           /*Pascal*/false, StrTy, &TokLoc, 1);
3454       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3455     }
3456 
3457     case LOLR_Template: {
3458       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3459       // template), L is treated as a call fo the form
3460       //   operator "" X <'c1', 'c2', ... 'ck'>()
3461       // where n is the source character sequence c1 c2 ... ck.
3462       TemplateArgumentListInfo ExplicitArgs;
3463       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3464       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3465       llvm::APSInt Value(CharBits, CharIsUnsigned);
3466       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3467         Value = TokSpelling[I];
3468         TemplateArgument Arg(Context, Value, Context.CharTy);
3469         TemplateArgumentLocInfo ArgInfo;
3470         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3471       }
3472       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3473                                       &ExplicitArgs);
3474     }
3475     case LOLR_StringTemplate:
3476       llvm_unreachable("unexpected literal operator lookup result");
3477     }
3478   }
3479 
3480   Expr *Res;
3481 
3482   if (Literal.isFixedPointLiteral()) {
3483     QualType Ty;
3484 
3485     if (Literal.isAccum) {
3486       if (Literal.isHalf) {
3487         Ty = Context.ShortAccumTy;
3488       } else if (Literal.isLong) {
3489         Ty = Context.LongAccumTy;
3490       } else {
3491         Ty = Context.AccumTy;
3492       }
3493     } else if (Literal.isFract) {
3494       if (Literal.isHalf) {
3495         Ty = Context.ShortFractTy;
3496       } else if (Literal.isLong) {
3497         Ty = Context.LongFractTy;
3498       } else {
3499         Ty = Context.FractTy;
3500       }
3501     }
3502 
3503     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3504 
3505     bool isSigned = !Literal.isUnsigned;
3506     unsigned scale = Context.getFixedPointScale(Ty);
3507     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3508 
3509     llvm::APInt Val(bit_width, 0, isSigned);
3510     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3511     bool ValIsZero = Val.isNullValue() && !Overflowed;
3512 
3513     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3514     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3515       // Clause 6.4.4 - The value of a constant shall be in the range of
3516       // representable values for its type, with exception for constants of a
3517       // fract type with a value of exactly 1; such a constant shall denote
3518       // the maximal value for the type.
3519       --Val;
3520     else if (Val.ugt(MaxVal) || Overflowed)
3521       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3522 
3523     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3524                                               Tok.getLocation(), scale);
3525   } else if (Literal.isFloatingLiteral()) {
3526     QualType Ty;
3527     if (Literal.isHalf){
3528       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3529         Ty = Context.HalfTy;
3530       else {
3531         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3532         return ExprError();
3533       }
3534     } else if (Literal.isFloat)
3535       Ty = Context.FloatTy;
3536     else if (Literal.isLong)
3537       Ty = Context.LongDoubleTy;
3538     else if (Literal.isFloat16)
3539       Ty = Context.Float16Ty;
3540     else if (Literal.isFloat128)
3541       Ty = Context.Float128Ty;
3542     else
3543       Ty = Context.DoubleTy;
3544 
3545     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3546 
3547     if (Ty == Context.DoubleTy) {
3548       if (getLangOpts().SinglePrecisionConstants) {
3549         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3550         if (BTy->getKind() != BuiltinType::Float) {
3551           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3552         }
3553       } else if (getLangOpts().OpenCL &&
3554                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3555         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3556         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3557         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3558       }
3559     }
3560   } else if (!Literal.isIntegerLiteral()) {
3561     return ExprError();
3562   } else {
3563     QualType Ty;
3564 
3565     // 'long long' is a C99 or C++11 feature.
3566     if (!getLangOpts().C99 && Literal.isLongLong) {
3567       if (getLangOpts().CPlusPlus)
3568         Diag(Tok.getLocation(),
3569              getLangOpts().CPlusPlus11 ?
3570              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3571       else
3572         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3573     }
3574 
3575     // Get the value in the widest-possible width.
3576     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3577     llvm::APInt ResultVal(MaxWidth, 0);
3578 
3579     if (Literal.GetIntegerValue(ResultVal)) {
3580       // If this value didn't fit into uintmax_t, error and force to ull.
3581       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3582           << /* Unsigned */ 1;
3583       Ty = Context.UnsignedLongLongTy;
3584       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3585              "long long is not intmax_t?");
3586     } else {
3587       // If this value fits into a ULL, try to figure out what else it fits into
3588       // according to the rules of C99 6.4.4.1p5.
3589 
3590       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3591       // be an unsigned int.
3592       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3593 
3594       // Check from smallest to largest, picking the smallest type we can.
3595       unsigned Width = 0;
3596 
3597       // Microsoft specific integer suffixes are explicitly sized.
3598       if (Literal.MicrosoftInteger) {
3599         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3600           Width = 8;
3601           Ty = Context.CharTy;
3602         } else {
3603           Width = Literal.MicrosoftInteger;
3604           Ty = Context.getIntTypeForBitwidth(Width,
3605                                              /*Signed=*/!Literal.isUnsigned);
3606         }
3607       }
3608 
3609       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3610         // Are int/unsigned possibilities?
3611         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3612 
3613         // Does it fit in a unsigned int?
3614         if (ResultVal.isIntN(IntSize)) {
3615           // Does it fit in a signed int?
3616           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3617             Ty = Context.IntTy;
3618           else if (AllowUnsigned)
3619             Ty = Context.UnsignedIntTy;
3620           Width = IntSize;
3621         }
3622       }
3623 
3624       // Are long/unsigned long possibilities?
3625       if (Ty.isNull() && !Literal.isLongLong) {
3626         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3627 
3628         // Does it fit in a unsigned long?
3629         if (ResultVal.isIntN(LongSize)) {
3630           // Does it fit in a signed long?
3631           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3632             Ty = Context.LongTy;
3633           else if (AllowUnsigned)
3634             Ty = Context.UnsignedLongTy;
3635           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3636           // is compatible.
3637           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3638             const unsigned LongLongSize =
3639                 Context.getTargetInfo().getLongLongWidth();
3640             Diag(Tok.getLocation(),
3641                  getLangOpts().CPlusPlus
3642                      ? Literal.isLong
3643                            ? diag::warn_old_implicitly_unsigned_long_cxx
3644                            : /*C++98 UB*/ diag::
3645                                  ext_old_implicitly_unsigned_long_cxx
3646                      : diag::warn_old_implicitly_unsigned_long)
3647                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3648                                             : /*will be ill-formed*/ 1);
3649             Ty = Context.UnsignedLongTy;
3650           }
3651           Width = LongSize;
3652         }
3653       }
3654 
3655       // Check long long if needed.
3656       if (Ty.isNull()) {
3657         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3658 
3659         // Does it fit in a unsigned long long?
3660         if (ResultVal.isIntN(LongLongSize)) {
3661           // Does it fit in a signed long long?
3662           // To be compatible with MSVC, hex integer literals ending with the
3663           // LL or i64 suffix are always signed in Microsoft mode.
3664           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3665               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3666             Ty = Context.LongLongTy;
3667           else if (AllowUnsigned)
3668             Ty = Context.UnsignedLongLongTy;
3669           Width = LongLongSize;
3670         }
3671       }
3672 
3673       // If we still couldn't decide a type, we probably have something that
3674       // does not fit in a signed long long, but has no U suffix.
3675       if (Ty.isNull()) {
3676         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3677         Ty = Context.UnsignedLongLongTy;
3678         Width = Context.getTargetInfo().getLongLongWidth();
3679       }
3680 
3681       if (ResultVal.getBitWidth() != Width)
3682         ResultVal = ResultVal.trunc(Width);
3683     }
3684     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3685   }
3686 
3687   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3688   if (Literal.isImaginary) {
3689     Res = new (Context) ImaginaryLiteral(Res,
3690                                         Context.getComplexType(Res->getType()));
3691 
3692     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3693   }
3694   return Res;
3695 }
3696 
3697 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3698   assert(E && "ActOnParenExpr() missing expr");
3699   return new (Context) ParenExpr(L, R, E);
3700 }
3701 
3702 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3703                                          SourceLocation Loc,
3704                                          SourceRange ArgRange) {
3705   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3706   // scalar or vector data type argument..."
3707   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3708   // type (C99 6.2.5p18) or void.
3709   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3710     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3711       << T << ArgRange;
3712     return true;
3713   }
3714 
3715   assert((T->isVoidType() || !T->isIncompleteType()) &&
3716          "Scalar types should always be complete");
3717   return false;
3718 }
3719 
3720 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3721                                            SourceLocation Loc,
3722                                            SourceRange ArgRange,
3723                                            UnaryExprOrTypeTrait TraitKind) {
3724   // Invalid types must be hard errors for SFINAE in C++.
3725   if (S.LangOpts.CPlusPlus)
3726     return true;
3727 
3728   // C99 6.5.3.4p1:
3729   if (T->isFunctionType() &&
3730       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3731        TraitKind == UETT_PreferredAlignOf)) {
3732     // sizeof(function)/alignof(function) is allowed as an extension.
3733     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3734       << TraitKind << ArgRange;
3735     return false;
3736   }
3737 
3738   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3739   // this is an error (OpenCL v1.1 s6.3.k)
3740   if (T->isVoidType()) {
3741     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3742                                         : diag::ext_sizeof_alignof_void_type;
3743     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3744     return false;
3745   }
3746 
3747   return true;
3748 }
3749 
3750 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3751                                              SourceLocation Loc,
3752                                              SourceRange ArgRange,
3753                                              UnaryExprOrTypeTrait TraitKind) {
3754   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3755   // runtime doesn't allow it.
3756   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3757     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3758       << T << (TraitKind == UETT_SizeOf)
3759       << ArgRange;
3760     return true;
3761   }
3762 
3763   return false;
3764 }
3765 
3766 /// Check whether E is a pointer from a decayed array type (the decayed
3767 /// pointer type is equal to T) and emit a warning if it is.
3768 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3769                                      Expr *E) {
3770   // Don't warn if the operation changed the type.
3771   if (T != E->getType())
3772     return;
3773 
3774   // Now look for array decays.
3775   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3776   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3777     return;
3778 
3779   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3780                                              << ICE->getType()
3781                                              << ICE->getSubExpr()->getType();
3782 }
3783 
3784 /// Check the constraints on expression operands to unary type expression
3785 /// and type traits.
3786 ///
3787 /// Completes any types necessary and validates the constraints on the operand
3788 /// expression. The logic mostly mirrors the type-based overload, but may modify
3789 /// the expression as it completes the type for that expression through template
3790 /// instantiation, etc.
3791 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3792                                             UnaryExprOrTypeTrait ExprKind) {
3793   QualType ExprTy = E->getType();
3794   assert(!ExprTy->isReferenceType());
3795 
3796   if (ExprKind == UETT_VecStep)
3797     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3798                                         E->getSourceRange());
3799 
3800   // Whitelist some types as extensions
3801   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3802                                       E->getSourceRange(), ExprKind))
3803     return false;
3804 
3805   // 'alignof' applied to an expression only requires the base element type of
3806   // the expression to be complete. 'sizeof' requires the expression's type to
3807   // be complete (and will attempt to complete it if it's an array of unknown
3808   // bound).
3809   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3810     if (RequireCompleteType(E->getExprLoc(),
3811                             Context.getBaseElementType(E->getType()),
3812                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3813                             E->getSourceRange()))
3814       return true;
3815   } else {
3816     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3817                                 ExprKind, E->getSourceRange()))
3818       return true;
3819   }
3820 
3821   // Completing the expression's type may have changed it.
3822   ExprTy = E->getType();
3823   assert(!ExprTy->isReferenceType());
3824 
3825   if (ExprTy->isFunctionType()) {
3826     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3827       << ExprKind << E->getSourceRange();
3828     return true;
3829   }
3830 
3831   // The operand for sizeof and alignof is in an unevaluated expression context,
3832   // so side effects could result in unintended consequences.
3833   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3834        ExprKind == UETT_PreferredAlignOf) &&
3835       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3836     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3837 
3838   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3839                                        E->getSourceRange(), ExprKind))
3840     return true;
3841 
3842   if (ExprKind == UETT_SizeOf) {
3843     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3844       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3845         QualType OType = PVD->getOriginalType();
3846         QualType Type = PVD->getType();
3847         if (Type->isPointerType() && OType->isArrayType()) {
3848           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3849             << Type << OType;
3850           Diag(PVD->getLocation(), diag::note_declared_at);
3851         }
3852       }
3853     }
3854 
3855     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3856     // decays into a pointer and returns an unintended result. This is most
3857     // likely a typo for "sizeof(array) op x".
3858     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3859       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3860                                BO->getLHS());
3861       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3862                                BO->getRHS());
3863     }
3864   }
3865 
3866   return false;
3867 }
3868 
3869 /// Check the constraints on operands to unary expression and type
3870 /// traits.
3871 ///
3872 /// This will complete any types necessary, and validate the various constraints
3873 /// on those operands.
3874 ///
3875 /// The UsualUnaryConversions() function is *not* called by this routine.
3876 /// C99 6.3.2.1p[2-4] all state:
3877 ///   Except when it is the operand of the sizeof operator ...
3878 ///
3879 /// C++ [expr.sizeof]p4
3880 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3881 ///   standard conversions are not applied to the operand of sizeof.
3882 ///
3883 /// This policy is followed for all of the unary trait expressions.
3884 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3885                                             SourceLocation OpLoc,
3886                                             SourceRange ExprRange,
3887                                             UnaryExprOrTypeTrait ExprKind) {
3888   if (ExprType->isDependentType())
3889     return false;
3890 
3891   // C++ [expr.sizeof]p2:
3892   //     When applied to a reference or a reference type, the result
3893   //     is the size of the referenced type.
3894   // C++11 [expr.alignof]p3:
3895   //     When alignof is applied to a reference type, the result
3896   //     shall be the alignment of the referenced type.
3897   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3898     ExprType = Ref->getPointeeType();
3899 
3900   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3901   //   When alignof or _Alignof is applied to an array type, the result
3902   //   is the alignment of the element type.
3903   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3904       ExprKind == UETT_OpenMPRequiredSimdAlign)
3905     ExprType = Context.getBaseElementType(ExprType);
3906 
3907   if (ExprKind == UETT_VecStep)
3908     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3909 
3910   // Whitelist some types as extensions
3911   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3912                                       ExprKind))
3913     return false;
3914 
3915   if (RequireCompleteType(OpLoc, ExprType,
3916                           diag::err_sizeof_alignof_incomplete_type,
3917                           ExprKind, ExprRange))
3918     return true;
3919 
3920   if (ExprType->isFunctionType()) {
3921     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3922       << ExprKind << ExprRange;
3923     return true;
3924   }
3925 
3926   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3927                                        ExprKind))
3928     return true;
3929 
3930   return false;
3931 }
3932 
3933 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3934   E = E->IgnoreParens();
3935 
3936   // Cannot know anything else if the expression is dependent.
3937   if (E->isTypeDependent())
3938     return false;
3939 
3940   if (E->getObjectKind() == OK_BitField) {
3941     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3942        << 1 << E->getSourceRange();
3943     return true;
3944   }
3945 
3946   ValueDecl *D = nullptr;
3947   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3948     D = DRE->getDecl();
3949   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3950     D = ME->getMemberDecl();
3951   }
3952 
3953   // If it's a field, require the containing struct to have a
3954   // complete definition so that we can compute the layout.
3955   //
3956   // This can happen in C++11 onwards, either by naming the member
3957   // in a way that is not transformed into a member access expression
3958   // (in an unevaluated operand, for instance), or by naming the member
3959   // in a trailing-return-type.
3960   //
3961   // For the record, since __alignof__ on expressions is a GCC
3962   // extension, GCC seems to permit this but always gives the
3963   // nonsensical answer 0.
3964   //
3965   // We don't really need the layout here --- we could instead just
3966   // directly check for all the appropriate alignment-lowing
3967   // attributes --- but that would require duplicating a lot of
3968   // logic that just isn't worth duplicating for such a marginal
3969   // use-case.
3970   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3971     // Fast path this check, since we at least know the record has a
3972     // definition if we can find a member of it.
3973     if (!FD->getParent()->isCompleteDefinition()) {
3974       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3975         << E->getSourceRange();
3976       return true;
3977     }
3978 
3979     // Otherwise, if it's a field, and the field doesn't have
3980     // reference type, then it must have a complete type (or be a
3981     // flexible array member, which we explicitly want to
3982     // white-list anyway), which makes the following checks trivial.
3983     if (!FD->getType()->isReferenceType())
3984       return false;
3985   }
3986 
3987   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3988 }
3989 
3990 bool Sema::CheckVecStepExpr(Expr *E) {
3991   E = E->IgnoreParens();
3992 
3993   // Cannot know anything else if the expression is dependent.
3994   if (E->isTypeDependent())
3995     return false;
3996 
3997   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3998 }
3999 
4000 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4001                                         CapturingScopeInfo *CSI) {
4002   assert(T->isVariablyModifiedType());
4003   assert(CSI != nullptr);
4004 
4005   // We're going to walk down into the type and look for VLA expressions.
4006   do {
4007     const Type *Ty = T.getTypePtr();
4008     switch (Ty->getTypeClass()) {
4009 #define TYPE(Class, Base)
4010 #define ABSTRACT_TYPE(Class, Base)
4011 #define NON_CANONICAL_TYPE(Class, Base)
4012 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4013 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4014 #include "clang/AST/TypeNodes.def"
4015       T = QualType();
4016       break;
4017     // These types are never variably-modified.
4018     case Type::Builtin:
4019     case Type::Complex:
4020     case Type::Vector:
4021     case Type::ExtVector:
4022     case Type::Record:
4023     case Type::Enum:
4024     case Type::Elaborated:
4025     case Type::TemplateSpecialization:
4026     case Type::ObjCObject:
4027     case Type::ObjCInterface:
4028     case Type::ObjCObjectPointer:
4029     case Type::ObjCTypeParam:
4030     case Type::Pipe:
4031       llvm_unreachable("type class is never variably-modified!");
4032     case Type::Adjusted:
4033       T = cast<AdjustedType>(Ty)->getOriginalType();
4034       break;
4035     case Type::Decayed:
4036       T = cast<DecayedType>(Ty)->getPointeeType();
4037       break;
4038     case Type::Pointer:
4039       T = cast<PointerType>(Ty)->getPointeeType();
4040       break;
4041     case Type::BlockPointer:
4042       T = cast<BlockPointerType>(Ty)->getPointeeType();
4043       break;
4044     case Type::LValueReference:
4045     case Type::RValueReference:
4046       T = cast<ReferenceType>(Ty)->getPointeeType();
4047       break;
4048     case Type::MemberPointer:
4049       T = cast<MemberPointerType>(Ty)->getPointeeType();
4050       break;
4051     case Type::ConstantArray:
4052     case Type::IncompleteArray:
4053       // Losing element qualification here is fine.
4054       T = cast<ArrayType>(Ty)->getElementType();
4055       break;
4056     case Type::VariableArray: {
4057       // Losing element qualification here is fine.
4058       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4059 
4060       // Unknown size indication requires no size computation.
4061       // Otherwise, evaluate and record it.
4062       if (auto Size = VAT->getSizeExpr()) {
4063         if (!CSI->isVLATypeCaptured(VAT)) {
4064           RecordDecl *CapRecord = nullptr;
4065           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
4066             CapRecord = LSI->Lambda;
4067           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
4068             CapRecord = CRSI->TheRecordDecl;
4069           }
4070           if (CapRecord) {
4071             auto ExprLoc = Size->getExprLoc();
4072             auto SizeType = Context.getSizeType();
4073             // Build the non-static data member.
4074             auto Field =
4075                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
4076                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
4077                                   /*BW*/ nullptr, /*Mutable*/ false,
4078                                   /*InitStyle*/ ICIS_NoInit);
4079             Field->setImplicit(true);
4080             Field->setAccess(AS_private);
4081             Field->setCapturedVLAType(VAT);
4082             CapRecord->addDecl(Field);
4083 
4084             CSI->addVLATypeCapture(ExprLoc, SizeType);
4085           }
4086         }
4087       }
4088       T = VAT->getElementType();
4089       break;
4090     }
4091     case Type::FunctionProto:
4092     case Type::FunctionNoProto:
4093       T = cast<FunctionType>(Ty)->getReturnType();
4094       break;
4095     case Type::Paren:
4096     case Type::TypeOf:
4097     case Type::UnaryTransform:
4098     case Type::Attributed:
4099     case Type::SubstTemplateTypeParm:
4100     case Type::PackExpansion:
4101       // Keep walking after single level desugaring.
4102       T = T.getSingleStepDesugaredType(Context);
4103       break;
4104     case Type::Typedef:
4105       T = cast<TypedefType>(Ty)->desugar();
4106       break;
4107     case Type::Decltype:
4108       T = cast<DecltypeType>(Ty)->desugar();
4109       break;
4110     case Type::Auto:
4111     case Type::DeducedTemplateSpecialization:
4112       T = cast<DeducedType>(Ty)->getDeducedType();
4113       break;
4114     case Type::TypeOfExpr:
4115       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4116       break;
4117     case Type::Atomic:
4118       T = cast<AtomicType>(Ty)->getValueType();
4119       break;
4120     }
4121   } while (!T.isNull() && T->isVariablyModifiedType());
4122 }
4123 
4124 /// Build a sizeof or alignof expression given a type operand.
4125 ExprResult
4126 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4127                                      SourceLocation OpLoc,
4128                                      UnaryExprOrTypeTrait ExprKind,
4129                                      SourceRange R) {
4130   if (!TInfo)
4131     return ExprError();
4132 
4133   QualType T = TInfo->getType();
4134 
4135   if (!T->isDependentType() &&
4136       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4137     return ExprError();
4138 
4139   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4140     if (auto *TT = T->getAs<TypedefType>()) {
4141       for (auto I = FunctionScopes.rbegin(),
4142                 E = std::prev(FunctionScopes.rend());
4143            I != E; ++I) {
4144         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4145         if (CSI == nullptr)
4146           break;
4147         DeclContext *DC = nullptr;
4148         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4149           DC = LSI->CallOperator;
4150         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4151           DC = CRSI->TheCapturedDecl;
4152         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4153           DC = BSI->TheDecl;
4154         if (DC) {
4155           if (DC->containsDecl(TT->getDecl()))
4156             break;
4157           captureVariablyModifiedType(Context, T, CSI);
4158         }
4159       }
4160     }
4161   }
4162 
4163   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4164   return new (Context) UnaryExprOrTypeTraitExpr(
4165       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4166 }
4167 
4168 /// Build a sizeof or alignof expression given an expression
4169 /// operand.
4170 ExprResult
4171 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4172                                      UnaryExprOrTypeTrait ExprKind) {
4173   ExprResult PE = CheckPlaceholderExpr(E);
4174   if (PE.isInvalid())
4175     return ExprError();
4176 
4177   E = PE.get();
4178 
4179   // Verify that the operand is valid.
4180   bool isInvalid = false;
4181   if (E->isTypeDependent()) {
4182     // Delay type-checking for type-dependent expressions.
4183   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4184     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4185   } else if (ExprKind == UETT_VecStep) {
4186     isInvalid = CheckVecStepExpr(E);
4187   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4188       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4189       isInvalid = true;
4190   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4191     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4192     isInvalid = true;
4193   } else {
4194     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4195   }
4196 
4197   if (isInvalid)
4198     return ExprError();
4199 
4200   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4201     PE = TransformToPotentiallyEvaluated(E);
4202     if (PE.isInvalid()) return ExprError();
4203     E = PE.get();
4204   }
4205 
4206   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4207   return new (Context) UnaryExprOrTypeTraitExpr(
4208       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4209 }
4210 
4211 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4212 /// expr and the same for @c alignof and @c __alignof
4213 /// Note that the ArgRange is invalid if isType is false.
4214 ExprResult
4215 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4216                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4217                                     void *TyOrEx, SourceRange ArgRange) {
4218   // If error parsing type, ignore.
4219   if (!TyOrEx) return ExprError();
4220 
4221   if (IsType) {
4222     TypeSourceInfo *TInfo;
4223     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4224     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4225   }
4226 
4227   Expr *ArgEx = (Expr *)TyOrEx;
4228   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4229   return Result;
4230 }
4231 
4232 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4233                                      bool IsReal) {
4234   if (V.get()->isTypeDependent())
4235     return S.Context.DependentTy;
4236 
4237   // _Real and _Imag are only l-values for normal l-values.
4238   if (V.get()->getObjectKind() != OK_Ordinary) {
4239     V = S.DefaultLvalueConversion(V.get());
4240     if (V.isInvalid())
4241       return QualType();
4242   }
4243 
4244   // These operators return the element type of a complex type.
4245   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4246     return CT->getElementType();
4247 
4248   // Otherwise they pass through real integer and floating point types here.
4249   if (V.get()->getType()->isArithmeticType())
4250     return V.get()->getType();
4251 
4252   // Test for placeholders.
4253   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4254   if (PR.isInvalid()) return QualType();
4255   if (PR.get() != V.get()) {
4256     V = PR;
4257     return CheckRealImagOperand(S, V, Loc, IsReal);
4258   }
4259 
4260   // Reject anything else.
4261   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4262     << (IsReal ? "__real" : "__imag");
4263   return QualType();
4264 }
4265 
4266 
4267 
4268 ExprResult
4269 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4270                           tok::TokenKind Kind, Expr *Input) {
4271   UnaryOperatorKind Opc;
4272   switch (Kind) {
4273   default: llvm_unreachable("Unknown unary op!");
4274   case tok::plusplus:   Opc = UO_PostInc; break;
4275   case tok::minusminus: Opc = UO_PostDec; break;
4276   }
4277 
4278   // Since this might is a postfix expression, get rid of ParenListExprs.
4279   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4280   if (Result.isInvalid()) return ExprError();
4281   Input = Result.get();
4282 
4283   return BuildUnaryOp(S, OpLoc, Opc, Input);
4284 }
4285 
4286 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4287 ///
4288 /// \return true on error
4289 static bool checkArithmeticOnObjCPointer(Sema &S,
4290                                          SourceLocation opLoc,
4291                                          Expr *op) {
4292   assert(op->getType()->isObjCObjectPointerType());
4293   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4294       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4295     return false;
4296 
4297   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4298     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4299     << op->getSourceRange();
4300   return true;
4301 }
4302 
4303 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4304   auto *BaseNoParens = Base->IgnoreParens();
4305   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4306     return MSProp->getPropertyDecl()->getType()->isArrayType();
4307   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4308 }
4309 
4310 ExprResult
4311 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4312                               Expr *idx, SourceLocation rbLoc) {
4313   if (base && !base->getType().isNull() &&
4314       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4315     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4316                                     /*Length=*/nullptr, rbLoc);
4317 
4318   // Since this might be a postfix expression, get rid of ParenListExprs.
4319   if (isa<ParenListExpr>(base)) {
4320     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4321     if (result.isInvalid()) return ExprError();
4322     base = result.get();
4323   }
4324 
4325   // Handle any non-overload placeholder types in the base and index
4326   // expressions.  We can't handle overloads here because the other
4327   // operand might be an overloadable type, in which case the overload
4328   // resolution for the operator overload should get the first crack
4329   // at the overload.
4330   bool IsMSPropertySubscript = false;
4331   if (base->getType()->isNonOverloadPlaceholderType()) {
4332     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4333     if (!IsMSPropertySubscript) {
4334       ExprResult result = CheckPlaceholderExpr(base);
4335       if (result.isInvalid())
4336         return ExprError();
4337       base = result.get();
4338     }
4339   }
4340   if (idx->getType()->isNonOverloadPlaceholderType()) {
4341     ExprResult result = CheckPlaceholderExpr(idx);
4342     if (result.isInvalid()) return ExprError();
4343     idx = result.get();
4344   }
4345 
4346   // Build an unanalyzed expression if either operand is type-dependent.
4347   if (getLangOpts().CPlusPlus &&
4348       (base->isTypeDependent() || idx->isTypeDependent())) {
4349     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4350                                             VK_LValue, OK_Ordinary, rbLoc);
4351   }
4352 
4353   // MSDN, property (C++)
4354   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4355   // This attribute can also be used in the declaration of an empty array in a
4356   // class or structure definition. For example:
4357   // __declspec(property(get=GetX, put=PutX)) int x[];
4358   // The above statement indicates that x[] can be used with one or more array
4359   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4360   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4361   if (IsMSPropertySubscript) {
4362     // Build MS property subscript expression if base is MS property reference
4363     // or MS property subscript.
4364     return new (Context) MSPropertySubscriptExpr(
4365         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4366   }
4367 
4368   // Use C++ overloaded-operator rules if either operand has record
4369   // type.  The spec says to do this if either type is *overloadable*,
4370   // but enum types can't declare subscript operators or conversion
4371   // operators, so there's nothing interesting for overload resolution
4372   // to do if there aren't any record types involved.
4373   //
4374   // ObjC pointers have their own subscripting logic that is not tied
4375   // to overload resolution and so should not take this path.
4376   if (getLangOpts().CPlusPlus &&
4377       (base->getType()->isRecordType() ||
4378        (!base->getType()->isObjCObjectPointerType() &&
4379         idx->getType()->isRecordType()))) {
4380     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4381   }
4382 
4383   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4384 
4385   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4386     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4387 
4388   return Res;
4389 }
4390 
4391 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4392   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4393   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4394 
4395   // For expressions like `&(*s).b`, the base is recorded and what should be
4396   // checked.
4397   const MemberExpr *Member = nullptr;
4398   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4399     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4400 
4401   LastRecord.PossibleDerefs.erase(StrippedExpr);
4402 }
4403 
4404 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4405   QualType ResultTy = E->getType();
4406   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4407 
4408   // Bail if the element is an array since it is not memory access.
4409   if (isa<ArrayType>(ResultTy))
4410     return;
4411 
4412   if (ResultTy->hasAttr(attr::NoDeref)) {
4413     LastRecord.PossibleDerefs.insert(E);
4414     return;
4415   }
4416 
4417   // Check if the base type is a pointer to a member access of a struct
4418   // marked with noderef.
4419   const Expr *Base = E->getBase();
4420   QualType BaseTy = Base->getType();
4421   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4422     // Not a pointer access
4423     return;
4424 
4425   const MemberExpr *Member = nullptr;
4426   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4427          Member->isArrow())
4428     Base = Member->getBase();
4429 
4430   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4431     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4432       LastRecord.PossibleDerefs.insert(E);
4433   }
4434 }
4435 
4436 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4437                                           Expr *LowerBound,
4438                                           SourceLocation ColonLoc, Expr *Length,
4439                                           SourceLocation RBLoc) {
4440   if (Base->getType()->isPlaceholderType() &&
4441       !Base->getType()->isSpecificPlaceholderType(
4442           BuiltinType::OMPArraySection)) {
4443     ExprResult Result = CheckPlaceholderExpr(Base);
4444     if (Result.isInvalid())
4445       return ExprError();
4446     Base = Result.get();
4447   }
4448   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4449     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4450     if (Result.isInvalid())
4451       return ExprError();
4452     Result = DefaultLvalueConversion(Result.get());
4453     if (Result.isInvalid())
4454       return ExprError();
4455     LowerBound = Result.get();
4456   }
4457   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4458     ExprResult Result = CheckPlaceholderExpr(Length);
4459     if (Result.isInvalid())
4460       return ExprError();
4461     Result = DefaultLvalueConversion(Result.get());
4462     if (Result.isInvalid())
4463       return ExprError();
4464     Length = Result.get();
4465   }
4466 
4467   // Build an unanalyzed expression if either operand is type-dependent.
4468   if (Base->isTypeDependent() ||
4469       (LowerBound &&
4470        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4471       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4472     return new (Context)
4473         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4474                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4475   }
4476 
4477   // Perform default conversions.
4478   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4479   QualType ResultTy;
4480   if (OriginalTy->isAnyPointerType()) {
4481     ResultTy = OriginalTy->getPointeeType();
4482   } else if (OriginalTy->isArrayType()) {
4483     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4484   } else {
4485     return ExprError(
4486         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4487         << Base->getSourceRange());
4488   }
4489   // C99 6.5.2.1p1
4490   if (LowerBound) {
4491     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4492                                                       LowerBound);
4493     if (Res.isInvalid())
4494       return ExprError(Diag(LowerBound->getExprLoc(),
4495                             diag::err_omp_typecheck_section_not_integer)
4496                        << 0 << LowerBound->getSourceRange());
4497     LowerBound = Res.get();
4498 
4499     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4500         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4501       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4502           << 0 << LowerBound->getSourceRange();
4503   }
4504   if (Length) {
4505     auto Res =
4506         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4507     if (Res.isInvalid())
4508       return ExprError(Diag(Length->getExprLoc(),
4509                             diag::err_omp_typecheck_section_not_integer)
4510                        << 1 << Length->getSourceRange());
4511     Length = Res.get();
4512 
4513     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4514         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4515       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4516           << 1 << Length->getSourceRange();
4517   }
4518 
4519   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4520   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4521   // type. Note that functions are not objects, and that (in C99 parlance)
4522   // incomplete types are not object types.
4523   if (ResultTy->isFunctionType()) {
4524     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4525         << ResultTy << Base->getSourceRange();
4526     return ExprError();
4527   }
4528 
4529   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4530                           diag::err_omp_section_incomplete_type, Base))
4531     return ExprError();
4532 
4533   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4534     Expr::EvalResult Result;
4535     if (LowerBound->EvaluateAsInt(Result, Context)) {
4536       // OpenMP 4.5, [2.4 Array Sections]
4537       // The array section must be a subset of the original array.
4538       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4539       if (LowerBoundValue.isNegative()) {
4540         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4541             << LowerBound->getSourceRange();
4542         return ExprError();
4543       }
4544     }
4545   }
4546 
4547   if (Length) {
4548     Expr::EvalResult Result;
4549     if (Length->EvaluateAsInt(Result, Context)) {
4550       // OpenMP 4.5, [2.4 Array Sections]
4551       // The length must evaluate to non-negative integers.
4552       llvm::APSInt LengthValue = Result.Val.getInt();
4553       if (LengthValue.isNegative()) {
4554         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4555             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4556             << Length->getSourceRange();
4557         return ExprError();
4558       }
4559     }
4560   } else if (ColonLoc.isValid() &&
4561              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4562                                       !OriginalTy->isVariableArrayType()))) {
4563     // OpenMP 4.5, [2.4 Array Sections]
4564     // When the size of the array dimension is not known, the length must be
4565     // specified explicitly.
4566     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4567         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4568     return ExprError();
4569   }
4570 
4571   if (!Base->getType()->isSpecificPlaceholderType(
4572           BuiltinType::OMPArraySection)) {
4573     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4574     if (Result.isInvalid())
4575       return ExprError();
4576     Base = Result.get();
4577   }
4578   return new (Context)
4579       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4580                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4581 }
4582 
4583 ExprResult
4584 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4585                                       Expr *Idx, SourceLocation RLoc) {
4586   Expr *LHSExp = Base;
4587   Expr *RHSExp = Idx;
4588 
4589   ExprValueKind VK = VK_LValue;
4590   ExprObjectKind OK = OK_Ordinary;
4591 
4592   // Per C++ core issue 1213, the result is an xvalue if either operand is
4593   // a non-lvalue array, and an lvalue otherwise.
4594   if (getLangOpts().CPlusPlus11) {
4595     for (auto *Op : {LHSExp, RHSExp}) {
4596       Op = Op->IgnoreImplicit();
4597       if (Op->getType()->isArrayType() && !Op->isLValue())
4598         VK = VK_XValue;
4599     }
4600   }
4601 
4602   // Perform default conversions.
4603   if (!LHSExp->getType()->getAs<VectorType>()) {
4604     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4605     if (Result.isInvalid())
4606       return ExprError();
4607     LHSExp = Result.get();
4608   }
4609   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4610   if (Result.isInvalid())
4611     return ExprError();
4612   RHSExp = Result.get();
4613 
4614   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4615 
4616   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4617   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4618   // in the subscript position. As a result, we need to derive the array base
4619   // and index from the expression types.
4620   Expr *BaseExpr, *IndexExpr;
4621   QualType ResultType;
4622   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4623     BaseExpr = LHSExp;
4624     IndexExpr = RHSExp;
4625     ResultType = Context.DependentTy;
4626   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4627     BaseExpr = LHSExp;
4628     IndexExpr = RHSExp;
4629     ResultType = PTy->getPointeeType();
4630   } else if (const ObjCObjectPointerType *PTy =
4631                LHSTy->getAs<ObjCObjectPointerType>()) {
4632     BaseExpr = LHSExp;
4633     IndexExpr = RHSExp;
4634 
4635     // Use custom logic if this should be the pseudo-object subscript
4636     // expression.
4637     if (!LangOpts.isSubscriptPointerArithmetic())
4638       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4639                                           nullptr);
4640 
4641     ResultType = PTy->getPointeeType();
4642   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4643      // Handle the uncommon case of "123[Ptr]".
4644     BaseExpr = RHSExp;
4645     IndexExpr = LHSExp;
4646     ResultType = PTy->getPointeeType();
4647   } else if (const ObjCObjectPointerType *PTy =
4648                RHSTy->getAs<ObjCObjectPointerType>()) {
4649      // Handle the uncommon case of "123[Ptr]".
4650     BaseExpr = RHSExp;
4651     IndexExpr = LHSExp;
4652     ResultType = PTy->getPointeeType();
4653     if (!LangOpts.isSubscriptPointerArithmetic()) {
4654       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4655         << ResultType << BaseExpr->getSourceRange();
4656       return ExprError();
4657     }
4658   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4659     BaseExpr = LHSExp;    // vectors: V[123]
4660     IndexExpr = RHSExp;
4661     // We apply C++ DR1213 to vector subscripting too.
4662     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4663       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4664       if (Materialized.isInvalid())
4665         return ExprError();
4666       LHSExp = Materialized.get();
4667     }
4668     VK = LHSExp->getValueKind();
4669     if (VK != VK_RValue)
4670       OK = OK_VectorComponent;
4671 
4672     ResultType = VTy->getElementType();
4673     QualType BaseType = BaseExpr->getType();
4674     Qualifiers BaseQuals = BaseType.getQualifiers();
4675     Qualifiers MemberQuals = ResultType.getQualifiers();
4676     Qualifiers Combined = BaseQuals + MemberQuals;
4677     if (Combined != MemberQuals)
4678       ResultType = Context.getQualifiedType(ResultType, Combined);
4679   } else if (LHSTy->isArrayType()) {
4680     // If we see an array that wasn't promoted by
4681     // DefaultFunctionArrayLvalueConversion, it must be an array that
4682     // wasn't promoted because of the C90 rule that doesn't
4683     // allow promoting non-lvalue arrays.  Warn, then
4684     // force the promotion here.
4685     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4686         << LHSExp->getSourceRange();
4687     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4688                                CK_ArrayToPointerDecay).get();
4689     LHSTy = LHSExp->getType();
4690 
4691     BaseExpr = LHSExp;
4692     IndexExpr = RHSExp;
4693     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4694   } else if (RHSTy->isArrayType()) {
4695     // Same as previous, except for 123[f().a] case
4696     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4697         << RHSExp->getSourceRange();
4698     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4699                                CK_ArrayToPointerDecay).get();
4700     RHSTy = RHSExp->getType();
4701 
4702     BaseExpr = RHSExp;
4703     IndexExpr = LHSExp;
4704     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4705   } else {
4706     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4707        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4708   }
4709   // C99 6.5.2.1p1
4710   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4711     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4712                      << IndexExpr->getSourceRange());
4713 
4714   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4715        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4716          && !IndexExpr->isTypeDependent())
4717     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4718 
4719   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4720   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4721   // type. Note that Functions are not objects, and that (in C99 parlance)
4722   // incomplete types are not object types.
4723   if (ResultType->isFunctionType()) {
4724     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4725         << ResultType << BaseExpr->getSourceRange();
4726     return ExprError();
4727   }
4728 
4729   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4730     // GNU extension: subscripting on pointer to void
4731     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4732       << BaseExpr->getSourceRange();
4733 
4734     // C forbids expressions of unqualified void type from being l-values.
4735     // See IsCForbiddenLValueType.
4736     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4737   } else if (!ResultType->isDependentType() &&
4738       RequireCompleteType(LLoc, ResultType,
4739                           diag::err_subscript_incomplete_type, BaseExpr))
4740     return ExprError();
4741 
4742   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4743          !ResultType.isCForbiddenLValueType());
4744 
4745   return new (Context)
4746       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4747 }
4748 
4749 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4750                                   ParmVarDecl *Param) {
4751   if (Param->hasUnparsedDefaultArg()) {
4752     Diag(CallLoc,
4753          diag::err_use_of_default_argument_to_function_declared_later) <<
4754       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4755     Diag(UnparsedDefaultArgLocs[Param],
4756          diag::note_default_argument_declared_here);
4757     return true;
4758   }
4759 
4760   if (Param->hasUninstantiatedDefaultArg()) {
4761     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4762 
4763     EnterExpressionEvaluationContext EvalContext(
4764         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4765 
4766     // Instantiate the expression.
4767     //
4768     // FIXME: Pass in a correct Pattern argument, otherwise
4769     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4770     //
4771     // template<typename T>
4772     // struct A {
4773     //   static int FooImpl();
4774     //
4775     //   template<typename Tp>
4776     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4777     //   // template argument list [[T], [Tp]], should be [[Tp]].
4778     //   friend A<Tp> Foo(int a);
4779     // };
4780     //
4781     // template<typename T>
4782     // A<T> Foo(int a = A<T>::FooImpl());
4783     MultiLevelTemplateArgumentList MutiLevelArgList
4784       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4785 
4786     InstantiatingTemplate Inst(*this, CallLoc, Param,
4787                                MutiLevelArgList.getInnermost());
4788     if (Inst.isInvalid())
4789       return true;
4790     if (Inst.isAlreadyInstantiating()) {
4791       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4792       Param->setInvalidDecl();
4793       return true;
4794     }
4795 
4796     ExprResult Result;
4797     {
4798       // C++ [dcl.fct.default]p5:
4799       //   The names in the [default argument] expression are bound, and
4800       //   the semantic constraints are checked, at the point where the
4801       //   default argument expression appears.
4802       ContextRAII SavedContext(*this, FD);
4803       LocalInstantiationScope Local(*this);
4804       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4805                                 /*DirectInit*/false);
4806     }
4807     if (Result.isInvalid())
4808       return true;
4809 
4810     // Check the expression as an initializer for the parameter.
4811     InitializedEntity Entity
4812       = InitializedEntity::InitializeParameter(Context, Param);
4813     InitializationKind Kind = InitializationKind::CreateCopy(
4814         Param->getLocation(),
4815         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4816     Expr *ResultE = Result.getAs<Expr>();
4817 
4818     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4819     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4820     if (Result.isInvalid())
4821       return true;
4822 
4823     Result =
4824         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4825                             /*DiscardedValue*/ false);
4826     if (Result.isInvalid())
4827       return true;
4828 
4829     // Remember the instantiated default argument.
4830     Param->setDefaultArg(Result.getAs<Expr>());
4831     if (ASTMutationListener *L = getASTMutationListener()) {
4832       L->DefaultArgumentInstantiated(Param);
4833     }
4834   }
4835 
4836   // If the default argument expression is not set yet, we are building it now.
4837   if (!Param->hasInit()) {
4838     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4839     Param->setInvalidDecl();
4840     return true;
4841   }
4842 
4843   // If the default expression creates temporaries, we need to
4844   // push them to the current stack of expression temporaries so they'll
4845   // be properly destroyed.
4846   // FIXME: We should really be rebuilding the default argument with new
4847   // bound temporaries; see the comment in PR5810.
4848   // We don't need to do that with block decls, though, because
4849   // blocks in default argument expression can never capture anything.
4850   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4851     // Set the "needs cleanups" bit regardless of whether there are
4852     // any explicit objects.
4853     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4854 
4855     // Append all the objects to the cleanup list.  Right now, this
4856     // should always be a no-op, because blocks in default argument
4857     // expressions should never be able to capture anything.
4858     assert(!Init->getNumObjects() &&
4859            "default argument expression has capturing blocks?");
4860   }
4861 
4862   // We already type-checked the argument, so we know it works.
4863   // Just mark all of the declarations in this potentially-evaluated expression
4864   // as being "referenced".
4865   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4866                                    /*SkipLocalVariables=*/true);
4867   return false;
4868 }
4869 
4870 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4871                                         FunctionDecl *FD, ParmVarDecl *Param) {
4872   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4873     return ExprError();
4874   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4875 }
4876 
4877 Sema::VariadicCallType
4878 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4879                           Expr *Fn) {
4880   if (Proto && Proto->isVariadic()) {
4881     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4882       return VariadicConstructor;
4883     else if (Fn && Fn->getType()->isBlockPointerType())
4884       return VariadicBlock;
4885     else if (FDecl) {
4886       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4887         if (Method->isInstance())
4888           return VariadicMethod;
4889     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4890       return VariadicMethod;
4891     return VariadicFunction;
4892   }
4893   return VariadicDoesNotApply;
4894 }
4895 
4896 namespace {
4897 class FunctionCallCCC final : public FunctionCallFilterCCC {
4898 public:
4899   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4900                   unsigned NumArgs, MemberExpr *ME)
4901       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4902         FunctionName(FuncName) {}
4903 
4904   bool ValidateCandidate(const TypoCorrection &candidate) override {
4905     if (!candidate.getCorrectionSpecifier() ||
4906         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4907       return false;
4908     }
4909 
4910     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4911   }
4912 
4913   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4914     return llvm::make_unique<FunctionCallCCC>(*this);
4915   }
4916 
4917 private:
4918   const IdentifierInfo *const FunctionName;
4919 };
4920 }
4921 
4922 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4923                                                FunctionDecl *FDecl,
4924                                                ArrayRef<Expr *> Args) {
4925   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4926   DeclarationName FuncName = FDecl->getDeclName();
4927   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4928 
4929   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4930   if (TypoCorrection Corrected = S.CorrectTypo(
4931           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4932           S.getScopeForContext(S.CurContext), nullptr, CCC,
4933           Sema::CTK_ErrorRecovery)) {
4934     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4935       if (Corrected.isOverloaded()) {
4936         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4937         OverloadCandidateSet::iterator Best;
4938         for (NamedDecl *CD : Corrected) {
4939           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4940             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4941                                    OCS);
4942         }
4943         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4944         case OR_Success:
4945           ND = Best->FoundDecl;
4946           Corrected.setCorrectionDecl(ND);
4947           break;
4948         default:
4949           break;
4950         }
4951       }
4952       ND = ND->getUnderlyingDecl();
4953       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4954         return Corrected;
4955     }
4956   }
4957   return TypoCorrection();
4958 }
4959 
4960 /// ConvertArgumentsForCall - Converts the arguments specified in
4961 /// Args/NumArgs to the parameter types of the function FDecl with
4962 /// function prototype Proto. Call is the call expression itself, and
4963 /// Fn is the function expression. For a C++ member function, this
4964 /// routine does not attempt to convert the object argument. Returns
4965 /// true if the call is ill-formed.
4966 bool
4967 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4968                               FunctionDecl *FDecl,
4969                               const FunctionProtoType *Proto,
4970                               ArrayRef<Expr *> Args,
4971                               SourceLocation RParenLoc,
4972                               bool IsExecConfig) {
4973   // Bail out early if calling a builtin with custom typechecking.
4974   if (FDecl)
4975     if (unsigned ID = FDecl->getBuiltinID())
4976       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4977         return false;
4978 
4979   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4980   // assignment, to the types of the corresponding parameter, ...
4981   unsigned NumParams = Proto->getNumParams();
4982   bool Invalid = false;
4983   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4984   unsigned FnKind = Fn->getType()->isBlockPointerType()
4985                        ? 1 /* block */
4986                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4987                                        : 0 /* function */);
4988 
4989   // If too few arguments are available (and we don't have default
4990   // arguments for the remaining parameters), don't make the call.
4991   if (Args.size() < NumParams) {
4992     if (Args.size() < MinArgs) {
4993       TypoCorrection TC;
4994       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4995         unsigned diag_id =
4996             MinArgs == NumParams && !Proto->isVariadic()
4997                 ? diag::err_typecheck_call_too_few_args_suggest
4998                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4999         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5000                                         << static_cast<unsigned>(Args.size())
5001                                         << TC.getCorrectionRange());
5002       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5003         Diag(RParenLoc,
5004              MinArgs == NumParams && !Proto->isVariadic()
5005                  ? diag::err_typecheck_call_too_few_args_one
5006                  : diag::err_typecheck_call_too_few_args_at_least_one)
5007             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5008       else
5009         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5010                             ? diag::err_typecheck_call_too_few_args
5011                             : diag::err_typecheck_call_too_few_args_at_least)
5012             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5013             << Fn->getSourceRange();
5014 
5015       // Emit the location of the prototype.
5016       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5017         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5018 
5019       return true;
5020     }
5021     // We reserve space for the default arguments when we create
5022     // the call expression, before calling ConvertArgumentsForCall.
5023     assert((Call->getNumArgs() == NumParams) &&
5024            "We should have reserved space for the default arguments before!");
5025   }
5026 
5027   // If too many are passed and not variadic, error on the extras and drop
5028   // them.
5029   if (Args.size() > NumParams) {
5030     if (!Proto->isVariadic()) {
5031       TypoCorrection TC;
5032       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5033         unsigned diag_id =
5034             MinArgs == NumParams && !Proto->isVariadic()
5035                 ? diag::err_typecheck_call_too_many_args_suggest
5036                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5037         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5038                                         << static_cast<unsigned>(Args.size())
5039                                         << TC.getCorrectionRange());
5040       } else if (NumParams == 1 && FDecl &&
5041                  FDecl->getParamDecl(0)->getDeclName())
5042         Diag(Args[NumParams]->getBeginLoc(),
5043              MinArgs == NumParams
5044                  ? diag::err_typecheck_call_too_many_args_one
5045                  : diag::err_typecheck_call_too_many_args_at_most_one)
5046             << FnKind << FDecl->getParamDecl(0)
5047             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5048             << SourceRange(Args[NumParams]->getBeginLoc(),
5049                            Args.back()->getEndLoc());
5050       else
5051         Diag(Args[NumParams]->getBeginLoc(),
5052              MinArgs == NumParams
5053                  ? diag::err_typecheck_call_too_many_args
5054                  : diag::err_typecheck_call_too_many_args_at_most)
5055             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5056             << Fn->getSourceRange()
5057             << SourceRange(Args[NumParams]->getBeginLoc(),
5058                            Args.back()->getEndLoc());
5059 
5060       // Emit the location of the prototype.
5061       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5062         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5063 
5064       // This deletes the extra arguments.
5065       Call->shrinkNumArgs(NumParams);
5066       return true;
5067     }
5068   }
5069   SmallVector<Expr *, 8> AllArgs;
5070   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5071 
5072   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5073                                    AllArgs, CallType);
5074   if (Invalid)
5075     return true;
5076   unsigned TotalNumArgs = AllArgs.size();
5077   for (unsigned i = 0; i < TotalNumArgs; ++i)
5078     Call->setArg(i, AllArgs[i]);
5079 
5080   return false;
5081 }
5082 
5083 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5084                                   const FunctionProtoType *Proto,
5085                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5086                                   SmallVectorImpl<Expr *> &AllArgs,
5087                                   VariadicCallType CallType, bool AllowExplicit,
5088                                   bool IsListInitialization) {
5089   unsigned NumParams = Proto->getNumParams();
5090   bool Invalid = false;
5091   size_t ArgIx = 0;
5092   // Continue to check argument types (even if we have too few/many args).
5093   for (unsigned i = FirstParam; i < NumParams; i++) {
5094     QualType ProtoArgType = Proto->getParamType(i);
5095 
5096     Expr *Arg;
5097     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5098     if (ArgIx < Args.size()) {
5099       Arg = Args[ArgIx++];
5100 
5101       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5102                               diag::err_call_incomplete_argument, Arg))
5103         return true;
5104 
5105       // Strip the unbridged-cast placeholder expression off, if applicable.
5106       bool CFAudited = false;
5107       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5108           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5109           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5110         Arg = stripARCUnbridgedCast(Arg);
5111       else if (getLangOpts().ObjCAutoRefCount &&
5112                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5113                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5114         CFAudited = true;
5115 
5116       if (Proto->getExtParameterInfo(i).isNoEscape())
5117         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5118           BE->getBlockDecl()->setDoesNotEscape();
5119 
5120       InitializedEntity Entity =
5121           Param ? InitializedEntity::InitializeParameter(Context, Param,
5122                                                          ProtoArgType)
5123                 : InitializedEntity::InitializeParameter(
5124                       Context, ProtoArgType, Proto->isParamConsumed(i));
5125 
5126       // Remember that parameter belongs to a CF audited API.
5127       if (CFAudited)
5128         Entity.setParameterCFAudited();
5129 
5130       ExprResult ArgE = PerformCopyInitialization(
5131           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5132       if (ArgE.isInvalid())
5133         return true;
5134 
5135       Arg = ArgE.getAs<Expr>();
5136     } else {
5137       assert(Param && "can't use default arguments without a known callee");
5138 
5139       ExprResult ArgExpr =
5140         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5141       if (ArgExpr.isInvalid())
5142         return true;
5143 
5144       Arg = ArgExpr.getAs<Expr>();
5145     }
5146 
5147     // Check for array bounds violations for each argument to the call. This
5148     // check only triggers warnings when the argument isn't a more complex Expr
5149     // with its own checking, such as a BinaryOperator.
5150     CheckArrayAccess(Arg);
5151 
5152     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5153     CheckStaticArrayArgument(CallLoc, Param, Arg);
5154 
5155     AllArgs.push_back(Arg);
5156   }
5157 
5158   // If this is a variadic call, handle args passed through "...".
5159   if (CallType != VariadicDoesNotApply) {
5160     // Assume that extern "C" functions with variadic arguments that
5161     // return __unknown_anytype aren't *really* variadic.
5162     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5163         FDecl->isExternC()) {
5164       for (Expr *A : Args.slice(ArgIx)) {
5165         QualType paramType; // ignored
5166         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5167         Invalid |= arg.isInvalid();
5168         AllArgs.push_back(arg.get());
5169       }
5170 
5171     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5172     } else {
5173       for (Expr *A : Args.slice(ArgIx)) {
5174         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5175         Invalid |= Arg.isInvalid();
5176         AllArgs.push_back(Arg.get());
5177       }
5178     }
5179 
5180     // Check for array bounds violations.
5181     for (Expr *A : Args.slice(ArgIx))
5182       CheckArrayAccess(A);
5183   }
5184   return Invalid;
5185 }
5186 
5187 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5188   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5189   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5190     TL = DTL.getOriginalLoc();
5191   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5192     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5193       << ATL.getLocalSourceRange();
5194 }
5195 
5196 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5197 /// array parameter, check that it is non-null, and that if it is formed by
5198 /// array-to-pointer decay, the underlying array is sufficiently large.
5199 ///
5200 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5201 /// array type derivation, then for each call to the function, the value of the
5202 /// corresponding actual argument shall provide access to the first element of
5203 /// an array with at least as many elements as specified by the size expression.
5204 void
5205 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5206                                ParmVarDecl *Param,
5207                                const Expr *ArgExpr) {
5208   // Static array parameters are not supported in C++.
5209   if (!Param || getLangOpts().CPlusPlus)
5210     return;
5211 
5212   QualType OrigTy = Param->getOriginalType();
5213 
5214   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5215   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5216     return;
5217 
5218   if (ArgExpr->isNullPointerConstant(Context,
5219                                      Expr::NPC_NeverValueDependent)) {
5220     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5221     DiagnoseCalleeStaticArrayParam(*this, Param);
5222     return;
5223   }
5224 
5225   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5226   if (!CAT)
5227     return;
5228 
5229   const ConstantArrayType *ArgCAT =
5230     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5231   if (!ArgCAT)
5232     return;
5233 
5234   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5235                                              ArgCAT->getElementType())) {
5236     if (ArgCAT->getSize().ult(CAT->getSize())) {
5237       Diag(CallLoc, diag::warn_static_array_too_small)
5238           << ArgExpr->getSourceRange()
5239           << (unsigned)ArgCAT->getSize().getZExtValue()
5240           << (unsigned)CAT->getSize().getZExtValue() << 0;
5241       DiagnoseCalleeStaticArrayParam(*this, Param);
5242     }
5243     return;
5244   }
5245 
5246   Optional<CharUnits> ArgSize =
5247       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5248   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5249   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5250     Diag(CallLoc, diag::warn_static_array_too_small)
5251         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5252         << (unsigned)ParmSize->getQuantity() << 1;
5253     DiagnoseCalleeStaticArrayParam(*this, Param);
5254   }
5255 }
5256 
5257 /// Given a function expression of unknown-any type, try to rebuild it
5258 /// to have a function type.
5259 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5260 
5261 /// Is the given type a placeholder that we need to lower out
5262 /// immediately during argument processing?
5263 static bool isPlaceholderToRemoveAsArg(QualType type) {
5264   // Placeholders are never sugared.
5265   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5266   if (!placeholder) return false;
5267 
5268   switch (placeholder->getKind()) {
5269   // Ignore all the non-placeholder types.
5270 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5271   case BuiltinType::Id:
5272 #include "clang/Basic/OpenCLImageTypes.def"
5273 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5274   case BuiltinType::Id:
5275 #include "clang/Basic/OpenCLExtensionTypes.def"
5276 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5277 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5278 #include "clang/AST/BuiltinTypes.def"
5279     return false;
5280 
5281   // We cannot lower out overload sets; they might validly be resolved
5282   // by the call machinery.
5283   case BuiltinType::Overload:
5284     return false;
5285 
5286   // Unbridged casts in ARC can be handled in some call positions and
5287   // should be left in place.
5288   case BuiltinType::ARCUnbridgedCast:
5289     return false;
5290 
5291   // Pseudo-objects should be converted as soon as possible.
5292   case BuiltinType::PseudoObject:
5293     return true;
5294 
5295   // The debugger mode could theoretically but currently does not try
5296   // to resolve unknown-typed arguments based on known parameter types.
5297   case BuiltinType::UnknownAny:
5298     return true;
5299 
5300   // These are always invalid as call arguments and should be reported.
5301   case BuiltinType::BoundMember:
5302   case BuiltinType::BuiltinFn:
5303   case BuiltinType::OMPArraySection:
5304     return true;
5305 
5306   }
5307   llvm_unreachable("bad builtin type kind");
5308 }
5309 
5310 /// Check an argument list for placeholders that we won't try to
5311 /// handle later.
5312 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5313   // Apply this processing to all the arguments at once instead of
5314   // dying at the first failure.
5315   bool hasInvalid = false;
5316   for (size_t i = 0, e = args.size(); i != e; i++) {
5317     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5318       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5319       if (result.isInvalid()) hasInvalid = true;
5320       else args[i] = result.get();
5321     } else if (hasInvalid) {
5322       (void)S.CorrectDelayedTyposInExpr(args[i]);
5323     }
5324   }
5325   return hasInvalid;
5326 }
5327 
5328 /// If a builtin function has a pointer argument with no explicit address
5329 /// space, then it should be able to accept a pointer to any address
5330 /// space as input.  In order to do this, we need to replace the
5331 /// standard builtin declaration with one that uses the same address space
5332 /// as the call.
5333 ///
5334 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5335 ///                  it does not contain any pointer arguments without
5336 ///                  an address space qualifer.  Otherwise the rewritten
5337 ///                  FunctionDecl is returned.
5338 /// TODO: Handle pointer return types.
5339 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5340                                                 const FunctionDecl *FDecl,
5341                                                 MultiExprArg ArgExprs) {
5342 
5343   QualType DeclType = FDecl->getType();
5344   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5345 
5346   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5347       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5348     return nullptr;
5349 
5350   bool NeedsNewDecl = false;
5351   unsigned i = 0;
5352   SmallVector<QualType, 8> OverloadParams;
5353 
5354   for (QualType ParamType : FT->param_types()) {
5355 
5356     // Convert array arguments to pointer to simplify type lookup.
5357     ExprResult ArgRes =
5358         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5359     if (ArgRes.isInvalid())
5360       return nullptr;
5361     Expr *Arg = ArgRes.get();
5362     QualType ArgType = Arg->getType();
5363     if (!ParamType->isPointerType() ||
5364         ParamType.getQualifiers().hasAddressSpace() ||
5365         !ArgType->isPointerType() ||
5366         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5367       OverloadParams.push_back(ParamType);
5368       continue;
5369     }
5370 
5371     QualType PointeeType = ParamType->getPointeeType();
5372     if (PointeeType.getQualifiers().hasAddressSpace())
5373       continue;
5374 
5375     NeedsNewDecl = true;
5376     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5377 
5378     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5379     OverloadParams.push_back(Context.getPointerType(PointeeType));
5380   }
5381 
5382   if (!NeedsNewDecl)
5383     return nullptr;
5384 
5385   FunctionProtoType::ExtProtoInfo EPI;
5386   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5387                                                 OverloadParams, EPI);
5388   DeclContext *Parent = Context.getTranslationUnitDecl();
5389   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5390                                                     FDecl->getLocation(),
5391                                                     FDecl->getLocation(),
5392                                                     FDecl->getIdentifier(),
5393                                                     OverloadTy,
5394                                                     /*TInfo=*/nullptr,
5395                                                     SC_Extern, false,
5396                                                     /*hasPrototype=*/true);
5397   SmallVector<ParmVarDecl*, 16> Params;
5398   FT = cast<FunctionProtoType>(OverloadTy);
5399   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5400     QualType ParamType = FT->getParamType(i);
5401     ParmVarDecl *Parm =
5402         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5403                                 SourceLocation(), nullptr, ParamType,
5404                                 /*TInfo=*/nullptr, SC_None, nullptr);
5405     Parm->setScopeInfo(0, i);
5406     Params.push_back(Parm);
5407   }
5408   OverloadDecl->setParams(Params);
5409   return OverloadDecl;
5410 }
5411 
5412 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5413                                     FunctionDecl *Callee,
5414                                     MultiExprArg ArgExprs) {
5415   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5416   // similar attributes) really don't like it when functions are called with an
5417   // invalid number of args.
5418   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5419                          /*PartialOverloading=*/false) &&
5420       !Callee->isVariadic())
5421     return;
5422   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5423     return;
5424 
5425   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5426     S.Diag(Fn->getBeginLoc(),
5427            isa<CXXMethodDecl>(Callee)
5428                ? diag::err_ovl_no_viable_member_function_in_call
5429                : diag::err_ovl_no_viable_function_in_call)
5430         << Callee << Callee->getSourceRange();
5431     S.Diag(Callee->getLocation(),
5432            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5433         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5434     return;
5435   }
5436 }
5437 
5438 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5439     const UnresolvedMemberExpr *const UME, Sema &S) {
5440 
5441   const auto GetFunctionLevelDCIfCXXClass =
5442       [](Sema &S) -> const CXXRecordDecl * {
5443     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5444     if (!DC || !DC->getParent())
5445       return nullptr;
5446 
5447     // If the call to some member function was made from within a member
5448     // function body 'M' return return 'M's parent.
5449     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5450       return MD->getParent()->getCanonicalDecl();
5451     // else the call was made from within a default member initializer of a
5452     // class, so return the class.
5453     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5454       return RD->getCanonicalDecl();
5455     return nullptr;
5456   };
5457   // If our DeclContext is neither a member function nor a class (in the
5458   // case of a lambda in a default member initializer), we can't have an
5459   // enclosing 'this'.
5460 
5461   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5462   if (!CurParentClass)
5463     return false;
5464 
5465   // The naming class for implicit member functions call is the class in which
5466   // name lookup starts.
5467   const CXXRecordDecl *const NamingClass =
5468       UME->getNamingClass()->getCanonicalDecl();
5469   assert(NamingClass && "Must have naming class even for implicit access");
5470 
5471   // If the unresolved member functions were found in a 'naming class' that is
5472   // related (either the same or derived from) to the class that contains the
5473   // member function that itself contained the implicit member access.
5474 
5475   return CurParentClass == NamingClass ||
5476          CurParentClass->isDerivedFrom(NamingClass);
5477 }
5478 
5479 static void
5480 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5481     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5482 
5483   if (!UME)
5484     return;
5485 
5486   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5487   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5488   // already been captured, or if this is an implicit member function call (if
5489   // it isn't, an attempt to capture 'this' should already have been made).
5490   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5491       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5492     return;
5493 
5494   // Check if the naming class in which the unresolved members were found is
5495   // related (same as or is a base of) to the enclosing class.
5496 
5497   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5498     return;
5499 
5500 
5501   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5502   // If the enclosing function is not dependent, then this lambda is
5503   // capture ready, so if we can capture this, do so.
5504   if (!EnclosingFunctionCtx->isDependentContext()) {
5505     // If the current lambda and all enclosing lambdas can capture 'this' -
5506     // then go ahead and capture 'this' (since our unresolved overload set
5507     // contains at least one non-static member function).
5508     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5509       S.CheckCXXThisCapture(CallLoc);
5510   } else if (S.CurContext->isDependentContext()) {
5511     // ... since this is an implicit member reference, that might potentially
5512     // involve a 'this' capture, mark 'this' for potential capture in
5513     // enclosing lambdas.
5514     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5515       CurLSI->addPotentialThisCapture(CallLoc);
5516   }
5517 }
5518 
5519 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5520 /// This provides the location of the left/right parens and a list of comma
5521 /// locations.
5522 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5523                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5524                                Expr *ExecConfig, bool IsExecConfig) {
5525   // Since this might be a postfix expression, get rid of ParenListExprs.
5526   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5527   if (Result.isInvalid()) return ExprError();
5528   Fn = Result.get();
5529 
5530   if (checkArgsForPlaceholders(*this, ArgExprs))
5531     return ExprError();
5532 
5533   if (getLangOpts().CPlusPlus) {
5534     // If this is a pseudo-destructor expression, build the call immediately.
5535     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5536       if (!ArgExprs.empty()) {
5537         // Pseudo-destructor calls should not have any arguments.
5538         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5539             << FixItHint::CreateRemoval(
5540                    SourceRange(ArgExprs.front()->getBeginLoc(),
5541                                ArgExprs.back()->getEndLoc()));
5542       }
5543 
5544       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5545                               VK_RValue, RParenLoc);
5546     }
5547     if (Fn->getType() == Context.PseudoObjectTy) {
5548       ExprResult result = CheckPlaceholderExpr(Fn);
5549       if (result.isInvalid()) return ExprError();
5550       Fn = result.get();
5551     }
5552 
5553     // Determine whether this is a dependent call inside a C++ template,
5554     // in which case we won't do any semantic analysis now.
5555     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5556       if (ExecConfig) {
5557         return CUDAKernelCallExpr::Create(
5558             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5559             Context.DependentTy, VK_RValue, RParenLoc);
5560       } else {
5561 
5562         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5563             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5564             Fn->getBeginLoc());
5565 
5566         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5567                                 VK_RValue, RParenLoc);
5568       }
5569     }
5570 
5571     // Determine whether this is a call to an object (C++ [over.call.object]).
5572     if (Fn->getType()->isRecordType())
5573       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5574                                           RParenLoc);
5575 
5576     if (Fn->getType() == Context.UnknownAnyTy) {
5577       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5578       if (result.isInvalid()) return ExprError();
5579       Fn = result.get();
5580     }
5581 
5582     if (Fn->getType() == Context.BoundMemberTy) {
5583       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5584                                        RParenLoc);
5585     }
5586   }
5587 
5588   // Check for overloaded calls.  This can happen even in C due to extensions.
5589   if (Fn->getType() == Context.OverloadTy) {
5590     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5591 
5592     // We aren't supposed to apply this logic if there's an '&' involved.
5593     if (!find.HasFormOfMemberPointer) {
5594       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5595         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5596                                 VK_RValue, RParenLoc);
5597       OverloadExpr *ovl = find.Expression;
5598       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5599         return BuildOverloadedCallExpr(
5600             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5601             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5602       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5603                                        RParenLoc);
5604     }
5605   }
5606 
5607   // If we're directly calling a function, get the appropriate declaration.
5608   if (Fn->getType() == Context.UnknownAnyTy) {
5609     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5610     if (result.isInvalid()) return ExprError();
5611     Fn = result.get();
5612   }
5613 
5614   Expr *NakedFn = Fn->IgnoreParens();
5615 
5616   bool CallingNDeclIndirectly = false;
5617   NamedDecl *NDecl = nullptr;
5618   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5619     if (UnOp->getOpcode() == UO_AddrOf) {
5620       CallingNDeclIndirectly = true;
5621       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5622     }
5623   }
5624 
5625   if (isa<DeclRefExpr>(NakedFn)) {
5626     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5627 
5628     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5629     if (FDecl && FDecl->getBuiltinID()) {
5630       // Rewrite the function decl for this builtin by replacing parameters
5631       // with no explicit address space with the address space of the arguments
5632       // in ArgExprs.
5633       if ((FDecl =
5634                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5635         NDecl = FDecl;
5636         Fn = DeclRefExpr::Create(
5637             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5638             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5639       }
5640     }
5641   } else if (isa<MemberExpr>(NakedFn))
5642     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5643 
5644   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5645     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5646                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5647       return ExprError();
5648 
5649     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5650       return ExprError();
5651 
5652     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5653   }
5654 
5655   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5656                                ExecConfig, IsExecConfig);
5657 }
5658 
5659 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5660 ///
5661 /// __builtin_astype( value, dst type )
5662 ///
5663 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5664                                  SourceLocation BuiltinLoc,
5665                                  SourceLocation RParenLoc) {
5666   ExprValueKind VK = VK_RValue;
5667   ExprObjectKind OK = OK_Ordinary;
5668   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5669   QualType SrcTy = E->getType();
5670   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5671     return ExprError(Diag(BuiltinLoc,
5672                           diag::err_invalid_astype_of_different_size)
5673                      << DstTy
5674                      << SrcTy
5675                      << E->getSourceRange());
5676   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5677 }
5678 
5679 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5680 /// provided arguments.
5681 ///
5682 /// __builtin_convertvector( value, dst type )
5683 ///
5684 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5685                                         SourceLocation BuiltinLoc,
5686                                         SourceLocation RParenLoc) {
5687   TypeSourceInfo *TInfo;
5688   GetTypeFromParser(ParsedDestTy, &TInfo);
5689   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5690 }
5691 
5692 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5693 /// i.e. an expression not of \p OverloadTy.  The expression should
5694 /// unary-convert to an expression of function-pointer or
5695 /// block-pointer type.
5696 ///
5697 /// \param NDecl the declaration being called, if available
5698 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5699                                        SourceLocation LParenLoc,
5700                                        ArrayRef<Expr *> Args,
5701                                        SourceLocation RParenLoc, Expr *Config,
5702                                        bool IsExecConfig, ADLCallKind UsesADL) {
5703   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5704   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5705 
5706   // Functions with 'interrupt' attribute cannot be called directly.
5707   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5708     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5709     return ExprError();
5710   }
5711 
5712   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5713   // so there's some risk when calling out to non-interrupt handler functions
5714   // that the callee might not preserve them. This is easy to diagnose here,
5715   // but can be very challenging to debug.
5716   if (auto *Caller = getCurFunctionDecl())
5717     if (Caller->hasAttr<ARMInterruptAttr>()) {
5718       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5719       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5720         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5721     }
5722 
5723   // Promote the function operand.
5724   // We special-case function promotion here because we only allow promoting
5725   // builtin functions to function pointers in the callee of a call.
5726   ExprResult Result;
5727   QualType ResultTy;
5728   if (BuiltinID &&
5729       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5730     // Extract the return type from the (builtin) function pointer type.
5731     // FIXME Several builtins still have setType in
5732     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5733     // Builtins.def to ensure they are correct before removing setType calls.
5734     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5735     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5736     ResultTy = FDecl->getCallResultType();
5737   } else {
5738     Result = CallExprUnaryConversions(Fn);
5739     ResultTy = Context.BoolTy;
5740   }
5741   if (Result.isInvalid())
5742     return ExprError();
5743   Fn = Result.get();
5744 
5745   // Check for a valid function type, but only if it is not a builtin which
5746   // requires custom type checking. These will be handled by
5747   // CheckBuiltinFunctionCall below just after creation of the call expression.
5748   const FunctionType *FuncT = nullptr;
5749   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5750    retry:
5751     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5752       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5753       // have type pointer to function".
5754       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5755       if (!FuncT)
5756         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5757                            << Fn->getType() << Fn->getSourceRange());
5758     } else if (const BlockPointerType *BPT =
5759                  Fn->getType()->getAs<BlockPointerType>()) {
5760       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5761     } else {
5762       // Handle calls to expressions of unknown-any type.
5763       if (Fn->getType() == Context.UnknownAnyTy) {
5764         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5765         if (rewrite.isInvalid()) return ExprError();
5766         Fn = rewrite.get();
5767         goto retry;
5768       }
5769 
5770     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5771       << Fn->getType() << Fn->getSourceRange());
5772     }
5773   }
5774 
5775   // Get the number of parameters in the function prototype, if any.
5776   // We will allocate space for max(Args.size(), NumParams) arguments
5777   // in the call expression.
5778   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5779   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5780 
5781   CallExpr *TheCall;
5782   if (Config) {
5783     assert(UsesADL == ADLCallKind::NotADL &&
5784            "CUDAKernelCallExpr should not use ADL");
5785     TheCall =
5786         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5787                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5788   } else {
5789     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5790                                RParenLoc, NumParams, UsesADL);
5791   }
5792 
5793   if (!getLangOpts().CPlusPlus) {
5794     // Forget about the nulled arguments since typo correction
5795     // do not handle them well.
5796     TheCall->shrinkNumArgs(Args.size());
5797     // C cannot always handle TypoExpr nodes in builtin calls and direct
5798     // function calls as their argument checking don't necessarily handle
5799     // dependent types properly, so make sure any TypoExprs have been
5800     // dealt with.
5801     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5802     if (!Result.isUsable()) return ExprError();
5803     CallExpr *TheOldCall = TheCall;
5804     TheCall = dyn_cast<CallExpr>(Result.get());
5805     bool CorrectedTypos = TheCall != TheOldCall;
5806     if (!TheCall) return Result;
5807     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5808 
5809     // A new call expression node was created if some typos were corrected.
5810     // However it may not have been constructed with enough storage. In this
5811     // case, rebuild the node with enough storage. The waste of space is
5812     // immaterial since this only happens when some typos were corrected.
5813     if (CorrectedTypos && Args.size() < NumParams) {
5814       if (Config)
5815         TheCall = CUDAKernelCallExpr::Create(
5816             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5817             RParenLoc, NumParams);
5818       else
5819         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5820                                    RParenLoc, NumParams, UsesADL);
5821     }
5822     // We can now handle the nulled arguments for the default arguments.
5823     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5824   }
5825 
5826   // Bail out early if calling a builtin with custom type checking.
5827   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5828     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5829 
5830   if (getLangOpts().CUDA) {
5831     if (Config) {
5832       // CUDA: Kernel calls must be to global functions
5833       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5834         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5835             << FDecl << Fn->getSourceRange());
5836 
5837       // CUDA: Kernel function must have 'void' return type
5838       if (!FuncT->getReturnType()->isVoidType())
5839         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5840             << Fn->getType() << Fn->getSourceRange());
5841     } else {
5842       // CUDA: Calls to global functions must be configured
5843       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5844         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5845             << FDecl << Fn->getSourceRange());
5846     }
5847   }
5848 
5849   // Check for a valid return type
5850   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5851                           FDecl))
5852     return ExprError();
5853 
5854   // We know the result type of the call, set it.
5855   TheCall->setType(FuncT->getCallResultType(Context));
5856   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5857 
5858   if (Proto) {
5859     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5860                                 IsExecConfig))
5861       return ExprError();
5862   } else {
5863     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5864 
5865     if (FDecl) {
5866       // Check if we have too few/too many template arguments, based
5867       // on our knowledge of the function definition.
5868       const FunctionDecl *Def = nullptr;
5869       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5870         Proto = Def->getType()->getAs<FunctionProtoType>();
5871        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5872           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5873           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5874       }
5875 
5876       // If the function we're calling isn't a function prototype, but we have
5877       // a function prototype from a prior declaratiom, use that prototype.
5878       if (!FDecl->hasPrototype())
5879         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5880     }
5881 
5882     // Promote the arguments (C99 6.5.2.2p6).
5883     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5884       Expr *Arg = Args[i];
5885 
5886       if (Proto && i < Proto->getNumParams()) {
5887         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5888             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5889         ExprResult ArgE =
5890             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5891         if (ArgE.isInvalid())
5892           return true;
5893 
5894         Arg = ArgE.getAs<Expr>();
5895 
5896       } else {
5897         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5898 
5899         if (ArgE.isInvalid())
5900           return true;
5901 
5902         Arg = ArgE.getAs<Expr>();
5903       }
5904 
5905       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5906                               diag::err_call_incomplete_argument, Arg))
5907         return ExprError();
5908 
5909       TheCall->setArg(i, Arg);
5910     }
5911   }
5912 
5913   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5914     if (!Method->isStatic())
5915       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5916         << Fn->getSourceRange());
5917 
5918   // Check for sentinels
5919   if (NDecl)
5920     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5921 
5922   // Do special checking on direct calls to functions.
5923   if (FDecl) {
5924     if (CheckFunctionCall(FDecl, TheCall, Proto))
5925       return ExprError();
5926 
5927     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5928 
5929     if (BuiltinID)
5930       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5931   } else if (NDecl) {
5932     if (CheckPointerCall(NDecl, TheCall, Proto))
5933       return ExprError();
5934   } else {
5935     if (CheckOtherCall(TheCall, Proto))
5936       return ExprError();
5937   }
5938 
5939   return MaybeBindToTemporary(TheCall);
5940 }
5941 
5942 ExprResult
5943 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5944                            SourceLocation RParenLoc, Expr *InitExpr) {
5945   assert(Ty && "ActOnCompoundLiteral(): missing type");
5946   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5947 
5948   TypeSourceInfo *TInfo;
5949   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5950   if (!TInfo)
5951     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5952 
5953   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5954 }
5955 
5956 ExprResult
5957 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5958                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5959   QualType literalType = TInfo->getType();
5960 
5961   if (literalType->isArrayType()) {
5962     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5963           diag::err_illegal_decl_array_incomplete_type,
5964           SourceRange(LParenLoc,
5965                       LiteralExpr->getSourceRange().getEnd())))
5966       return ExprError();
5967     if (literalType->isVariableArrayType())
5968       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5969         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5970   } else if (!literalType->isDependentType() &&
5971              RequireCompleteType(LParenLoc, literalType,
5972                diag::err_typecheck_decl_incomplete_type,
5973                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5974     return ExprError();
5975 
5976   InitializedEntity Entity
5977     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5978   InitializationKind Kind
5979     = InitializationKind::CreateCStyleCast(LParenLoc,
5980                                            SourceRange(LParenLoc, RParenLoc),
5981                                            /*InitList=*/true);
5982   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5983   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5984                                       &literalType);
5985   if (Result.isInvalid())
5986     return ExprError();
5987   LiteralExpr = Result.get();
5988 
5989   bool isFileScope = !CurContext->isFunctionOrMethod();
5990 
5991   // In C, compound literals are l-values for some reason.
5992   // For GCC compatibility, in C++, file-scope array compound literals with
5993   // constant initializers are also l-values, and compound literals are
5994   // otherwise prvalues.
5995   //
5996   // (GCC also treats C++ list-initialized file-scope array prvalues with
5997   // constant initializers as l-values, but that's non-conforming, so we don't
5998   // follow it there.)
5999   //
6000   // FIXME: It would be better to handle the lvalue cases as materializing and
6001   // lifetime-extending a temporary object, but our materialized temporaries
6002   // representation only supports lifetime extension from a variable, not "out
6003   // of thin air".
6004   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6005   // is bound to the result of applying array-to-pointer decay to the compound
6006   // literal.
6007   // FIXME: GCC supports compound literals of reference type, which should
6008   // obviously have a value kind derived from the kind of reference involved.
6009   ExprValueKind VK =
6010       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6011           ? VK_RValue
6012           : VK_LValue;
6013 
6014   if (isFileScope)
6015     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6016       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6017         Expr *Init = ILE->getInit(i);
6018         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6019       }
6020 
6021   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6022                                               VK, LiteralExpr, isFileScope);
6023   if (isFileScope) {
6024     if (!LiteralExpr->isTypeDependent() &&
6025         !LiteralExpr->isValueDependent() &&
6026         !literalType->isDependentType()) // C99 6.5.2.5p3
6027       if (CheckForConstantInitializer(LiteralExpr, literalType))
6028         return ExprError();
6029   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6030              literalType.getAddressSpace() != LangAS::Default) {
6031     // Embedded-C extensions to C99 6.5.2.5:
6032     //   "If the compound literal occurs inside the body of a function, the
6033     //   type name shall not be qualified by an address-space qualifier."
6034     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6035       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6036     return ExprError();
6037   }
6038 
6039   return MaybeBindToTemporary(E);
6040 }
6041 
6042 ExprResult
6043 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6044                     SourceLocation RBraceLoc) {
6045   // Immediately handle non-overload placeholders.  Overloads can be
6046   // resolved contextually, but everything else here can't.
6047   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6048     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6049       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6050 
6051       // Ignore failures; dropping the entire initializer list because
6052       // of one failure would be terrible for indexing/etc.
6053       if (result.isInvalid()) continue;
6054 
6055       InitArgList[I] = result.get();
6056     }
6057   }
6058 
6059   // Semantic analysis for initializers is done by ActOnDeclarator() and
6060   // CheckInitializer() - it requires knowledge of the object being initialized.
6061 
6062   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6063                                                RBraceLoc);
6064   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6065   return E;
6066 }
6067 
6068 /// Do an explicit extend of the given block pointer if we're in ARC.
6069 void Sema::maybeExtendBlockObject(ExprResult &E) {
6070   assert(E.get()->getType()->isBlockPointerType());
6071   assert(E.get()->isRValue());
6072 
6073   // Only do this in an r-value context.
6074   if (!getLangOpts().ObjCAutoRefCount) return;
6075 
6076   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6077                                CK_ARCExtendBlockObject, E.get(),
6078                                /*base path*/ nullptr, VK_RValue);
6079   Cleanup.setExprNeedsCleanups(true);
6080 }
6081 
6082 /// Prepare a conversion of the given expression to an ObjC object
6083 /// pointer type.
6084 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6085   QualType type = E.get()->getType();
6086   if (type->isObjCObjectPointerType()) {
6087     return CK_BitCast;
6088   } else if (type->isBlockPointerType()) {
6089     maybeExtendBlockObject(E);
6090     return CK_BlockPointerToObjCPointerCast;
6091   } else {
6092     assert(type->isPointerType());
6093     return CK_CPointerToObjCPointerCast;
6094   }
6095 }
6096 
6097 /// Prepares for a scalar cast, performing all the necessary stages
6098 /// except the final cast and returning the kind required.
6099 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6100   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6101   // Also, callers should have filtered out the invalid cases with
6102   // pointers.  Everything else should be possible.
6103 
6104   QualType SrcTy = Src.get()->getType();
6105   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6106     return CK_NoOp;
6107 
6108   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6109   case Type::STK_MemberPointer:
6110     llvm_unreachable("member pointer type in C");
6111 
6112   case Type::STK_CPointer:
6113   case Type::STK_BlockPointer:
6114   case Type::STK_ObjCObjectPointer:
6115     switch (DestTy->getScalarTypeKind()) {
6116     case Type::STK_CPointer: {
6117       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6118       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6119       if (SrcAS != DestAS)
6120         return CK_AddressSpaceConversion;
6121       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6122         return CK_NoOp;
6123       return CK_BitCast;
6124     }
6125     case Type::STK_BlockPointer:
6126       return (SrcKind == Type::STK_BlockPointer
6127                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6128     case Type::STK_ObjCObjectPointer:
6129       if (SrcKind == Type::STK_ObjCObjectPointer)
6130         return CK_BitCast;
6131       if (SrcKind == Type::STK_CPointer)
6132         return CK_CPointerToObjCPointerCast;
6133       maybeExtendBlockObject(Src);
6134       return CK_BlockPointerToObjCPointerCast;
6135     case Type::STK_Bool:
6136       return CK_PointerToBoolean;
6137     case Type::STK_Integral:
6138       return CK_PointerToIntegral;
6139     case Type::STK_Floating:
6140     case Type::STK_FloatingComplex:
6141     case Type::STK_IntegralComplex:
6142     case Type::STK_MemberPointer:
6143     case Type::STK_FixedPoint:
6144       llvm_unreachable("illegal cast from pointer");
6145     }
6146     llvm_unreachable("Should have returned before this");
6147 
6148   case Type::STK_FixedPoint:
6149     switch (DestTy->getScalarTypeKind()) {
6150     case Type::STK_FixedPoint:
6151       return CK_FixedPointCast;
6152     case Type::STK_Bool:
6153       return CK_FixedPointToBoolean;
6154     case Type::STK_Integral:
6155       return CK_FixedPointToIntegral;
6156     case Type::STK_Floating:
6157     case Type::STK_IntegralComplex:
6158     case Type::STK_FloatingComplex:
6159       Diag(Src.get()->getExprLoc(),
6160            diag::err_unimplemented_conversion_with_fixed_point_type)
6161           << DestTy;
6162       return CK_IntegralCast;
6163     case Type::STK_CPointer:
6164     case Type::STK_ObjCObjectPointer:
6165     case Type::STK_BlockPointer:
6166     case Type::STK_MemberPointer:
6167       llvm_unreachable("illegal cast to pointer type");
6168     }
6169     llvm_unreachable("Should have returned before this");
6170 
6171   case Type::STK_Bool: // casting from bool is like casting from an integer
6172   case Type::STK_Integral:
6173     switch (DestTy->getScalarTypeKind()) {
6174     case Type::STK_CPointer:
6175     case Type::STK_ObjCObjectPointer:
6176     case Type::STK_BlockPointer:
6177       if (Src.get()->isNullPointerConstant(Context,
6178                                            Expr::NPC_ValueDependentIsNull))
6179         return CK_NullToPointer;
6180       return CK_IntegralToPointer;
6181     case Type::STK_Bool:
6182       return CK_IntegralToBoolean;
6183     case Type::STK_Integral:
6184       return CK_IntegralCast;
6185     case Type::STK_Floating:
6186       return CK_IntegralToFloating;
6187     case Type::STK_IntegralComplex:
6188       Src = ImpCastExprToType(Src.get(),
6189                       DestTy->castAs<ComplexType>()->getElementType(),
6190                       CK_IntegralCast);
6191       return CK_IntegralRealToComplex;
6192     case Type::STK_FloatingComplex:
6193       Src = ImpCastExprToType(Src.get(),
6194                       DestTy->castAs<ComplexType>()->getElementType(),
6195                       CK_IntegralToFloating);
6196       return CK_FloatingRealToComplex;
6197     case Type::STK_MemberPointer:
6198       llvm_unreachable("member pointer type in C");
6199     case Type::STK_FixedPoint:
6200       return CK_IntegralToFixedPoint;
6201     }
6202     llvm_unreachable("Should have returned before this");
6203 
6204   case Type::STK_Floating:
6205     switch (DestTy->getScalarTypeKind()) {
6206     case Type::STK_Floating:
6207       return CK_FloatingCast;
6208     case Type::STK_Bool:
6209       return CK_FloatingToBoolean;
6210     case Type::STK_Integral:
6211       return CK_FloatingToIntegral;
6212     case Type::STK_FloatingComplex:
6213       Src = ImpCastExprToType(Src.get(),
6214                               DestTy->castAs<ComplexType>()->getElementType(),
6215                               CK_FloatingCast);
6216       return CK_FloatingRealToComplex;
6217     case Type::STK_IntegralComplex:
6218       Src = ImpCastExprToType(Src.get(),
6219                               DestTy->castAs<ComplexType>()->getElementType(),
6220                               CK_FloatingToIntegral);
6221       return CK_IntegralRealToComplex;
6222     case Type::STK_CPointer:
6223     case Type::STK_ObjCObjectPointer:
6224     case Type::STK_BlockPointer:
6225       llvm_unreachable("valid float->pointer cast?");
6226     case Type::STK_MemberPointer:
6227       llvm_unreachable("member pointer type in C");
6228     case Type::STK_FixedPoint:
6229       Diag(Src.get()->getExprLoc(),
6230            diag::err_unimplemented_conversion_with_fixed_point_type)
6231           << SrcTy;
6232       return CK_IntegralCast;
6233     }
6234     llvm_unreachable("Should have returned before this");
6235 
6236   case Type::STK_FloatingComplex:
6237     switch (DestTy->getScalarTypeKind()) {
6238     case Type::STK_FloatingComplex:
6239       return CK_FloatingComplexCast;
6240     case Type::STK_IntegralComplex:
6241       return CK_FloatingComplexToIntegralComplex;
6242     case Type::STK_Floating: {
6243       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6244       if (Context.hasSameType(ET, DestTy))
6245         return CK_FloatingComplexToReal;
6246       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6247       return CK_FloatingCast;
6248     }
6249     case Type::STK_Bool:
6250       return CK_FloatingComplexToBoolean;
6251     case Type::STK_Integral:
6252       Src = ImpCastExprToType(Src.get(),
6253                               SrcTy->castAs<ComplexType>()->getElementType(),
6254                               CK_FloatingComplexToReal);
6255       return CK_FloatingToIntegral;
6256     case Type::STK_CPointer:
6257     case Type::STK_ObjCObjectPointer:
6258     case Type::STK_BlockPointer:
6259       llvm_unreachable("valid complex float->pointer cast?");
6260     case Type::STK_MemberPointer:
6261       llvm_unreachable("member pointer type in C");
6262     case Type::STK_FixedPoint:
6263       Diag(Src.get()->getExprLoc(),
6264            diag::err_unimplemented_conversion_with_fixed_point_type)
6265           << SrcTy;
6266       return CK_IntegralCast;
6267     }
6268     llvm_unreachable("Should have returned before this");
6269 
6270   case Type::STK_IntegralComplex:
6271     switch (DestTy->getScalarTypeKind()) {
6272     case Type::STK_FloatingComplex:
6273       return CK_IntegralComplexToFloatingComplex;
6274     case Type::STK_IntegralComplex:
6275       return CK_IntegralComplexCast;
6276     case Type::STK_Integral: {
6277       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6278       if (Context.hasSameType(ET, DestTy))
6279         return CK_IntegralComplexToReal;
6280       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6281       return CK_IntegralCast;
6282     }
6283     case Type::STK_Bool:
6284       return CK_IntegralComplexToBoolean;
6285     case Type::STK_Floating:
6286       Src = ImpCastExprToType(Src.get(),
6287                               SrcTy->castAs<ComplexType>()->getElementType(),
6288                               CK_IntegralComplexToReal);
6289       return CK_IntegralToFloating;
6290     case Type::STK_CPointer:
6291     case Type::STK_ObjCObjectPointer:
6292     case Type::STK_BlockPointer:
6293       llvm_unreachable("valid complex int->pointer cast?");
6294     case Type::STK_MemberPointer:
6295       llvm_unreachable("member pointer type in C");
6296     case Type::STK_FixedPoint:
6297       Diag(Src.get()->getExprLoc(),
6298            diag::err_unimplemented_conversion_with_fixed_point_type)
6299           << SrcTy;
6300       return CK_IntegralCast;
6301     }
6302     llvm_unreachable("Should have returned before this");
6303   }
6304 
6305   llvm_unreachable("Unhandled scalar cast");
6306 }
6307 
6308 static bool breakDownVectorType(QualType type, uint64_t &len,
6309                                 QualType &eltType) {
6310   // Vectors are simple.
6311   if (const VectorType *vecType = type->getAs<VectorType>()) {
6312     len = vecType->getNumElements();
6313     eltType = vecType->getElementType();
6314     assert(eltType->isScalarType());
6315     return true;
6316   }
6317 
6318   // We allow lax conversion to and from non-vector types, but only if
6319   // they're real types (i.e. non-complex, non-pointer scalar types).
6320   if (!type->isRealType()) return false;
6321 
6322   len = 1;
6323   eltType = type;
6324   return true;
6325 }
6326 
6327 /// Are the two types lax-compatible vector types?  That is, given
6328 /// that one of them is a vector, do they have equal storage sizes,
6329 /// where the storage size is the number of elements times the element
6330 /// size?
6331 ///
6332 /// This will also return false if either of the types is neither a
6333 /// vector nor a real type.
6334 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6335   assert(destTy->isVectorType() || srcTy->isVectorType());
6336 
6337   // Disallow lax conversions between scalars and ExtVectors (these
6338   // conversions are allowed for other vector types because common headers
6339   // depend on them).  Most scalar OP ExtVector cases are handled by the
6340   // splat path anyway, which does what we want (convert, not bitcast).
6341   // What this rules out for ExtVectors is crazy things like char4*float.
6342   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6343   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6344 
6345   uint64_t srcLen, destLen;
6346   QualType srcEltTy, destEltTy;
6347   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6348   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6349 
6350   // ASTContext::getTypeSize will return the size rounded up to a
6351   // power of 2, so instead of using that, we need to use the raw
6352   // element size multiplied by the element count.
6353   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6354   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6355 
6356   return (srcLen * srcEltSize == destLen * destEltSize);
6357 }
6358 
6359 /// Is this a legal conversion between two types, one of which is
6360 /// known to be a vector type?
6361 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6362   assert(destTy->isVectorType() || srcTy->isVectorType());
6363 
6364   if (!Context.getLangOpts().LaxVectorConversions)
6365     return false;
6366   return areLaxCompatibleVectorTypes(srcTy, destTy);
6367 }
6368 
6369 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6370                            CastKind &Kind) {
6371   assert(VectorTy->isVectorType() && "Not a vector type!");
6372 
6373   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6374     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6375       return Diag(R.getBegin(),
6376                   Ty->isVectorType() ?
6377                   diag::err_invalid_conversion_between_vectors :
6378                   diag::err_invalid_conversion_between_vector_and_integer)
6379         << VectorTy << Ty << R;
6380   } else
6381     return Diag(R.getBegin(),
6382                 diag::err_invalid_conversion_between_vector_and_scalar)
6383       << VectorTy << Ty << R;
6384 
6385   Kind = CK_BitCast;
6386   return false;
6387 }
6388 
6389 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6390   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6391 
6392   if (DestElemTy == SplattedExpr->getType())
6393     return SplattedExpr;
6394 
6395   assert(DestElemTy->isFloatingType() ||
6396          DestElemTy->isIntegralOrEnumerationType());
6397 
6398   CastKind CK;
6399   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6400     // OpenCL requires that we convert `true` boolean expressions to -1, but
6401     // only when splatting vectors.
6402     if (DestElemTy->isFloatingType()) {
6403       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6404       // in two steps: boolean to signed integral, then to floating.
6405       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6406                                                  CK_BooleanToSignedIntegral);
6407       SplattedExpr = CastExprRes.get();
6408       CK = CK_IntegralToFloating;
6409     } else {
6410       CK = CK_BooleanToSignedIntegral;
6411     }
6412   } else {
6413     ExprResult CastExprRes = SplattedExpr;
6414     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6415     if (CastExprRes.isInvalid())
6416       return ExprError();
6417     SplattedExpr = CastExprRes.get();
6418   }
6419   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6420 }
6421 
6422 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6423                                     Expr *CastExpr, CastKind &Kind) {
6424   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6425 
6426   QualType SrcTy = CastExpr->getType();
6427 
6428   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6429   // an ExtVectorType.
6430   // In OpenCL, casts between vectors of different types are not allowed.
6431   // (See OpenCL 6.2).
6432   if (SrcTy->isVectorType()) {
6433     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6434         (getLangOpts().OpenCL &&
6435          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6436       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6437         << DestTy << SrcTy << R;
6438       return ExprError();
6439     }
6440     Kind = CK_BitCast;
6441     return CastExpr;
6442   }
6443 
6444   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6445   // conversion will take place first from scalar to elt type, and then
6446   // splat from elt type to vector.
6447   if (SrcTy->isPointerType())
6448     return Diag(R.getBegin(),
6449                 diag::err_invalid_conversion_between_vector_and_scalar)
6450       << DestTy << SrcTy << R;
6451 
6452   Kind = CK_VectorSplat;
6453   return prepareVectorSplat(DestTy, CastExpr);
6454 }
6455 
6456 ExprResult
6457 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6458                     Declarator &D, ParsedType &Ty,
6459                     SourceLocation RParenLoc, Expr *CastExpr) {
6460   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6461          "ActOnCastExpr(): missing type or expr");
6462 
6463   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6464   if (D.isInvalidType())
6465     return ExprError();
6466 
6467   if (getLangOpts().CPlusPlus) {
6468     // Check that there are no default arguments (C++ only).
6469     CheckExtraCXXDefaultArguments(D);
6470   } else {
6471     // Make sure any TypoExprs have been dealt with.
6472     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6473     if (!Res.isUsable())
6474       return ExprError();
6475     CastExpr = Res.get();
6476   }
6477 
6478   checkUnusedDeclAttributes(D);
6479 
6480   QualType castType = castTInfo->getType();
6481   Ty = CreateParsedType(castType, castTInfo);
6482 
6483   bool isVectorLiteral = false;
6484 
6485   // Check for an altivec or OpenCL literal,
6486   // i.e. all the elements are integer constants.
6487   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6488   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6489   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6490        && castType->isVectorType() && (PE || PLE)) {
6491     if (PLE && PLE->getNumExprs() == 0) {
6492       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6493       return ExprError();
6494     }
6495     if (PE || PLE->getNumExprs() == 1) {
6496       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6497       if (!E->getType()->isVectorType())
6498         isVectorLiteral = true;
6499     }
6500     else
6501       isVectorLiteral = true;
6502   }
6503 
6504   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6505   // then handle it as such.
6506   if (isVectorLiteral)
6507     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6508 
6509   // If the Expr being casted is a ParenListExpr, handle it specially.
6510   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6511   // sequence of BinOp comma operators.
6512   if (isa<ParenListExpr>(CastExpr)) {
6513     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6514     if (Result.isInvalid()) return ExprError();
6515     CastExpr = Result.get();
6516   }
6517 
6518   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6519       !getSourceManager().isInSystemMacro(LParenLoc))
6520     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6521 
6522   CheckTollFreeBridgeCast(castType, CastExpr);
6523 
6524   CheckObjCBridgeRelatedCast(castType, CastExpr);
6525 
6526   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6527 
6528   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6529 }
6530 
6531 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6532                                     SourceLocation RParenLoc, Expr *E,
6533                                     TypeSourceInfo *TInfo) {
6534   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6535          "Expected paren or paren list expression");
6536 
6537   Expr **exprs;
6538   unsigned numExprs;
6539   Expr *subExpr;
6540   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6541   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6542     LiteralLParenLoc = PE->getLParenLoc();
6543     LiteralRParenLoc = PE->getRParenLoc();
6544     exprs = PE->getExprs();
6545     numExprs = PE->getNumExprs();
6546   } else { // isa<ParenExpr> by assertion at function entrance
6547     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6548     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6549     subExpr = cast<ParenExpr>(E)->getSubExpr();
6550     exprs = &subExpr;
6551     numExprs = 1;
6552   }
6553 
6554   QualType Ty = TInfo->getType();
6555   assert(Ty->isVectorType() && "Expected vector type");
6556 
6557   SmallVector<Expr *, 8> initExprs;
6558   const VectorType *VTy = Ty->getAs<VectorType>();
6559   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6560 
6561   // '(...)' form of vector initialization in AltiVec: the number of
6562   // initializers must be one or must match the size of the vector.
6563   // If a single value is specified in the initializer then it will be
6564   // replicated to all the components of the vector
6565   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6566     // The number of initializers must be one or must match the size of the
6567     // vector. If a single value is specified in the initializer then it will
6568     // be replicated to all the components of the vector
6569     if (numExprs == 1) {
6570       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6571       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6572       if (Literal.isInvalid())
6573         return ExprError();
6574       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6575                                   PrepareScalarCast(Literal, ElemTy));
6576       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6577     }
6578     else if (numExprs < numElems) {
6579       Diag(E->getExprLoc(),
6580            diag::err_incorrect_number_of_vector_initializers);
6581       return ExprError();
6582     }
6583     else
6584       initExprs.append(exprs, exprs + numExprs);
6585   }
6586   else {
6587     // For OpenCL, when the number of initializers is a single value,
6588     // it will be replicated to all components of the vector.
6589     if (getLangOpts().OpenCL &&
6590         VTy->getVectorKind() == VectorType::GenericVector &&
6591         numExprs == 1) {
6592         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6593         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6594         if (Literal.isInvalid())
6595           return ExprError();
6596         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6597                                     PrepareScalarCast(Literal, ElemTy));
6598         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6599     }
6600 
6601     initExprs.append(exprs, exprs + numExprs);
6602   }
6603   // FIXME: This means that pretty-printing the final AST will produce curly
6604   // braces instead of the original commas.
6605   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6606                                                    initExprs, LiteralRParenLoc);
6607   initE->setType(Ty);
6608   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6609 }
6610 
6611 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6612 /// the ParenListExpr into a sequence of comma binary operators.
6613 ExprResult
6614 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6615   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6616   if (!E)
6617     return OrigExpr;
6618 
6619   ExprResult Result(E->getExpr(0));
6620 
6621   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6622     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6623                         E->getExpr(i));
6624 
6625   if (Result.isInvalid()) return ExprError();
6626 
6627   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6628 }
6629 
6630 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6631                                     SourceLocation R,
6632                                     MultiExprArg Val) {
6633   return ParenListExpr::Create(Context, L, Val, R);
6634 }
6635 
6636 /// Emit a specialized diagnostic when one expression is a null pointer
6637 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6638 /// emitted.
6639 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6640                                       SourceLocation QuestionLoc) {
6641   Expr *NullExpr = LHSExpr;
6642   Expr *NonPointerExpr = RHSExpr;
6643   Expr::NullPointerConstantKind NullKind =
6644       NullExpr->isNullPointerConstant(Context,
6645                                       Expr::NPC_ValueDependentIsNotNull);
6646 
6647   if (NullKind == Expr::NPCK_NotNull) {
6648     NullExpr = RHSExpr;
6649     NonPointerExpr = LHSExpr;
6650     NullKind =
6651         NullExpr->isNullPointerConstant(Context,
6652                                         Expr::NPC_ValueDependentIsNotNull);
6653   }
6654 
6655   if (NullKind == Expr::NPCK_NotNull)
6656     return false;
6657 
6658   if (NullKind == Expr::NPCK_ZeroExpression)
6659     return false;
6660 
6661   if (NullKind == Expr::NPCK_ZeroLiteral) {
6662     // In this case, check to make sure that we got here from a "NULL"
6663     // string in the source code.
6664     NullExpr = NullExpr->IgnoreParenImpCasts();
6665     SourceLocation loc = NullExpr->getExprLoc();
6666     if (!findMacroSpelling(loc, "NULL"))
6667       return false;
6668   }
6669 
6670   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6671   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6672       << NonPointerExpr->getType() << DiagType
6673       << NonPointerExpr->getSourceRange();
6674   return true;
6675 }
6676 
6677 /// Return false if the condition expression is valid, true otherwise.
6678 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6679   QualType CondTy = Cond->getType();
6680 
6681   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6682   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6683     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6684       << CondTy << Cond->getSourceRange();
6685     return true;
6686   }
6687 
6688   // C99 6.5.15p2
6689   if (CondTy->isScalarType()) return false;
6690 
6691   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6692     << CondTy << Cond->getSourceRange();
6693   return true;
6694 }
6695 
6696 /// Handle when one or both operands are void type.
6697 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6698                                          ExprResult &RHS) {
6699     Expr *LHSExpr = LHS.get();
6700     Expr *RHSExpr = RHS.get();
6701 
6702     if (!LHSExpr->getType()->isVoidType())
6703       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6704           << RHSExpr->getSourceRange();
6705     if (!RHSExpr->getType()->isVoidType())
6706       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6707           << LHSExpr->getSourceRange();
6708     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6709     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6710     return S.Context.VoidTy;
6711 }
6712 
6713 /// Return false if the NullExpr can be promoted to PointerTy,
6714 /// true otherwise.
6715 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6716                                         QualType PointerTy) {
6717   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6718       !NullExpr.get()->isNullPointerConstant(S.Context,
6719                                             Expr::NPC_ValueDependentIsNull))
6720     return true;
6721 
6722   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6723   return false;
6724 }
6725 
6726 /// Checks compatibility between two pointers and return the resulting
6727 /// type.
6728 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6729                                                      ExprResult &RHS,
6730                                                      SourceLocation Loc) {
6731   QualType LHSTy = LHS.get()->getType();
6732   QualType RHSTy = RHS.get()->getType();
6733 
6734   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6735     // Two identical pointers types are always compatible.
6736     return LHSTy;
6737   }
6738 
6739   QualType lhptee, rhptee;
6740 
6741   // Get the pointee types.
6742   bool IsBlockPointer = false;
6743   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6744     lhptee = LHSBTy->getPointeeType();
6745     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6746     IsBlockPointer = true;
6747   } else {
6748     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6749     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6750   }
6751 
6752   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6753   // differently qualified versions of compatible types, the result type is
6754   // a pointer to an appropriately qualified version of the composite
6755   // type.
6756 
6757   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6758   // clause doesn't make sense for our extensions. E.g. address space 2 should
6759   // be incompatible with address space 3: they may live on different devices or
6760   // anything.
6761   Qualifiers lhQual = lhptee.getQualifiers();
6762   Qualifiers rhQual = rhptee.getQualifiers();
6763 
6764   LangAS ResultAddrSpace = LangAS::Default;
6765   LangAS LAddrSpace = lhQual.getAddressSpace();
6766   LangAS RAddrSpace = rhQual.getAddressSpace();
6767 
6768   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6769   // spaces is disallowed.
6770   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6771     ResultAddrSpace = LAddrSpace;
6772   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6773     ResultAddrSpace = RAddrSpace;
6774   else {
6775     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6776         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6777         << RHS.get()->getSourceRange();
6778     return QualType();
6779   }
6780 
6781   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6782   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6783   lhQual.removeCVRQualifiers();
6784   rhQual.removeCVRQualifiers();
6785 
6786   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6787   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6788   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6789   // qual types are compatible iff
6790   //  * corresponded types are compatible
6791   //  * CVR qualifiers are equal
6792   //  * address spaces are equal
6793   // Thus for conditional operator we merge CVR and address space unqualified
6794   // pointees and if there is a composite type we return a pointer to it with
6795   // merged qualifiers.
6796   LHSCastKind =
6797       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6798   RHSCastKind =
6799       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6800   lhQual.removeAddressSpace();
6801   rhQual.removeAddressSpace();
6802 
6803   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6804   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6805 
6806   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6807 
6808   if (CompositeTy.isNull()) {
6809     // In this situation, we assume void* type. No especially good
6810     // reason, but this is what gcc does, and we do have to pick
6811     // to get a consistent AST.
6812     QualType incompatTy;
6813     incompatTy = S.Context.getPointerType(
6814         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6815     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6816     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6817 
6818     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6819     // for casts between types with incompatible address space qualifiers.
6820     // For the following code the compiler produces casts between global and
6821     // local address spaces of the corresponded innermost pointees:
6822     // local int *global *a;
6823     // global int *global *b;
6824     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6825     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6826         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6827         << RHS.get()->getSourceRange();
6828 
6829     return incompatTy;
6830   }
6831 
6832   // The pointer types are compatible.
6833   // In case of OpenCL ResultTy should have the address space qualifier
6834   // which is a superset of address spaces of both the 2nd and the 3rd
6835   // operands of the conditional operator.
6836   QualType ResultTy = [&, ResultAddrSpace]() {
6837     if (S.getLangOpts().OpenCL) {
6838       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6839       CompositeQuals.setAddressSpace(ResultAddrSpace);
6840       return S.Context
6841           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6842           .withCVRQualifiers(MergedCVRQual);
6843     }
6844     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6845   }();
6846   if (IsBlockPointer)
6847     ResultTy = S.Context.getBlockPointerType(ResultTy);
6848   else
6849     ResultTy = S.Context.getPointerType(ResultTy);
6850 
6851   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6852   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6853   return ResultTy;
6854 }
6855 
6856 /// Return the resulting type when the operands are both block pointers.
6857 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6858                                                           ExprResult &LHS,
6859                                                           ExprResult &RHS,
6860                                                           SourceLocation Loc) {
6861   QualType LHSTy = LHS.get()->getType();
6862   QualType RHSTy = RHS.get()->getType();
6863 
6864   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6865     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6866       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6867       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6868       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6869       return destType;
6870     }
6871     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6872       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6873       << RHS.get()->getSourceRange();
6874     return QualType();
6875   }
6876 
6877   // We have 2 block pointer types.
6878   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6879 }
6880 
6881 /// Return the resulting type when the operands are both pointers.
6882 static QualType
6883 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6884                                             ExprResult &RHS,
6885                                             SourceLocation Loc) {
6886   // get the pointer types
6887   QualType LHSTy = LHS.get()->getType();
6888   QualType RHSTy = RHS.get()->getType();
6889 
6890   // get the "pointed to" types
6891   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6892   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6893 
6894   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6895   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6896     // Figure out necessary qualifiers (C99 6.5.15p6)
6897     QualType destPointee
6898       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6899     QualType destType = S.Context.getPointerType(destPointee);
6900     // Add qualifiers if necessary.
6901     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6902     // Promote to void*.
6903     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6904     return destType;
6905   }
6906   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6907     QualType destPointee
6908       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6909     QualType destType = S.Context.getPointerType(destPointee);
6910     // Add qualifiers if necessary.
6911     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6912     // Promote to void*.
6913     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6914     return destType;
6915   }
6916 
6917   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6918 }
6919 
6920 /// Return false if the first expression is not an integer and the second
6921 /// expression is not a pointer, true otherwise.
6922 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6923                                         Expr* PointerExpr, SourceLocation Loc,
6924                                         bool IsIntFirstExpr) {
6925   if (!PointerExpr->getType()->isPointerType() ||
6926       !Int.get()->getType()->isIntegerType())
6927     return false;
6928 
6929   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6930   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6931 
6932   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6933     << Expr1->getType() << Expr2->getType()
6934     << Expr1->getSourceRange() << Expr2->getSourceRange();
6935   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6936                             CK_IntegralToPointer);
6937   return true;
6938 }
6939 
6940 /// Simple conversion between integer and floating point types.
6941 ///
6942 /// Used when handling the OpenCL conditional operator where the
6943 /// condition is a vector while the other operands are scalar.
6944 ///
6945 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6946 /// types are either integer or floating type. Between the two
6947 /// operands, the type with the higher rank is defined as the "result
6948 /// type". The other operand needs to be promoted to the same type. No
6949 /// other type promotion is allowed. We cannot use
6950 /// UsualArithmeticConversions() for this purpose, since it always
6951 /// promotes promotable types.
6952 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6953                                             ExprResult &RHS,
6954                                             SourceLocation QuestionLoc) {
6955   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6956   if (LHS.isInvalid())
6957     return QualType();
6958   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6959   if (RHS.isInvalid())
6960     return QualType();
6961 
6962   // For conversion purposes, we ignore any qualifiers.
6963   // For example, "const float" and "float" are equivalent.
6964   QualType LHSType =
6965     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6966   QualType RHSType =
6967     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6968 
6969   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6970     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6971       << LHSType << LHS.get()->getSourceRange();
6972     return QualType();
6973   }
6974 
6975   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6976     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6977       << RHSType << RHS.get()->getSourceRange();
6978     return QualType();
6979   }
6980 
6981   // If both types are identical, no conversion is needed.
6982   if (LHSType == RHSType)
6983     return LHSType;
6984 
6985   // Now handle "real" floating types (i.e. float, double, long double).
6986   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6987     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6988                                  /*IsCompAssign = */ false);
6989 
6990   // Finally, we have two differing integer types.
6991   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6992   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6993 }
6994 
6995 /// Convert scalar operands to a vector that matches the
6996 ///        condition in length.
6997 ///
6998 /// Used when handling the OpenCL conditional operator where the
6999 /// condition is a vector while the other operands are scalar.
7000 ///
7001 /// We first compute the "result type" for the scalar operands
7002 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7003 /// into a vector of that type where the length matches the condition
7004 /// vector type. s6.11.6 requires that the element types of the result
7005 /// and the condition must have the same number of bits.
7006 static QualType
7007 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7008                               QualType CondTy, SourceLocation QuestionLoc) {
7009   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7010   if (ResTy.isNull()) return QualType();
7011 
7012   const VectorType *CV = CondTy->getAs<VectorType>();
7013   assert(CV);
7014 
7015   // Determine the vector result type
7016   unsigned NumElements = CV->getNumElements();
7017   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7018 
7019   // Ensure that all types have the same number of bits
7020   if (S.Context.getTypeSize(CV->getElementType())
7021       != S.Context.getTypeSize(ResTy)) {
7022     // Since VectorTy is created internally, it does not pretty print
7023     // with an OpenCL name. Instead, we just print a description.
7024     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7025     SmallString<64> Str;
7026     llvm::raw_svector_ostream OS(Str);
7027     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7028     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7029       << CondTy << OS.str();
7030     return QualType();
7031   }
7032 
7033   // Convert operands to the vector result type
7034   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7035   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7036 
7037   return VectorTy;
7038 }
7039 
7040 /// Return false if this is a valid OpenCL condition vector
7041 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7042                                        SourceLocation QuestionLoc) {
7043   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7044   // integral type.
7045   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7046   assert(CondTy);
7047   QualType EleTy = CondTy->getElementType();
7048   if (EleTy->isIntegerType()) return false;
7049 
7050   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7051     << Cond->getType() << Cond->getSourceRange();
7052   return true;
7053 }
7054 
7055 /// Return false if the vector condition type and the vector
7056 ///        result type are compatible.
7057 ///
7058 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7059 /// number of elements, and their element types have the same number
7060 /// of bits.
7061 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7062                               SourceLocation QuestionLoc) {
7063   const VectorType *CV = CondTy->getAs<VectorType>();
7064   const VectorType *RV = VecResTy->getAs<VectorType>();
7065   assert(CV && RV);
7066 
7067   if (CV->getNumElements() != RV->getNumElements()) {
7068     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7069       << CondTy << VecResTy;
7070     return true;
7071   }
7072 
7073   QualType CVE = CV->getElementType();
7074   QualType RVE = RV->getElementType();
7075 
7076   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7077     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7078       << CondTy << VecResTy;
7079     return true;
7080   }
7081 
7082   return false;
7083 }
7084 
7085 /// Return the resulting type for the conditional operator in
7086 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7087 ///        s6.3.i) when the condition is a vector type.
7088 static QualType
7089 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7090                              ExprResult &LHS, ExprResult &RHS,
7091                              SourceLocation QuestionLoc) {
7092   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7093   if (Cond.isInvalid())
7094     return QualType();
7095   QualType CondTy = Cond.get()->getType();
7096 
7097   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7098     return QualType();
7099 
7100   // If either operand is a vector then find the vector type of the
7101   // result as specified in OpenCL v1.1 s6.3.i.
7102   if (LHS.get()->getType()->isVectorType() ||
7103       RHS.get()->getType()->isVectorType()) {
7104     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7105                                               /*isCompAssign*/false,
7106                                               /*AllowBothBool*/true,
7107                                               /*AllowBoolConversions*/false);
7108     if (VecResTy.isNull()) return QualType();
7109     // The result type must match the condition type as specified in
7110     // OpenCL v1.1 s6.11.6.
7111     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7112       return QualType();
7113     return VecResTy;
7114   }
7115 
7116   // Both operands are scalar.
7117   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7118 }
7119 
7120 /// Return true if the Expr is block type
7121 static bool checkBlockType(Sema &S, const Expr *E) {
7122   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7123     QualType Ty = CE->getCallee()->getType();
7124     if (Ty->isBlockPointerType()) {
7125       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7126       return true;
7127     }
7128   }
7129   return false;
7130 }
7131 
7132 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7133 /// In that case, LHS = cond.
7134 /// C99 6.5.15
7135 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7136                                         ExprResult &RHS, ExprValueKind &VK,
7137                                         ExprObjectKind &OK,
7138                                         SourceLocation QuestionLoc) {
7139 
7140   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7141   if (!LHSResult.isUsable()) return QualType();
7142   LHS = LHSResult;
7143 
7144   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7145   if (!RHSResult.isUsable()) return QualType();
7146   RHS = RHSResult;
7147 
7148   // C++ is sufficiently different to merit its own checker.
7149   if (getLangOpts().CPlusPlus)
7150     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7151 
7152   VK = VK_RValue;
7153   OK = OK_Ordinary;
7154 
7155   // The OpenCL operator with a vector condition is sufficiently
7156   // different to merit its own checker.
7157   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7158     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7159 
7160   // First, check the condition.
7161   Cond = UsualUnaryConversions(Cond.get());
7162   if (Cond.isInvalid())
7163     return QualType();
7164   if (checkCondition(*this, Cond.get(), QuestionLoc))
7165     return QualType();
7166 
7167   // Now check the two expressions.
7168   if (LHS.get()->getType()->isVectorType() ||
7169       RHS.get()->getType()->isVectorType())
7170     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7171                                /*AllowBothBool*/true,
7172                                /*AllowBoolConversions*/false);
7173 
7174   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7175   if (LHS.isInvalid() || RHS.isInvalid())
7176     return QualType();
7177 
7178   QualType LHSTy = LHS.get()->getType();
7179   QualType RHSTy = RHS.get()->getType();
7180 
7181   // Diagnose attempts to convert between __float128 and long double where
7182   // such conversions currently can't be handled.
7183   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7184     Diag(QuestionLoc,
7185          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7186       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7187     return QualType();
7188   }
7189 
7190   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7191   // selection operator (?:).
7192   if (getLangOpts().OpenCL &&
7193       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7194     return QualType();
7195   }
7196 
7197   // If both operands have arithmetic type, do the usual arithmetic conversions
7198   // to find a common type: C99 6.5.15p3,5.
7199   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7200     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7201     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7202 
7203     return ResTy;
7204   }
7205 
7206   // If both operands are the same structure or union type, the result is that
7207   // type.
7208   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7209     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7210       if (LHSRT->getDecl() == RHSRT->getDecl())
7211         // "If both the operands have structure or union type, the result has
7212         // that type."  This implies that CV qualifiers are dropped.
7213         return LHSTy.getUnqualifiedType();
7214     // FIXME: Type of conditional expression must be complete in C mode.
7215   }
7216 
7217   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7218   // The following || allows only one side to be void (a GCC-ism).
7219   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7220     return checkConditionalVoidType(*this, LHS, RHS);
7221   }
7222 
7223   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7224   // the type of the other operand."
7225   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7226   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7227 
7228   // All objective-c pointer type analysis is done here.
7229   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7230                                                         QuestionLoc);
7231   if (LHS.isInvalid() || RHS.isInvalid())
7232     return QualType();
7233   if (!compositeType.isNull())
7234     return compositeType;
7235 
7236 
7237   // Handle block pointer types.
7238   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7239     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7240                                                      QuestionLoc);
7241 
7242   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7243   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7244     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7245                                                        QuestionLoc);
7246 
7247   // GCC compatibility: soften pointer/integer mismatch.  Note that
7248   // null pointers have been filtered out by this point.
7249   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7250       /*isIntFirstExpr=*/true))
7251     return RHSTy;
7252   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7253       /*isIntFirstExpr=*/false))
7254     return LHSTy;
7255 
7256   // Emit a better diagnostic if one of the expressions is a null pointer
7257   // constant and the other is not a pointer type. In this case, the user most
7258   // likely forgot to take the address of the other expression.
7259   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7260     return QualType();
7261 
7262   // Otherwise, the operands are not compatible.
7263   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7264     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7265     << RHS.get()->getSourceRange();
7266   return QualType();
7267 }
7268 
7269 /// FindCompositeObjCPointerType - Helper method to find composite type of
7270 /// two objective-c pointer types of the two input expressions.
7271 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7272                                             SourceLocation QuestionLoc) {
7273   QualType LHSTy = LHS.get()->getType();
7274   QualType RHSTy = RHS.get()->getType();
7275 
7276   // Handle things like Class and struct objc_class*.  Here we case the result
7277   // to the pseudo-builtin, because that will be implicitly cast back to the
7278   // redefinition type if an attempt is made to access its fields.
7279   if (LHSTy->isObjCClassType() &&
7280       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7281     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7282     return LHSTy;
7283   }
7284   if (RHSTy->isObjCClassType() &&
7285       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7286     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7287     return RHSTy;
7288   }
7289   // And the same for struct objc_object* / id
7290   if (LHSTy->isObjCIdType() &&
7291       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7292     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7293     return LHSTy;
7294   }
7295   if (RHSTy->isObjCIdType() &&
7296       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7297     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7298     return RHSTy;
7299   }
7300   // And the same for struct objc_selector* / SEL
7301   if (Context.isObjCSelType(LHSTy) &&
7302       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7303     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7304     return LHSTy;
7305   }
7306   if (Context.isObjCSelType(RHSTy) &&
7307       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7308     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7309     return RHSTy;
7310   }
7311   // Check constraints for Objective-C object pointers types.
7312   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7313 
7314     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7315       // Two identical object pointer types are always compatible.
7316       return LHSTy;
7317     }
7318     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7319     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7320     QualType compositeType = LHSTy;
7321 
7322     // If both operands are interfaces and either operand can be
7323     // assigned to the other, use that type as the composite
7324     // type. This allows
7325     //   xxx ? (A*) a : (B*) b
7326     // where B is a subclass of A.
7327     //
7328     // Additionally, as for assignment, if either type is 'id'
7329     // allow silent coercion. Finally, if the types are
7330     // incompatible then make sure to use 'id' as the composite
7331     // type so the result is acceptable for sending messages to.
7332 
7333     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7334     // It could return the composite type.
7335     if (!(compositeType =
7336           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7337       // Nothing more to do.
7338     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7339       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7340     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7341       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7342     } else if ((LHSTy->isObjCQualifiedIdType() ||
7343                 RHSTy->isObjCQualifiedIdType()) &&
7344                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7345       // Need to handle "id<xx>" explicitly.
7346       // GCC allows qualified id and any Objective-C type to devolve to
7347       // id. Currently localizing to here until clear this should be
7348       // part of ObjCQualifiedIdTypesAreCompatible.
7349       compositeType = Context.getObjCIdType();
7350     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7351       compositeType = Context.getObjCIdType();
7352     } else {
7353       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7354       << LHSTy << RHSTy
7355       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7356       QualType incompatTy = Context.getObjCIdType();
7357       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7358       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7359       return incompatTy;
7360     }
7361     // The object pointer types are compatible.
7362     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7363     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7364     return compositeType;
7365   }
7366   // Check Objective-C object pointer types and 'void *'
7367   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7368     if (getLangOpts().ObjCAutoRefCount) {
7369       // ARC forbids the implicit conversion of object pointers to 'void *',
7370       // so these types are not compatible.
7371       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7372           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7373       LHS = RHS = true;
7374       return QualType();
7375     }
7376     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7377     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7378     QualType destPointee
7379     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7380     QualType destType = Context.getPointerType(destPointee);
7381     // Add qualifiers if necessary.
7382     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7383     // Promote to void*.
7384     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7385     return destType;
7386   }
7387   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7388     if (getLangOpts().ObjCAutoRefCount) {
7389       // ARC forbids the implicit conversion of object pointers to 'void *',
7390       // so these types are not compatible.
7391       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7392           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7393       LHS = RHS = true;
7394       return QualType();
7395     }
7396     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7397     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7398     QualType destPointee
7399     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7400     QualType destType = Context.getPointerType(destPointee);
7401     // Add qualifiers if necessary.
7402     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7403     // Promote to void*.
7404     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7405     return destType;
7406   }
7407   return QualType();
7408 }
7409 
7410 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7411 /// ParenRange in parentheses.
7412 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7413                                const PartialDiagnostic &Note,
7414                                SourceRange ParenRange) {
7415   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7416   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7417       EndLoc.isValid()) {
7418     Self.Diag(Loc, Note)
7419       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7420       << FixItHint::CreateInsertion(EndLoc, ")");
7421   } else {
7422     // We can't display the parentheses, so just show the bare note.
7423     Self.Diag(Loc, Note) << ParenRange;
7424   }
7425 }
7426 
7427 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7428   return BinaryOperator::isAdditiveOp(Opc) ||
7429          BinaryOperator::isMultiplicativeOp(Opc) ||
7430          BinaryOperator::isShiftOp(Opc);
7431 }
7432 
7433 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7434 /// expression, either using a built-in or overloaded operator,
7435 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7436 /// expression.
7437 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7438                                    Expr **RHSExprs) {
7439   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7440   E = E->IgnoreImpCasts();
7441   E = E->IgnoreConversionOperator();
7442   E = E->IgnoreImpCasts();
7443   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7444     E = MTE->GetTemporaryExpr();
7445     E = E->IgnoreImpCasts();
7446   }
7447 
7448   // Built-in binary operator.
7449   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7450     if (IsArithmeticOp(OP->getOpcode())) {
7451       *Opcode = OP->getOpcode();
7452       *RHSExprs = OP->getRHS();
7453       return true;
7454     }
7455   }
7456 
7457   // Overloaded operator.
7458   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7459     if (Call->getNumArgs() != 2)
7460       return false;
7461 
7462     // Make sure this is really a binary operator that is safe to pass into
7463     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7464     OverloadedOperatorKind OO = Call->getOperator();
7465     if (OO < OO_Plus || OO > OO_Arrow ||
7466         OO == OO_PlusPlus || OO == OO_MinusMinus)
7467       return false;
7468 
7469     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7470     if (IsArithmeticOp(OpKind)) {
7471       *Opcode = OpKind;
7472       *RHSExprs = Call->getArg(1);
7473       return true;
7474     }
7475   }
7476 
7477   return false;
7478 }
7479 
7480 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7481 /// or is a logical expression such as (x==y) which has int type, but is
7482 /// commonly interpreted as boolean.
7483 static bool ExprLooksBoolean(Expr *E) {
7484   E = E->IgnoreParenImpCasts();
7485 
7486   if (E->getType()->isBooleanType())
7487     return true;
7488   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7489     return OP->isComparisonOp() || OP->isLogicalOp();
7490   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7491     return OP->getOpcode() == UO_LNot;
7492   if (E->getType()->isPointerType())
7493     return true;
7494   // FIXME: What about overloaded operator calls returning "unspecified boolean
7495   // type"s (commonly pointer-to-members)?
7496 
7497   return false;
7498 }
7499 
7500 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7501 /// and binary operator are mixed in a way that suggests the programmer assumed
7502 /// the conditional operator has higher precedence, for example:
7503 /// "int x = a + someBinaryCondition ? 1 : 2".
7504 static void DiagnoseConditionalPrecedence(Sema &Self,
7505                                           SourceLocation OpLoc,
7506                                           Expr *Condition,
7507                                           Expr *LHSExpr,
7508                                           Expr *RHSExpr) {
7509   BinaryOperatorKind CondOpcode;
7510   Expr *CondRHS;
7511 
7512   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7513     return;
7514   if (!ExprLooksBoolean(CondRHS))
7515     return;
7516 
7517   // The condition is an arithmetic binary expression, with a right-
7518   // hand side that looks boolean, so warn.
7519 
7520   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7521       << Condition->getSourceRange()
7522       << BinaryOperator::getOpcodeStr(CondOpcode);
7523 
7524   SuggestParentheses(
7525       Self, OpLoc,
7526       Self.PDiag(diag::note_precedence_silence)
7527           << BinaryOperator::getOpcodeStr(CondOpcode),
7528       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7529 
7530   SuggestParentheses(Self, OpLoc,
7531                      Self.PDiag(diag::note_precedence_conditional_first),
7532                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7533 }
7534 
7535 /// Compute the nullability of a conditional expression.
7536 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7537                                               QualType LHSTy, QualType RHSTy,
7538                                               ASTContext &Ctx) {
7539   if (!ResTy->isAnyPointerType())
7540     return ResTy;
7541 
7542   auto GetNullability = [&Ctx](QualType Ty) {
7543     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7544     if (Kind)
7545       return *Kind;
7546     return NullabilityKind::Unspecified;
7547   };
7548 
7549   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7550   NullabilityKind MergedKind;
7551 
7552   // Compute nullability of a binary conditional expression.
7553   if (IsBin) {
7554     if (LHSKind == NullabilityKind::NonNull)
7555       MergedKind = NullabilityKind::NonNull;
7556     else
7557       MergedKind = RHSKind;
7558   // Compute nullability of a normal conditional expression.
7559   } else {
7560     if (LHSKind == NullabilityKind::Nullable ||
7561         RHSKind == NullabilityKind::Nullable)
7562       MergedKind = NullabilityKind::Nullable;
7563     else if (LHSKind == NullabilityKind::NonNull)
7564       MergedKind = RHSKind;
7565     else if (RHSKind == NullabilityKind::NonNull)
7566       MergedKind = LHSKind;
7567     else
7568       MergedKind = NullabilityKind::Unspecified;
7569   }
7570 
7571   // Return if ResTy already has the correct nullability.
7572   if (GetNullability(ResTy) == MergedKind)
7573     return ResTy;
7574 
7575   // Strip all nullability from ResTy.
7576   while (ResTy->getNullability(Ctx))
7577     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7578 
7579   // Create a new AttributedType with the new nullability kind.
7580   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7581   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7582 }
7583 
7584 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7585 /// in the case of a the GNU conditional expr extension.
7586 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7587                                     SourceLocation ColonLoc,
7588                                     Expr *CondExpr, Expr *LHSExpr,
7589                                     Expr *RHSExpr) {
7590   if (!getLangOpts().CPlusPlus) {
7591     // C cannot handle TypoExpr nodes in the condition because it
7592     // doesn't handle dependent types properly, so make sure any TypoExprs have
7593     // been dealt with before checking the operands.
7594     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7595     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7596     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7597 
7598     if (!CondResult.isUsable())
7599       return ExprError();
7600 
7601     if (LHSExpr) {
7602       if (!LHSResult.isUsable())
7603         return ExprError();
7604     }
7605 
7606     if (!RHSResult.isUsable())
7607       return ExprError();
7608 
7609     CondExpr = CondResult.get();
7610     LHSExpr = LHSResult.get();
7611     RHSExpr = RHSResult.get();
7612   }
7613 
7614   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7615   // was the condition.
7616   OpaqueValueExpr *opaqueValue = nullptr;
7617   Expr *commonExpr = nullptr;
7618   if (!LHSExpr) {
7619     commonExpr = CondExpr;
7620     // Lower out placeholder types first.  This is important so that we don't
7621     // try to capture a placeholder. This happens in few cases in C++; such
7622     // as Objective-C++'s dictionary subscripting syntax.
7623     if (commonExpr->hasPlaceholderType()) {
7624       ExprResult result = CheckPlaceholderExpr(commonExpr);
7625       if (!result.isUsable()) return ExprError();
7626       commonExpr = result.get();
7627     }
7628     // We usually want to apply unary conversions *before* saving, except
7629     // in the special case of a C++ l-value conditional.
7630     if (!(getLangOpts().CPlusPlus
7631           && !commonExpr->isTypeDependent()
7632           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7633           && commonExpr->isGLValue()
7634           && commonExpr->isOrdinaryOrBitFieldObject()
7635           && RHSExpr->isOrdinaryOrBitFieldObject()
7636           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7637       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7638       if (commonRes.isInvalid())
7639         return ExprError();
7640       commonExpr = commonRes.get();
7641     }
7642 
7643     // If the common expression is a class or array prvalue, materialize it
7644     // so that we can safely refer to it multiple times.
7645     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7646                                    commonExpr->getType()->isArrayType())) {
7647       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7648       if (MatExpr.isInvalid())
7649         return ExprError();
7650       commonExpr = MatExpr.get();
7651     }
7652 
7653     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7654                                                 commonExpr->getType(),
7655                                                 commonExpr->getValueKind(),
7656                                                 commonExpr->getObjectKind(),
7657                                                 commonExpr);
7658     LHSExpr = CondExpr = opaqueValue;
7659   }
7660 
7661   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7662   ExprValueKind VK = VK_RValue;
7663   ExprObjectKind OK = OK_Ordinary;
7664   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7665   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7666                                              VK, OK, QuestionLoc);
7667   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7668       RHS.isInvalid())
7669     return ExprError();
7670 
7671   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7672                                 RHS.get());
7673 
7674   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7675 
7676   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7677                                          Context);
7678 
7679   if (!commonExpr)
7680     return new (Context)
7681         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7682                             RHS.get(), result, VK, OK);
7683 
7684   return new (Context) BinaryConditionalOperator(
7685       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7686       ColonLoc, result, VK, OK);
7687 }
7688 
7689 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7690 // being closely modeled after the C99 spec:-). The odd characteristic of this
7691 // routine is it effectively iqnores the qualifiers on the top level pointee.
7692 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7693 // FIXME: add a couple examples in this comment.
7694 static Sema::AssignConvertType
7695 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7696   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7697   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7698 
7699   // get the "pointed to" type (ignoring qualifiers at the top level)
7700   const Type *lhptee, *rhptee;
7701   Qualifiers lhq, rhq;
7702   std::tie(lhptee, lhq) =
7703       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7704   std::tie(rhptee, rhq) =
7705       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7706 
7707   Sema::AssignConvertType ConvTy = Sema::Compatible;
7708 
7709   // C99 6.5.16.1p1: This following citation is common to constraints
7710   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7711   // qualifiers of the type *pointed to* by the right;
7712 
7713   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7714   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7715       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7716     // Ignore lifetime for further calculation.
7717     lhq.removeObjCLifetime();
7718     rhq.removeObjCLifetime();
7719   }
7720 
7721   if (!lhq.compatiblyIncludes(rhq)) {
7722     // Treat address-space mismatches as fatal.  TODO: address subspaces
7723     if (!lhq.isAddressSpaceSupersetOf(rhq))
7724       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7725 
7726     // It's okay to add or remove GC or lifetime qualifiers when converting to
7727     // and from void*.
7728     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7729                         .compatiblyIncludes(
7730                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7731              && (lhptee->isVoidType() || rhptee->isVoidType()))
7732       ; // keep old
7733 
7734     // Treat lifetime mismatches as fatal.
7735     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7736       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7737 
7738     // For GCC/MS compatibility, other qualifier mismatches are treated
7739     // as still compatible in C.
7740     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7741   }
7742 
7743   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7744   // incomplete type and the other is a pointer to a qualified or unqualified
7745   // version of void...
7746   if (lhptee->isVoidType()) {
7747     if (rhptee->isIncompleteOrObjectType())
7748       return ConvTy;
7749 
7750     // As an extension, we allow cast to/from void* to function pointer.
7751     assert(rhptee->isFunctionType());
7752     return Sema::FunctionVoidPointer;
7753   }
7754 
7755   if (rhptee->isVoidType()) {
7756     if (lhptee->isIncompleteOrObjectType())
7757       return ConvTy;
7758 
7759     // As an extension, we allow cast to/from void* to function pointer.
7760     assert(lhptee->isFunctionType());
7761     return Sema::FunctionVoidPointer;
7762   }
7763 
7764   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7765   // unqualified versions of compatible types, ...
7766   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7767   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7768     // Check if the pointee types are compatible ignoring the sign.
7769     // We explicitly check for char so that we catch "char" vs
7770     // "unsigned char" on systems where "char" is unsigned.
7771     if (lhptee->isCharType())
7772       ltrans = S.Context.UnsignedCharTy;
7773     else if (lhptee->hasSignedIntegerRepresentation())
7774       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7775 
7776     if (rhptee->isCharType())
7777       rtrans = S.Context.UnsignedCharTy;
7778     else if (rhptee->hasSignedIntegerRepresentation())
7779       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7780 
7781     if (ltrans == rtrans) {
7782       // Types are compatible ignoring the sign. Qualifier incompatibility
7783       // takes priority over sign incompatibility because the sign
7784       // warning can be disabled.
7785       if (ConvTy != Sema::Compatible)
7786         return ConvTy;
7787 
7788       return Sema::IncompatiblePointerSign;
7789     }
7790 
7791     // If we are a multi-level pointer, it's possible that our issue is simply
7792     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7793     // the eventual target type is the same and the pointers have the same
7794     // level of indirection, this must be the issue.
7795     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7796       do {
7797         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7798         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7799       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7800 
7801       if (lhptee == rhptee)
7802         return Sema::IncompatibleNestedPointerQualifiers;
7803     }
7804 
7805     // General pointer incompatibility takes priority over qualifiers.
7806     return Sema::IncompatiblePointer;
7807   }
7808   if (!S.getLangOpts().CPlusPlus &&
7809       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7810     return Sema::IncompatiblePointer;
7811   return ConvTy;
7812 }
7813 
7814 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7815 /// block pointer types are compatible or whether a block and normal pointer
7816 /// are compatible. It is more restrict than comparing two function pointer
7817 // types.
7818 static Sema::AssignConvertType
7819 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7820                                     QualType RHSType) {
7821   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7822   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7823 
7824   QualType lhptee, rhptee;
7825 
7826   // get the "pointed to" type (ignoring qualifiers at the top level)
7827   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7828   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7829 
7830   // In C++, the types have to match exactly.
7831   if (S.getLangOpts().CPlusPlus)
7832     return Sema::IncompatibleBlockPointer;
7833 
7834   Sema::AssignConvertType ConvTy = Sema::Compatible;
7835 
7836   // For blocks we enforce that qualifiers are identical.
7837   Qualifiers LQuals = lhptee.getLocalQualifiers();
7838   Qualifiers RQuals = rhptee.getLocalQualifiers();
7839   if (S.getLangOpts().OpenCL) {
7840     LQuals.removeAddressSpace();
7841     RQuals.removeAddressSpace();
7842   }
7843   if (LQuals != RQuals)
7844     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7845 
7846   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7847   // assignment.
7848   // The current behavior is similar to C++ lambdas. A block might be
7849   // assigned to a variable iff its return type and parameters are compatible
7850   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7851   // an assignment. Presumably it should behave in way that a function pointer
7852   // assignment does in C, so for each parameter and return type:
7853   //  * CVR and address space of LHS should be a superset of CVR and address
7854   //  space of RHS.
7855   //  * unqualified types should be compatible.
7856   if (S.getLangOpts().OpenCL) {
7857     if (!S.Context.typesAreBlockPointerCompatible(
7858             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7859             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7860       return Sema::IncompatibleBlockPointer;
7861   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7862     return Sema::IncompatibleBlockPointer;
7863 
7864   return ConvTy;
7865 }
7866 
7867 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7868 /// for assignment compatibility.
7869 static Sema::AssignConvertType
7870 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7871                                    QualType RHSType) {
7872   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7873   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7874 
7875   if (LHSType->isObjCBuiltinType()) {
7876     // Class is not compatible with ObjC object pointers.
7877     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7878         !RHSType->isObjCQualifiedClassType())
7879       return Sema::IncompatiblePointer;
7880     return Sema::Compatible;
7881   }
7882   if (RHSType->isObjCBuiltinType()) {
7883     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7884         !LHSType->isObjCQualifiedClassType())
7885       return Sema::IncompatiblePointer;
7886     return Sema::Compatible;
7887   }
7888   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7889   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7890 
7891   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7892       // make an exception for id<P>
7893       !LHSType->isObjCQualifiedIdType())
7894     return Sema::CompatiblePointerDiscardsQualifiers;
7895 
7896   if (S.Context.typesAreCompatible(LHSType, RHSType))
7897     return Sema::Compatible;
7898   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7899     return Sema::IncompatibleObjCQualifiedId;
7900   return Sema::IncompatiblePointer;
7901 }
7902 
7903 Sema::AssignConvertType
7904 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7905                                  QualType LHSType, QualType RHSType) {
7906   // Fake up an opaque expression.  We don't actually care about what
7907   // cast operations are required, so if CheckAssignmentConstraints
7908   // adds casts to this they'll be wasted, but fortunately that doesn't
7909   // usually happen on valid code.
7910   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7911   ExprResult RHSPtr = &RHSExpr;
7912   CastKind K;
7913 
7914   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7915 }
7916 
7917 /// This helper function returns true if QT is a vector type that has element
7918 /// type ElementType.
7919 static bool isVector(QualType QT, QualType ElementType) {
7920   if (const VectorType *VT = QT->getAs<VectorType>())
7921     return VT->getElementType() == ElementType;
7922   return false;
7923 }
7924 
7925 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7926 /// has code to accommodate several GCC extensions when type checking
7927 /// pointers. Here are some objectionable examples that GCC considers warnings:
7928 ///
7929 ///  int a, *pint;
7930 ///  short *pshort;
7931 ///  struct foo *pfoo;
7932 ///
7933 ///  pint = pshort; // warning: assignment from incompatible pointer type
7934 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7935 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7936 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7937 ///
7938 /// As a result, the code for dealing with pointers is more complex than the
7939 /// C99 spec dictates.
7940 ///
7941 /// Sets 'Kind' for any result kind except Incompatible.
7942 Sema::AssignConvertType
7943 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7944                                  CastKind &Kind, bool ConvertRHS) {
7945   QualType RHSType = RHS.get()->getType();
7946   QualType OrigLHSType = LHSType;
7947 
7948   // Get canonical types.  We're not formatting these types, just comparing
7949   // them.
7950   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7951   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7952 
7953   // Common case: no conversion required.
7954   if (LHSType == RHSType) {
7955     Kind = CK_NoOp;
7956     return Compatible;
7957   }
7958 
7959   // If we have an atomic type, try a non-atomic assignment, then just add an
7960   // atomic qualification step.
7961   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7962     Sema::AssignConvertType result =
7963       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7964     if (result != Compatible)
7965       return result;
7966     if (Kind != CK_NoOp && ConvertRHS)
7967       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7968     Kind = CK_NonAtomicToAtomic;
7969     return Compatible;
7970   }
7971 
7972   // If the left-hand side is a reference type, then we are in a
7973   // (rare!) case where we've allowed the use of references in C,
7974   // e.g., as a parameter type in a built-in function. In this case,
7975   // just make sure that the type referenced is compatible with the
7976   // right-hand side type. The caller is responsible for adjusting
7977   // LHSType so that the resulting expression does not have reference
7978   // type.
7979   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7980     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7981       Kind = CK_LValueBitCast;
7982       return Compatible;
7983     }
7984     return Incompatible;
7985   }
7986 
7987   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7988   // to the same ExtVector type.
7989   if (LHSType->isExtVectorType()) {
7990     if (RHSType->isExtVectorType())
7991       return Incompatible;
7992     if (RHSType->isArithmeticType()) {
7993       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7994       if (ConvertRHS)
7995         RHS = prepareVectorSplat(LHSType, RHS.get());
7996       Kind = CK_VectorSplat;
7997       return Compatible;
7998     }
7999   }
8000 
8001   // Conversions to or from vector type.
8002   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8003     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8004       // Allow assignments of an AltiVec vector type to an equivalent GCC
8005       // vector type and vice versa
8006       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8007         Kind = CK_BitCast;
8008         return Compatible;
8009       }
8010 
8011       // If we are allowing lax vector conversions, and LHS and RHS are both
8012       // vectors, the total size only needs to be the same. This is a bitcast;
8013       // no bits are changed but the result type is different.
8014       if (isLaxVectorConversion(RHSType, LHSType)) {
8015         Kind = CK_BitCast;
8016         return IncompatibleVectors;
8017       }
8018     }
8019 
8020     // When the RHS comes from another lax conversion (e.g. binops between
8021     // scalars and vectors) the result is canonicalized as a vector. When the
8022     // LHS is also a vector, the lax is allowed by the condition above. Handle
8023     // the case where LHS is a scalar.
8024     if (LHSType->isScalarType()) {
8025       const VectorType *VecType = RHSType->getAs<VectorType>();
8026       if (VecType && VecType->getNumElements() == 1 &&
8027           isLaxVectorConversion(RHSType, LHSType)) {
8028         ExprResult *VecExpr = &RHS;
8029         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8030         Kind = CK_BitCast;
8031         return Compatible;
8032       }
8033     }
8034 
8035     return Incompatible;
8036   }
8037 
8038   // Diagnose attempts to convert between __float128 and long double where
8039   // such conversions currently can't be handled.
8040   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8041     return Incompatible;
8042 
8043   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8044   // discards the imaginary part.
8045   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8046       !LHSType->getAs<ComplexType>())
8047     return Incompatible;
8048 
8049   // Arithmetic conversions.
8050   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8051       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8052     if (ConvertRHS)
8053       Kind = PrepareScalarCast(RHS, LHSType);
8054     return Compatible;
8055   }
8056 
8057   // Conversions to normal pointers.
8058   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8059     // U* -> T*
8060     if (isa<PointerType>(RHSType)) {
8061       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8062       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8063       if (AddrSpaceL != AddrSpaceR)
8064         Kind = CK_AddressSpaceConversion;
8065       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8066         Kind = CK_NoOp;
8067       else
8068         Kind = CK_BitCast;
8069       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8070     }
8071 
8072     // int -> T*
8073     if (RHSType->isIntegerType()) {
8074       Kind = CK_IntegralToPointer; // FIXME: null?
8075       return IntToPointer;
8076     }
8077 
8078     // C pointers are not compatible with ObjC object pointers,
8079     // with two exceptions:
8080     if (isa<ObjCObjectPointerType>(RHSType)) {
8081       //  - conversions to void*
8082       if (LHSPointer->getPointeeType()->isVoidType()) {
8083         Kind = CK_BitCast;
8084         return Compatible;
8085       }
8086 
8087       //  - conversions from 'Class' to the redefinition type
8088       if (RHSType->isObjCClassType() &&
8089           Context.hasSameType(LHSType,
8090                               Context.getObjCClassRedefinitionType())) {
8091         Kind = CK_BitCast;
8092         return Compatible;
8093       }
8094 
8095       Kind = CK_BitCast;
8096       return IncompatiblePointer;
8097     }
8098 
8099     // U^ -> void*
8100     if (RHSType->getAs<BlockPointerType>()) {
8101       if (LHSPointer->getPointeeType()->isVoidType()) {
8102         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8103         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8104                                 ->getPointeeType()
8105                                 .getAddressSpace();
8106         Kind =
8107             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8108         return Compatible;
8109       }
8110     }
8111 
8112     return Incompatible;
8113   }
8114 
8115   // Conversions to block pointers.
8116   if (isa<BlockPointerType>(LHSType)) {
8117     // U^ -> T^
8118     if (RHSType->isBlockPointerType()) {
8119       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8120                               ->getPointeeType()
8121                               .getAddressSpace();
8122       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8123                               ->getPointeeType()
8124                               .getAddressSpace();
8125       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8126       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8127     }
8128 
8129     // int or null -> T^
8130     if (RHSType->isIntegerType()) {
8131       Kind = CK_IntegralToPointer; // FIXME: null
8132       return IntToBlockPointer;
8133     }
8134 
8135     // id -> T^
8136     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8137       Kind = CK_AnyPointerToBlockPointerCast;
8138       return Compatible;
8139     }
8140 
8141     // void* -> T^
8142     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8143       if (RHSPT->getPointeeType()->isVoidType()) {
8144         Kind = CK_AnyPointerToBlockPointerCast;
8145         return Compatible;
8146       }
8147 
8148     return Incompatible;
8149   }
8150 
8151   // Conversions to Objective-C pointers.
8152   if (isa<ObjCObjectPointerType>(LHSType)) {
8153     // A* -> B*
8154     if (RHSType->isObjCObjectPointerType()) {
8155       Kind = CK_BitCast;
8156       Sema::AssignConvertType result =
8157         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8158       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8159           result == Compatible &&
8160           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8161         result = IncompatibleObjCWeakRef;
8162       return result;
8163     }
8164 
8165     // int or null -> A*
8166     if (RHSType->isIntegerType()) {
8167       Kind = CK_IntegralToPointer; // FIXME: null
8168       return IntToPointer;
8169     }
8170 
8171     // In general, C pointers are not compatible with ObjC object pointers,
8172     // with two exceptions:
8173     if (isa<PointerType>(RHSType)) {
8174       Kind = CK_CPointerToObjCPointerCast;
8175 
8176       //  - conversions from 'void*'
8177       if (RHSType->isVoidPointerType()) {
8178         return Compatible;
8179       }
8180 
8181       //  - conversions to 'Class' from its redefinition type
8182       if (LHSType->isObjCClassType() &&
8183           Context.hasSameType(RHSType,
8184                               Context.getObjCClassRedefinitionType())) {
8185         return Compatible;
8186       }
8187 
8188       return IncompatiblePointer;
8189     }
8190 
8191     // Only under strict condition T^ is compatible with an Objective-C pointer.
8192     if (RHSType->isBlockPointerType() &&
8193         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8194       if (ConvertRHS)
8195         maybeExtendBlockObject(RHS);
8196       Kind = CK_BlockPointerToObjCPointerCast;
8197       return Compatible;
8198     }
8199 
8200     return Incompatible;
8201   }
8202 
8203   // Conversions from pointers that are not covered by the above.
8204   if (isa<PointerType>(RHSType)) {
8205     // T* -> _Bool
8206     if (LHSType == Context.BoolTy) {
8207       Kind = CK_PointerToBoolean;
8208       return Compatible;
8209     }
8210 
8211     // T* -> int
8212     if (LHSType->isIntegerType()) {
8213       Kind = CK_PointerToIntegral;
8214       return PointerToInt;
8215     }
8216 
8217     return Incompatible;
8218   }
8219 
8220   // Conversions from Objective-C pointers that are not covered by the above.
8221   if (isa<ObjCObjectPointerType>(RHSType)) {
8222     // T* -> _Bool
8223     if (LHSType == Context.BoolTy) {
8224       Kind = CK_PointerToBoolean;
8225       return Compatible;
8226     }
8227 
8228     // T* -> int
8229     if (LHSType->isIntegerType()) {
8230       Kind = CK_PointerToIntegral;
8231       return PointerToInt;
8232     }
8233 
8234     return Incompatible;
8235   }
8236 
8237   // struct A -> struct B
8238   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8239     if (Context.typesAreCompatible(LHSType, RHSType)) {
8240       Kind = CK_NoOp;
8241       return Compatible;
8242     }
8243   }
8244 
8245   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8246     Kind = CK_IntToOCLSampler;
8247     return Compatible;
8248   }
8249 
8250   return Incompatible;
8251 }
8252 
8253 /// Constructs a transparent union from an expression that is
8254 /// used to initialize the transparent union.
8255 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8256                                       ExprResult &EResult, QualType UnionType,
8257                                       FieldDecl *Field) {
8258   // Build an initializer list that designates the appropriate member
8259   // of the transparent union.
8260   Expr *E = EResult.get();
8261   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8262                                                    E, SourceLocation());
8263   Initializer->setType(UnionType);
8264   Initializer->setInitializedFieldInUnion(Field);
8265 
8266   // Build a compound literal constructing a value of the transparent
8267   // union type from this initializer list.
8268   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8269   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8270                                         VK_RValue, Initializer, false);
8271 }
8272 
8273 Sema::AssignConvertType
8274 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8275                                                ExprResult &RHS) {
8276   QualType RHSType = RHS.get()->getType();
8277 
8278   // If the ArgType is a Union type, we want to handle a potential
8279   // transparent_union GCC extension.
8280   const RecordType *UT = ArgType->getAsUnionType();
8281   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8282     return Incompatible;
8283 
8284   // The field to initialize within the transparent union.
8285   RecordDecl *UD = UT->getDecl();
8286   FieldDecl *InitField = nullptr;
8287   // It's compatible if the expression matches any of the fields.
8288   for (auto *it : UD->fields()) {
8289     if (it->getType()->isPointerType()) {
8290       // If the transparent union contains a pointer type, we allow:
8291       // 1) void pointer
8292       // 2) null pointer constant
8293       if (RHSType->isPointerType())
8294         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8295           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8296           InitField = it;
8297           break;
8298         }
8299 
8300       if (RHS.get()->isNullPointerConstant(Context,
8301                                            Expr::NPC_ValueDependentIsNull)) {
8302         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8303                                 CK_NullToPointer);
8304         InitField = it;
8305         break;
8306       }
8307     }
8308 
8309     CastKind Kind;
8310     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8311           == Compatible) {
8312       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8313       InitField = it;
8314       break;
8315     }
8316   }
8317 
8318   if (!InitField)
8319     return Incompatible;
8320 
8321   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8322   return Compatible;
8323 }
8324 
8325 Sema::AssignConvertType
8326 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8327                                        bool Diagnose,
8328                                        bool DiagnoseCFAudited,
8329                                        bool ConvertRHS) {
8330   // We need to be able to tell the caller whether we diagnosed a problem, if
8331   // they ask us to issue diagnostics.
8332   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8333 
8334   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8335   // we can't avoid *all* modifications at the moment, so we need some somewhere
8336   // to put the updated value.
8337   ExprResult LocalRHS = CallerRHS;
8338   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8339 
8340   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8341     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8342       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8343           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8344         Diag(RHS.get()->getExprLoc(),
8345              diag::warn_noderef_to_dereferenceable_pointer)
8346             << RHS.get()->getSourceRange();
8347       }
8348     }
8349   }
8350 
8351   if (getLangOpts().CPlusPlus) {
8352     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8353       // C++ 5.17p3: If the left operand is not of class type, the
8354       // expression is implicitly converted (C++ 4) to the
8355       // cv-unqualified type of the left operand.
8356       QualType RHSType = RHS.get()->getType();
8357       if (Diagnose) {
8358         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8359                                         AA_Assigning);
8360       } else {
8361         ImplicitConversionSequence ICS =
8362             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8363                                   /*SuppressUserConversions=*/false,
8364                                   /*AllowExplicit=*/false,
8365                                   /*InOverloadResolution=*/false,
8366                                   /*CStyle=*/false,
8367                                   /*AllowObjCWritebackConversion=*/false);
8368         if (ICS.isFailure())
8369           return Incompatible;
8370         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8371                                         ICS, AA_Assigning);
8372       }
8373       if (RHS.isInvalid())
8374         return Incompatible;
8375       Sema::AssignConvertType result = Compatible;
8376       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8377           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8378         result = IncompatibleObjCWeakRef;
8379       return result;
8380     }
8381 
8382     // FIXME: Currently, we fall through and treat C++ classes like C
8383     // structures.
8384     // FIXME: We also fall through for atomics; not sure what should
8385     // happen there, though.
8386   } else if (RHS.get()->getType() == Context.OverloadTy) {
8387     // As a set of extensions to C, we support overloading on functions. These
8388     // functions need to be resolved here.
8389     DeclAccessPair DAP;
8390     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8391             RHS.get(), LHSType, /*Complain=*/false, DAP))
8392       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8393     else
8394       return Incompatible;
8395   }
8396 
8397   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8398   // a null pointer constant.
8399   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8400        LHSType->isBlockPointerType()) &&
8401       RHS.get()->isNullPointerConstant(Context,
8402                                        Expr::NPC_ValueDependentIsNull)) {
8403     if (Diagnose || ConvertRHS) {
8404       CastKind Kind;
8405       CXXCastPath Path;
8406       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8407                              /*IgnoreBaseAccess=*/false, Diagnose);
8408       if (ConvertRHS)
8409         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8410     }
8411     return Compatible;
8412   }
8413 
8414   // OpenCL queue_t type assignment.
8415   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8416                                  Context, Expr::NPC_ValueDependentIsNull)) {
8417     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8418     return Compatible;
8419   }
8420 
8421   // This check seems unnatural, however it is necessary to ensure the proper
8422   // conversion of functions/arrays. If the conversion were done for all
8423   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8424   // expressions that suppress this implicit conversion (&, sizeof).
8425   //
8426   // Suppress this for references: C++ 8.5.3p5.
8427   if (!LHSType->isReferenceType()) {
8428     // FIXME: We potentially allocate here even if ConvertRHS is false.
8429     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8430     if (RHS.isInvalid())
8431       return Incompatible;
8432   }
8433   CastKind Kind;
8434   Sema::AssignConvertType result =
8435     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8436 
8437   // C99 6.5.16.1p2: The value of the right operand is converted to the
8438   // type of the assignment expression.
8439   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8440   // so that we can use references in built-in functions even in C.
8441   // The getNonReferenceType() call makes sure that the resulting expression
8442   // does not have reference type.
8443   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8444     QualType Ty = LHSType.getNonLValueExprType(Context);
8445     Expr *E = RHS.get();
8446 
8447     // Check for various Objective-C errors. If we are not reporting
8448     // diagnostics and just checking for errors, e.g., during overload
8449     // resolution, return Incompatible to indicate the failure.
8450     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8451         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8452                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8453       if (!Diagnose)
8454         return Incompatible;
8455     }
8456     if (getLangOpts().ObjC &&
8457         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8458                                            E->getType(), E, Diagnose) ||
8459          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8460       if (!Diagnose)
8461         return Incompatible;
8462       // Replace the expression with a corrected version and continue so we
8463       // can find further errors.
8464       RHS = E;
8465       return Compatible;
8466     }
8467 
8468     if (ConvertRHS)
8469       RHS = ImpCastExprToType(E, Ty, Kind);
8470   }
8471 
8472   return result;
8473 }
8474 
8475 namespace {
8476 /// The original operand to an operator, prior to the application of the usual
8477 /// arithmetic conversions and converting the arguments of a builtin operator
8478 /// candidate.
8479 struct OriginalOperand {
8480   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8481     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8482       Op = MTE->GetTemporaryExpr();
8483     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8484       Op = BTE->getSubExpr();
8485     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8486       Orig = ICE->getSubExprAsWritten();
8487       Conversion = ICE->getConversionFunction();
8488     }
8489   }
8490 
8491   QualType getType() const { return Orig->getType(); }
8492 
8493   Expr *Orig;
8494   NamedDecl *Conversion;
8495 };
8496 }
8497 
8498 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8499                                ExprResult &RHS) {
8500   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8501 
8502   Diag(Loc, diag::err_typecheck_invalid_operands)
8503     << OrigLHS.getType() << OrigRHS.getType()
8504     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8505 
8506   // If a user-defined conversion was applied to either of the operands prior
8507   // to applying the built-in operator rules, tell the user about it.
8508   if (OrigLHS.Conversion) {
8509     Diag(OrigLHS.Conversion->getLocation(),
8510          diag::note_typecheck_invalid_operands_converted)
8511       << 0 << LHS.get()->getType();
8512   }
8513   if (OrigRHS.Conversion) {
8514     Diag(OrigRHS.Conversion->getLocation(),
8515          diag::note_typecheck_invalid_operands_converted)
8516       << 1 << RHS.get()->getType();
8517   }
8518 
8519   return QualType();
8520 }
8521 
8522 // Diagnose cases where a scalar was implicitly converted to a vector and
8523 // diagnose the underlying types. Otherwise, diagnose the error
8524 // as invalid vector logical operands for non-C++ cases.
8525 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8526                                             ExprResult &RHS) {
8527   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8528   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8529 
8530   bool LHSNatVec = LHSType->isVectorType();
8531   bool RHSNatVec = RHSType->isVectorType();
8532 
8533   if (!(LHSNatVec && RHSNatVec)) {
8534     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8535     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8536     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8537         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8538         << Vector->getSourceRange();
8539     return QualType();
8540   }
8541 
8542   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8543       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8544       << RHS.get()->getSourceRange();
8545 
8546   return QualType();
8547 }
8548 
8549 /// Try to convert a value of non-vector type to a vector type by converting
8550 /// the type to the element type of the vector and then performing a splat.
8551 /// If the language is OpenCL, we only use conversions that promote scalar
8552 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8553 /// for float->int.
8554 ///
8555 /// OpenCL V2.0 6.2.6.p2:
8556 /// An error shall occur if any scalar operand type has greater rank
8557 /// than the type of the vector element.
8558 ///
8559 /// \param scalar - if non-null, actually perform the conversions
8560 /// \return true if the operation fails (but without diagnosing the failure)
8561 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8562                                      QualType scalarTy,
8563                                      QualType vectorEltTy,
8564                                      QualType vectorTy,
8565                                      unsigned &DiagID) {
8566   // The conversion to apply to the scalar before splatting it,
8567   // if necessary.
8568   CastKind scalarCast = CK_NoOp;
8569 
8570   if (vectorEltTy->isIntegralType(S.Context)) {
8571     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8572         (scalarTy->isIntegerType() &&
8573          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8574       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8575       return true;
8576     }
8577     if (!scalarTy->isIntegralType(S.Context))
8578       return true;
8579     scalarCast = CK_IntegralCast;
8580   } else if (vectorEltTy->isRealFloatingType()) {
8581     if (scalarTy->isRealFloatingType()) {
8582       if (S.getLangOpts().OpenCL &&
8583           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8584         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8585         return true;
8586       }
8587       scalarCast = CK_FloatingCast;
8588     }
8589     else if (scalarTy->isIntegralType(S.Context))
8590       scalarCast = CK_IntegralToFloating;
8591     else
8592       return true;
8593   } else {
8594     return true;
8595   }
8596 
8597   // Adjust scalar if desired.
8598   if (scalar) {
8599     if (scalarCast != CK_NoOp)
8600       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8601     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8602   }
8603   return false;
8604 }
8605 
8606 /// Convert vector E to a vector with the same number of elements but different
8607 /// element type.
8608 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8609   const auto *VecTy = E->getType()->getAs<VectorType>();
8610   assert(VecTy && "Expression E must be a vector");
8611   QualType NewVecTy = S.Context.getVectorType(ElementType,
8612                                               VecTy->getNumElements(),
8613                                               VecTy->getVectorKind());
8614 
8615   // Look through the implicit cast. Return the subexpression if its type is
8616   // NewVecTy.
8617   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8618     if (ICE->getSubExpr()->getType() == NewVecTy)
8619       return ICE->getSubExpr();
8620 
8621   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8622   return S.ImpCastExprToType(E, NewVecTy, Cast);
8623 }
8624 
8625 /// Test if a (constant) integer Int can be casted to another integer type
8626 /// IntTy without losing precision.
8627 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8628                                       QualType OtherIntTy) {
8629   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8630 
8631   // Reject cases where the value of the Int is unknown as that would
8632   // possibly cause truncation, but accept cases where the scalar can be
8633   // demoted without loss of precision.
8634   Expr::EvalResult EVResult;
8635   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8636   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8637   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8638   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8639 
8640   if (CstInt) {
8641     // If the scalar is constant and is of a higher order and has more active
8642     // bits that the vector element type, reject it.
8643     llvm::APSInt Result = EVResult.Val.getInt();
8644     unsigned NumBits = IntSigned
8645                            ? (Result.isNegative() ? Result.getMinSignedBits()
8646                                                   : Result.getActiveBits())
8647                            : Result.getActiveBits();
8648     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8649       return true;
8650 
8651     // If the signedness of the scalar type and the vector element type
8652     // differs and the number of bits is greater than that of the vector
8653     // element reject it.
8654     return (IntSigned != OtherIntSigned &&
8655             NumBits > S.Context.getIntWidth(OtherIntTy));
8656   }
8657 
8658   // Reject cases where the value of the scalar is not constant and it's
8659   // order is greater than that of the vector element type.
8660   return (Order < 0);
8661 }
8662 
8663 /// Test if a (constant) integer Int can be casted to floating point type
8664 /// FloatTy without losing precision.
8665 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8666                                      QualType FloatTy) {
8667   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8668 
8669   // Determine if the integer constant can be expressed as a floating point
8670   // number of the appropriate type.
8671   Expr::EvalResult EVResult;
8672   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8673 
8674   uint64_t Bits = 0;
8675   if (CstInt) {
8676     // Reject constants that would be truncated if they were converted to
8677     // the floating point type. Test by simple to/from conversion.
8678     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8679     //        could be avoided if there was a convertFromAPInt method
8680     //        which could signal back if implicit truncation occurred.
8681     llvm::APSInt Result = EVResult.Val.getInt();
8682     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8683     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8684                            llvm::APFloat::rmTowardZero);
8685     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8686                              !IntTy->hasSignedIntegerRepresentation());
8687     bool Ignored = false;
8688     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8689                            &Ignored);
8690     if (Result != ConvertBack)
8691       return true;
8692   } else {
8693     // Reject types that cannot be fully encoded into the mantissa of
8694     // the float.
8695     Bits = S.Context.getTypeSize(IntTy);
8696     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8697         S.Context.getFloatTypeSemantics(FloatTy));
8698     if (Bits > FloatPrec)
8699       return true;
8700   }
8701 
8702   return false;
8703 }
8704 
8705 /// Attempt to convert and splat Scalar into a vector whose types matches
8706 /// Vector following GCC conversion rules. The rule is that implicit
8707 /// conversion can occur when Scalar can be casted to match Vector's element
8708 /// type without causing truncation of Scalar.
8709 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8710                                         ExprResult *Vector) {
8711   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8712   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8713   const VectorType *VT = VectorTy->getAs<VectorType>();
8714 
8715   assert(!isa<ExtVectorType>(VT) &&
8716          "ExtVectorTypes should not be handled here!");
8717 
8718   QualType VectorEltTy = VT->getElementType();
8719 
8720   // Reject cases where the vector element type or the scalar element type are
8721   // not integral or floating point types.
8722   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8723     return true;
8724 
8725   // The conversion to apply to the scalar before splatting it,
8726   // if necessary.
8727   CastKind ScalarCast = CK_NoOp;
8728 
8729   // Accept cases where the vector elements are integers and the scalar is
8730   // an integer.
8731   // FIXME: Notionally if the scalar was a floating point value with a precise
8732   //        integral representation, we could cast it to an appropriate integer
8733   //        type and then perform the rest of the checks here. GCC will perform
8734   //        this conversion in some cases as determined by the input language.
8735   //        We should accept it on a language independent basis.
8736   if (VectorEltTy->isIntegralType(S.Context) &&
8737       ScalarTy->isIntegralType(S.Context) &&
8738       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8739 
8740     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8741       return true;
8742 
8743     ScalarCast = CK_IntegralCast;
8744   } else if (VectorEltTy->isRealFloatingType()) {
8745     if (ScalarTy->isRealFloatingType()) {
8746 
8747       // Reject cases where the scalar type is not a constant and has a higher
8748       // Order than the vector element type.
8749       llvm::APFloat Result(0.0);
8750       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8751       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8752       if (!CstScalar && Order < 0)
8753         return true;
8754 
8755       // If the scalar cannot be safely casted to the vector element type,
8756       // reject it.
8757       if (CstScalar) {
8758         bool Truncated = false;
8759         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8760                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8761         if (Truncated)
8762           return true;
8763       }
8764 
8765       ScalarCast = CK_FloatingCast;
8766     } else if (ScalarTy->isIntegralType(S.Context)) {
8767       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8768         return true;
8769 
8770       ScalarCast = CK_IntegralToFloating;
8771     } else
8772       return true;
8773   }
8774 
8775   // Adjust scalar if desired.
8776   if (Scalar) {
8777     if (ScalarCast != CK_NoOp)
8778       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8779     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8780   }
8781   return false;
8782 }
8783 
8784 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8785                                    SourceLocation Loc, bool IsCompAssign,
8786                                    bool AllowBothBool,
8787                                    bool AllowBoolConversions) {
8788   if (!IsCompAssign) {
8789     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8790     if (LHS.isInvalid())
8791       return QualType();
8792   }
8793   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8794   if (RHS.isInvalid())
8795     return QualType();
8796 
8797   // For conversion purposes, we ignore any qualifiers.
8798   // For example, "const float" and "float" are equivalent.
8799   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8800   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8801 
8802   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8803   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8804   assert(LHSVecType || RHSVecType);
8805 
8806   // AltiVec-style "vector bool op vector bool" combinations are allowed
8807   // for some operators but not others.
8808   if (!AllowBothBool &&
8809       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8810       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8811     return InvalidOperands(Loc, LHS, RHS);
8812 
8813   // If the vector types are identical, return.
8814   if (Context.hasSameType(LHSType, RHSType))
8815     return LHSType;
8816 
8817   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8818   if (LHSVecType && RHSVecType &&
8819       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8820     if (isa<ExtVectorType>(LHSVecType)) {
8821       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8822       return LHSType;
8823     }
8824 
8825     if (!IsCompAssign)
8826       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8827     return RHSType;
8828   }
8829 
8830   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8831   // can be mixed, with the result being the non-bool type.  The non-bool
8832   // operand must have integer element type.
8833   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8834       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8835       (Context.getTypeSize(LHSVecType->getElementType()) ==
8836        Context.getTypeSize(RHSVecType->getElementType()))) {
8837     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8838         LHSVecType->getElementType()->isIntegerType() &&
8839         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8840       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8841       return LHSType;
8842     }
8843     if (!IsCompAssign &&
8844         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8845         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8846         RHSVecType->getElementType()->isIntegerType()) {
8847       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8848       return RHSType;
8849     }
8850   }
8851 
8852   // If there's a vector type and a scalar, try to convert the scalar to
8853   // the vector element type and splat.
8854   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8855   if (!RHSVecType) {
8856     if (isa<ExtVectorType>(LHSVecType)) {
8857       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8858                                     LHSVecType->getElementType(), LHSType,
8859                                     DiagID))
8860         return LHSType;
8861     } else {
8862       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8863         return LHSType;
8864     }
8865   }
8866   if (!LHSVecType) {
8867     if (isa<ExtVectorType>(RHSVecType)) {
8868       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8869                                     LHSType, RHSVecType->getElementType(),
8870                                     RHSType, DiagID))
8871         return RHSType;
8872     } else {
8873       if (LHS.get()->getValueKind() == VK_LValue ||
8874           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8875         return RHSType;
8876     }
8877   }
8878 
8879   // FIXME: The code below also handles conversion between vectors and
8880   // non-scalars, we should break this down into fine grained specific checks
8881   // and emit proper diagnostics.
8882   QualType VecType = LHSVecType ? LHSType : RHSType;
8883   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8884   QualType OtherType = LHSVecType ? RHSType : LHSType;
8885   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8886   if (isLaxVectorConversion(OtherType, VecType)) {
8887     // If we're allowing lax vector conversions, only the total (data) size
8888     // needs to be the same. For non compound assignment, if one of the types is
8889     // scalar, the result is always the vector type.
8890     if (!IsCompAssign) {
8891       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8892       return VecType;
8893     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8894     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8895     // type. Note that this is already done by non-compound assignments in
8896     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8897     // <1 x T> -> T. The result is also a vector type.
8898     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8899                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8900       ExprResult *RHSExpr = &RHS;
8901       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8902       return VecType;
8903     }
8904   }
8905 
8906   // Okay, the expression is invalid.
8907 
8908   // If there's a non-vector, non-real operand, diagnose that.
8909   if ((!RHSVecType && !RHSType->isRealType()) ||
8910       (!LHSVecType && !LHSType->isRealType())) {
8911     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8912       << LHSType << RHSType
8913       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8914     return QualType();
8915   }
8916 
8917   // OpenCL V1.1 6.2.6.p1:
8918   // If the operands are of more than one vector type, then an error shall
8919   // occur. Implicit conversions between vector types are not permitted, per
8920   // section 6.2.1.
8921   if (getLangOpts().OpenCL &&
8922       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8923       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8924     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8925                                                            << RHSType;
8926     return QualType();
8927   }
8928 
8929 
8930   // If there is a vector type that is not a ExtVector and a scalar, we reach
8931   // this point if scalar could not be converted to the vector's element type
8932   // without truncation.
8933   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8934       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8935     QualType Scalar = LHSVecType ? RHSType : LHSType;
8936     QualType Vector = LHSVecType ? LHSType : RHSType;
8937     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8938     Diag(Loc,
8939          diag::err_typecheck_vector_not_convertable_implict_truncation)
8940         << ScalarOrVector << Scalar << Vector;
8941 
8942     return QualType();
8943   }
8944 
8945   // Otherwise, use the generic diagnostic.
8946   Diag(Loc, DiagID)
8947     << LHSType << RHSType
8948     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8949   return QualType();
8950 }
8951 
8952 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8953 // expression.  These are mainly cases where the null pointer is used as an
8954 // integer instead of a pointer.
8955 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8956                                 SourceLocation Loc, bool IsCompare) {
8957   // The canonical way to check for a GNU null is with isNullPointerConstant,
8958   // but we use a bit of a hack here for speed; this is a relatively
8959   // hot path, and isNullPointerConstant is slow.
8960   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8961   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8962 
8963   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8964 
8965   // Avoid analyzing cases where the result will either be invalid (and
8966   // diagnosed as such) or entirely valid and not something to warn about.
8967   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8968       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8969     return;
8970 
8971   // Comparison operations would not make sense with a null pointer no matter
8972   // what the other expression is.
8973   if (!IsCompare) {
8974     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8975         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8976         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8977     return;
8978   }
8979 
8980   // The rest of the operations only make sense with a null pointer
8981   // if the other expression is a pointer.
8982   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8983       NonNullType->canDecayToPointerType())
8984     return;
8985 
8986   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8987       << LHSNull /* LHS is NULL */ << NonNullType
8988       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8989 }
8990 
8991 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8992                                           SourceLocation Loc) {
8993   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8994   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
8995   if (!LUE || !RUE)
8996     return;
8997   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
8998       RUE->getKind() != UETT_SizeOf)
8999     return;
9000 
9001   QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
9002   QualType RHSTy;
9003 
9004   if (RUE->isArgumentType())
9005     RHSTy = RUE->getArgumentType();
9006   else
9007     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9008 
9009   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
9010     return;
9011   if (LHSTy->getPointeeType() != RHSTy)
9012     return;
9013 
9014   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9015 }
9016 
9017 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9018                                                ExprResult &RHS,
9019                                                SourceLocation Loc, bool IsDiv) {
9020   // Check for division/remainder by zero.
9021   Expr::EvalResult RHSValue;
9022   if (!RHS.get()->isValueDependent() &&
9023       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9024       RHSValue.Val.getInt() == 0)
9025     S.DiagRuntimeBehavior(Loc, RHS.get(),
9026                           S.PDiag(diag::warn_remainder_division_by_zero)
9027                             << IsDiv << RHS.get()->getSourceRange());
9028 }
9029 
9030 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9031                                            SourceLocation Loc,
9032                                            bool IsCompAssign, bool IsDiv) {
9033   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9034 
9035   if (LHS.get()->getType()->isVectorType() ||
9036       RHS.get()->getType()->isVectorType())
9037     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9038                                /*AllowBothBool*/getLangOpts().AltiVec,
9039                                /*AllowBoolConversions*/false);
9040 
9041   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9042   if (LHS.isInvalid() || RHS.isInvalid())
9043     return QualType();
9044 
9045 
9046   if (compType.isNull() || !compType->isArithmeticType())
9047     return InvalidOperands(Loc, LHS, RHS);
9048   if (IsDiv) {
9049     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9050     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9051   }
9052   return compType;
9053 }
9054 
9055 QualType Sema::CheckRemainderOperands(
9056   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9057   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9058 
9059   if (LHS.get()->getType()->isVectorType() ||
9060       RHS.get()->getType()->isVectorType()) {
9061     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9062         RHS.get()->getType()->hasIntegerRepresentation())
9063       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9064                                  /*AllowBothBool*/getLangOpts().AltiVec,
9065                                  /*AllowBoolConversions*/false);
9066     return InvalidOperands(Loc, LHS, RHS);
9067   }
9068 
9069   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9070   if (LHS.isInvalid() || RHS.isInvalid())
9071     return QualType();
9072 
9073   if (compType.isNull() || !compType->isIntegerType())
9074     return InvalidOperands(Loc, LHS, RHS);
9075   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9076   return compType;
9077 }
9078 
9079 /// Diagnose invalid arithmetic on two void pointers.
9080 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9081                                                 Expr *LHSExpr, Expr *RHSExpr) {
9082   S.Diag(Loc, S.getLangOpts().CPlusPlus
9083                 ? diag::err_typecheck_pointer_arith_void_type
9084                 : diag::ext_gnu_void_ptr)
9085     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9086                             << RHSExpr->getSourceRange();
9087 }
9088 
9089 /// Diagnose invalid arithmetic on a void pointer.
9090 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9091                                             Expr *Pointer) {
9092   S.Diag(Loc, S.getLangOpts().CPlusPlus
9093                 ? diag::err_typecheck_pointer_arith_void_type
9094                 : diag::ext_gnu_void_ptr)
9095     << 0 /* one pointer */ << Pointer->getSourceRange();
9096 }
9097 
9098 /// Diagnose invalid arithmetic on a null pointer.
9099 ///
9100 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9101 /// idiom, which we recognize as a GNU extension.
9102 ///
9103 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9104                                             Expr *Pointer, bool IsGNUIdiom) {
9105   if (IsGNUIdiom)
9106     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9107       << Pointer->getSourceRange();
9108   else
9109     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9110       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9111 }
9112 
9113 /// Diagnose invalid arithmetic on two function pointers.
9114 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9115                                                     Expr *LHS, Expr *RHS) {
9116   assert(LHS->getType()->isAnyPointerType());
9117   assert(RHS->getType()->isAnyPointerType());
9118   S.Diag(Loc, S.getLangOpts().CPlusPlus
9119                 ? diag::err_typecheck_pointer_arith_function_type
9120                 : diag::ext_gnu_ptr_func_arith)
9121     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9122     // We only show the second type if it differs from the first.
9123     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9124                                                    RHS->getType())
9125     << RHS->getType()->getPointeeType()
9126     << LHS->getSourceRange() << RHS->getSourceRange();
9127 }
9128 
9129 /// Diagnose invalid arithmetic on a function pointer.
9130 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9131                                                 Expr *Pointer) {
9132   assert(Pointer->getType()->isAnyPointerType());
9133   S.Diag(Loc, S.getLangOpts().CPlusPlus
9134                 ? diag::err_typecheck_pointer_arith_function_type
9135                 : diag::ext_gnu_ptr_func_arith)
9136     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9137     << 0 /* one pointer, so only one type */
9138     << Pointer->getSourceRange();
9139 }
9140 
9141 /// Emit error if Operand is incomplete pointer type
9142 ///
9143 /// \returns True if pointer has incomplete type
9144 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9145                                                  Expr *Operand) {
9146   QualType ResType = Operand->getType();
9147   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9148     ResType = ResAtomicType->getValueType();
9149 
9150   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9151   QualType PointeeTy = ResType->getPointeeType();
9152   return S.RequireCompleteType(Loc, PointeeTy,
9153                                diag::err_typecheck_arithmetic_incomplete_type,
9154                                PointeeTy, Operand->getSourceRange());
9155 }
9156 
9157 /// Check the validity of an arithmetic pointer operand.
9158 ///
9159 /// If the operand has pointer type, this code will check for pointer types
9160 /// which are invalid in arithmetic operations. These will be diagnosed
9161 /// appropriately, including whether or not the use is supported as an
9162 /// extension.
9163 ///
9164 /// \returns True when the operand is valid to use (even if as an extension).
9165 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9166                                             Expr *Operand) {
9167   QualType ResType = Operand->getType();
9168   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9169     ResType = ResAtomicType->getValueType();
9170 
9171   if (!ResType->isAnyPointerType()) return true;
9172 
9173   QualType PointeeTy = ResType->getPointeeType();
9174   if (PointeeTy->isVoidType()) {
9175     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9176     return !S.getLangOpts().CPlusPlus;
9177   }
9178   if (PointeeTy->isFunctionType()) {
9179     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9180     return !S.getLangOpts().CPlusPlus;
9181   }
9182 
9183   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9184 
9185   return true;
9186 }
9187 
9188 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9189 /// operands.
9190 ///
9191 /// This routine will diagnose any invalid arithmetic on pointer operands much
9192 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9193 /// for emitting a single diagnostic even for operations where both LHS and RHS
9194 /// are (potentially problematic) pointers.
9195 ///
9196 /// \returns True when the operand is valid to use (even if as an extension).
9197 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9198                                                 Expr *LHSExpr, Expr *RHSExpr) {
9199   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9200   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9201   if (!isLHSPointer && !isRHSPointer) return true;
9202 
9203   QualType LHSPointeeTy, RHSPointeeTy;
9204   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9205   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9206 
9207   // if both are pointers check if operation is valid wrt address spaces
9208   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9209     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9210     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9211     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9212       S.Diag(Loc,
9213              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9214           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9215           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9216       return false;
9217     }
9218   }
9219 
9220   // Check for arithmetic on pointers to incomplete types.
9221   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9222   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9223   if (isLHSVoidPtr || isRHSVoidPtr) {
9224     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9225     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9226     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9227 
9228     return !S.getLangOpts().CPlusPlus;
9229   }
9230 
9231   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9232   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9233   if (isLHSFuncPtr || isRHSFuncPtr) {
9234     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9235     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9236                                                                 RHSExpr);
9237     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9238 
9239     return !S.getLangOpts().CPlusPlus;
9240   }
9241 
9242   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9243     return false;
9244   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9245     return false;
9246 
9247   return true;
9248 }
9249 
9250 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9251 /// literal.
9252 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9253                                   Expr *LHSExpr, Expr *RHSExpr) {
9254   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9255   Expr* IndexExpr = RHSExpr;
9256   if (!StrExpr) {
9257     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9258     IndexExpr = LHSExpr;
9259   }
9260 
9261   bool IsStringPlusInt = StrExpr &&
9262       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9263   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9264     return;
9265 
9266   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9267   Self.Diag(OpLoc, diag::warn_string_plus_int)
9268       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9269 
9270   // Only print a fixit for "str" + int, not for int + "str".
9271   if (IndexExpr == RHSExpr) {
9272     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9273     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9274         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9275         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9276         << FixItHint::CreateInsertion(EndLoc, "]");
9277   } else
9278     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9279 }
9280 
9281 /// Emit a warning when adding a char literal to a string.
9282 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9283                                    Expr *LHSExpr, Expr *RHSExpr) {
9284   const Expr *StringRefExpr = LHSExpr;
9285   const CharacterLiteral *CharExpr =
9286       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9287 
9288   if (!CharExpr) {
9289     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9290     StringRefExpr = RHSExpr;
9291   }
9292 
9293   if (!CharExpr || !StringRefExpr)
9294     return;
9295 
9296   const QualType StringType = StringRefExpr->getType();
9297 
9298   // Return if not a PointerType.
9299   if (!StringType->isAnyPointerType())
9300     return;
9301 
9302   // Return if not a CharacterType.
9303   if (!StringType->getPointeeType()->isAnyCharacterType())
9304     return;
9305 
9306   ASTContext &Ctx = Self.getASTContext();
9307   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9308 
9309   const QualType CharType = CharExpr->getType();
9310   if (!CharType->isAnyCharacterType() &&
9311       CharType->isIntegerType() &&
9312       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9313     Self.Diag(OpLoc, diag::warn_string_plus_char)
9314         << DiagRange << Ctx.CharTy;
9315   } else {
9316     Self.Diag(OpLoc, diag::warn_string_plus_char)
9317         << DiagRange << CharExpr->getType();
9318   }
9319 
9320   // Only print a fixit for str + char, not for char + str.
9321   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9322     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9323     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9324         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9325         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9326         << FixItHint::CreateInsertion(EndLoc, "]");
9327   } else {
9328     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9329   }
9330 }
9331 
9332 /// Emit error when two pointers are incompatible.
9333 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9334                                            Expr *LHSExpr, Expr *RHSExpr) {
9335   assert(LHSExpr->getType()->isAnyPointerType());
9336   assert(RHSExpr->getType()->isAnyPointerType());
9337   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9338     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9339     << RHSExpr->getSourceRange();
9340 }
9341 
9342 // C99 6.5.6
9343 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9344                                      SourceLocation Loc, BinaryOperatorKind Opc,
9345                                      QualType* CompLHSTy) {
9346   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9347 
9348   if (LHS.get()->getType()->isVectorType() ||
9349       RHS.get()->getType()->isVectorType()) {
9350     QualType compType = CheckVectorOperands(
9351         LHS, RHS, Loc, CompLHSTy,
9352         /*AllowBothBool*/getLangOpts().AltiVec,
9353         /*AllowBoolConversions*/getLangOpts().ZVector);
9354     if (CompLHSTy) *CompLHSTy = compType;
9355     return compType;
9356   }
9357 
9358   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9359   if (LHS.isInvalid() || RHS.isInvalid())
9360     return QualType();
9361 
9362   // Diagnose "string literal" '+' int and string '+' "char literal".
9363   if (Opc == BO_Add) {
9364     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9365     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9366   }
9367 
9368   // handle the common case first (both operands are arithmetic).
9369   if (!compType.isNull() && compType->isArithmeticType()) {
9370     if (CompLHSTy) *CompLHSTy = compType;
9371     return compType;
9372   }
9373 
9374   // Type-checking.  Ultimately the pointer's going to be in PExp;
9375   // note that we bias towards the LHS being the pointer.
9376   Expr *PExp = LHS.get(), *IExp = RHS.get();
9377 
9378   bool isObjCPointer;
9379   if (PExp->getType()->isPointerType()) {
9380     isObjCPointer = false;
9381   } else if (PExp->getType()->isObjCObjectPointerType()) {
9382     isObjCPointer = true;
9383   } else {
9384     std::swap(PExp, IExp);
9385     if (PExp->getType()->isPointerType()) {
9386       isObjCPointer = false;
9387     } else if (PExp->getType()->isObjCObjectPointerType()) {
9388       isObjCPointer = true;
9389     } else {
9390       return InvalidOperands(Loc, LHS, RHS);
9391     }
9392   }
9393   assert(PExp->getType()->isAnyPointerType());
9394 
9395   if (!IExp->getType()->isIntegerType())
9396     return InvalidOperands(Loc, LHS, RHS);
9397 
9398   // Adding to a null pointer results in undefined behavior.
9399   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9400           Context, Expr::NPC_ValueDependentIsNotNull)) {
9401     // In C++ adding zero to a null pointer is defined.
9402     Expr::EvalResult KnownVal;
9403     if (!getLangOpts().CPlusPlus ||
9404         (!IExp->isValueDependent() &&
9405          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9406           KnownVal.Val.getInt() != 0))) {
9407       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9408       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9409           Context, BO_Add, PExp, IExp);
9410       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9411     }
9412   }
9413 
9414   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9415     return QualType();
9416 
9417   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9418     return QualType();
9419 
9420   // Check array bounds for pointer arithemtic
9421   CheckArrayAccess(PExp, IExp);
9422 
9423   if (CompLHSTy) {
9424     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9425     if (LHSTy.isNull()) {
9426       LHSTy = LHS.get()->getType();
9427       if (LHSTy->isPromotableIntegerType())
9428         LHSTy = Context.getPromotedIntegerType(LHSTy);
9429     }
9430     *CompLHSTy = LHSTy;
9431   }
9432 
9433   return PExp->getType();
9434 }
9435 
9436 // C99 6.5.6
9437 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9438                                         SourceLocation Loc,
9439                                         QualType* CompLHSTy) {
9440   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9441 
9442   if (LHS.get()->getType()->isVectorType() ||
9443       RHS.get()->getType()->isVectorType()) {
9444     QualType compType = CheckVectorOperands(
9445         LHS, RHS, Loc, CompLHSTy,
9446         /*AllowBothBool*/getLangOpts().AltiVec,
9447         /*AllowBoolConversions*/getLangOpts().ZVector);
9448     if (CompLHSTy) *CompLHSTy = compType;
9449     return compType;
9450   }
9451 
9452   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9453   if (LHS.isInvalid() || RHS.isInvalid())
9454     return QualType();
9455 
9456   // Enforce type constraints: C99 6.5.6p3.
9457 
9458   // Handle the common case first (both operands are arithmetic).
9459   if (!compType.isNull() && compType->isArithmeticType()) {
9460     if (CompLHSTy) *CompLHSTy = compType;
9461     return compType;
9462   }
9463 
9464   // Either ptr - int   or   ptr - ptr.
9465   if (LHS.get()->getType()->isAnyPointerType()) {
9466     QualType lpointee = LHS.get()->getType()->getPointeeType();
9467 
9468     // Diagnose bad cases where we step over interface counts.
9469     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9470         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9471       return QualType();
9472 
9473     // The result type of a pointer-int computation is the pointer type.
9474     if (RHS.get()->getType()->isIntegerType()) {
9475       // Subtracting from a null pointer should produce a warning.
9476       // The last argument to the diagnose call says this doesn't match the
9477       // GNU int-to-pointer idiom.
9478       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9479                                            Expr::NPC_ValueDependentIsNotNull)) {
9480         // In C++ adding zero to a null pointer is defined.
9481         Expr::EvalResult KnownVal;
9482         if (!getLangOpts().CPlusPlus ||
9483             (!RHS.get()->isValueDependent() &&
9484              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9485               KnownVal.Val.getInt() != 0))) {
9486           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9487         }
9488       }
9489 
9490       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9491         return QualType();
9492 
9493       // Check array bounds for pointer arithemtic
9494       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9495                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9496 
9497       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9498       return LHS.get()->getType();
9499     }
9500 
9501     // Handle pointer-pointer subtractions.
9502     if (const PointerType *RHSPTy
9503           = RHS.get()->getType()->getAs<PointerType>()) {
9504       QualType rpointee = RHSPTy->getPointeeType();
9505 
9506       if (getLangOpts().CPlusPlus) {
9507         // Pointee types must be the same: C++ [expr.add]
9508         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9509           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9510         }
9511       } else {
9512         // Pointee types must be compatible C99 6.5.6p3
9513         if (!Context.typesAreCompatible(
9514                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9515                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9516           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9517           return QualType();
9518         }
9519       }
9520 
9521       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9522                                                LHS.get(), RHS.get()))
9523         return QualType();
9524 
9525       // FIXME: Add warnings for nullptr - ptr.
9526 
9527       // The pointee type may have zero size.  As an extension, a structure or
9528       // union may have zero size or an array may have zero length.  In this
9529       // case subtraction does not make sense.
9530       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9531         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9532         if (ElementSize.isZero()) {
9533           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9534             << rpointee.getUnqualifiedType()
9535             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9536         }
9537       }
9538 
9539       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9540       return Context.getPointerDiffType();
9541     }
9542   }
9543 
9544   return InvalidOperands(Loc, LHS, RHS);
9545 }
9546 
9547 static bool isScopedEnumerationType(QualType T) {
9548   if (const EnumType *ET = T->getAs<EnumType>())
9549     return ET->getDecl()->isScoped();
9550   return false;
9551 }
9552 
9553 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9554                                    SourceLocation Loc, BinaryOperatorKind Opc,
9555                                    QualType LHSType) {
9556   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9557   // so skip remaining warnings as we don't want to modify values within Sema.
9558   if (S.getLangOpts().OpenCL)
9559     return;
9560 
9561   // Check right/shifter operand
9562   Expr::EvalResult RHSResult;
9563   if (RHS.get()->isValueDependent() ||
9564       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9565     return;
9566   llvm::APSInt Right = RHSResult.Val.getInt();
9567 
9568   if (Right.isNegative()) {
9569     S.DiagRuntimeBehavior(Loc, RHS.get(),
9570                           S.PDiag(diag::warn_shift_negative)
9571                             << RHS.get()->getSourceRange());
9572     return;
9573   }
9574   llvm::APInt LeftBits(Right.getBitWidth(),
9575                        S.Context.getTypeSize(LHS.get()->getType()));
9576   if (Right.uge(LeftBits)) {
9577     S.DiagRuntimeBehavior(Loc, RHS.get(),
9578                           S.PDiag(diag::warn_shift_gt_typewidth)
9579                             << RHS.get()->getSourceRange());
9580     return;
9581   }
9582   if (Opc != BO_Shl)
9583     return;
9584 
9585   // When left shifting an ICE which is signed, we can check for overflow which
9586   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9587   // integers have defined behavior modulo one more than the maximum value
9588   // representable in the result type, so never warn for those.
9589   Expr::EvalResult LHSResult;
9590   if (LHS.get()->isValueDependent() ||
9591       LHSType->hasUnsignedIntegerRepresentation() ||
9592       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9593     return;
9594   llvm::APSInt Left = LHSResult.Val.getInt();
9595 
9596   // If LHS does not have a signed type and non-negative value
9597   // then, the behavior is undefined. Warn about it.
9598   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9599     S.DiagRuntimeBehavior(Loc, LHS.get(),
9600                           S.PDiag(diag::warn_shift_lhs_negative)
9601                             << LHS.get()->getSourceRange());
9602     return;
9603   }
9604 
9605   llvm::APInt ResultBits =
9606       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9607   if (LeftBits.uge(ResultBits))
9608     return;
9609   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9610   Result = Result.shl(Right);
9611 
9612   // Print the bit representation of the signed integer as an unsigned
9613   // hexadecimal number.
9614   SmallString<40> HexResult;
9615   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9616 
9617   // If we are only missing a sign bit, this is less likely to result in actual
9618   // bugs -- if the result is cast back to an unsigned type, it will have the
9619   // expected value. Thus we place this behind a different warning that can be
9620   // turned off separately if needed.
9621   if (LeftBits == ResultBits - 1) {
9622     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9623         << HexResult << LHSType
9624         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9625     return;
9626   }
9627 
9628   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9629     << HexResult.str() << Result.getMinSignedBits() << LHSType
9630     << Left.getBitWidth() << LHS.get()->getSourceRange()
9631     << RHS.get()->getSourceRange();
9632 }
9633 
9634 /// Return the resulting type when a vector is shifted
9635 ///        by a scalar or vector shift amount.
9636 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9637                                  SourceLocation Loc, bool IsCompAssign) {
9638   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9639   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9640       !LHS.get()->getType()->isVectorType()) {
9641     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9642       << RHS.get()->getType() << LHS.get()->getType()
9643       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9644     return QualType();
9645   }
9646 
9647   if (!IsCompAssign) {
9648     LHS = S.UsualUnaryConversions(LHS.get());
9649     if (LHS.isInvalid()) return QualType();
9650   }
9651 
9652   RHS = S.UsualUnaryConversions(RHS.get());
9653   if (RHS.isInvalid()) return QualType();
9654 
9655   QualType LHSType = LHS.get()->getType();
9656   // Note that LHS might be a scalar because the routine calls not only in
9657   // OpenCL case.
9658   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9659   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9660 
9661   // Note that RHS might not be a vector.
9662   QualType RHSType = RHS.get()->getType();
9663   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9664   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9665 
9666   // The operands need to be integers.
9667   if (!LHSEleType->isIntegerType()) {
9668     S.Diag(Loc, diag::err_typecheck_expect_int)
9669       << LHS.get()->getType() << LHS.get()->getSourceRange();
9670     return QualType();
9671   }
9672 
9673   if (!RHSEleType->isIntegerType()) {
9674     S.Diag(Loc, diag::err_typecheck_expect_int)
9675       << RHS.get()->getType() << RHS.get()->getSourceRange();
9676     return QualType();
9677   }
9678 
9679   if (!LHSVecTy) {
9680     assert(RHSVecTy);
9681     if (IsCompAssign)
9682       return RHSType;
9683     if (LHSEleType != RHSEleType) {
9684       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9685       LHSEleType = RHSEleType;
9686     }
9687     QualType VecTy =
9688         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9689     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9690     LHSType = VecTy;
9691   } else if (RHSVecTy) {
9692     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9693     // are applied component-wise. So if RHS is a vector, then ensure
9694     // that the number of elements is the same as LHS...
9695     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9696       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9697         << LHS.get()->getType() << RHS.get()->getType()
9698         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9699       return QualType();
9700     }
9701     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9702       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9703       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9704       if (LHSBT != RHSBT &&
9705           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9706         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9707             << LHS.get()->getType() << RHS.get()->getType()
9708             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9709       }
9710     }
9711   } else {
9712     // ...else expand RHS to match the number of elements in LHS.
9713     QualType VecTy =
9714       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9715     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9716   }
9717 
9718   return LHSType;
9719 }
9720 
9721 // C99 6.5.7
9722 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9723                                   SourceLocation Loc, BinaryOperatorKind Opc,
9724                                   bool IsCompAssign) {
9725   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9726 
9727   // Vector shifts promote their scalar inputs to vector type.
9728   if (LHS.get()->getType()->isVectorType() ||
9729       RHS.get()->getType()->isVectorType()) {
9730     if (LangOpts.ZVector) {
9731       // The shift operators for the z vector extensions work basically
9732       // like general shifts, except that neither the LHS nor the RHS is
9733       // allowed to be a "vector bool".
9734       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9735         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9736           return InvalidOperands(Loc, LHS, RHS);
9737       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9738         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9739           return InvalidOperands(Loc, LHS, RHS);
9740     }
9741     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9742   }
9743 
9744   // Shifts don't perform usual arithmetic conversions, they just do integer
9745   // promotions on each operand. C99 6.5.7p3
9746 
9747   // For the LHS, do usual unary conversions, but then reset them away
9748   // if this is a compound assignment.
9749   ExprResult OldLHS = LHS;
9750   LHS = UsualUnaryConversions(LHS.get());
9751   if (LHS.isInvalid())
9752     return QualType();
9753   QualType LHSType = LHS.get()->getType();
9754   if (IsCompAssign) LHS = OldLHS;
9755 
9756   // The RHS is simpler.
9757   RHS = UsualUnaryConversions(RHS.get());
9758   if (RHS.isInvalid())
9759     return QualType();
9760   QualType RHSType = RHS.get()->getType();
9761 
9762   // C99 6.5.7p2: Each of the operands shall have integer type.
9763   if (!LHSType->hasIntegerRepresentation() ||
9764       !RHSType->hasIntegerRepresentation())
9765     return InvalidOperands(Loc, LHS, RHS);
9766 
9767   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9768   // hasIntegerRepresentation() above instead of this.
9769   if (isScopedEnumerationType(LHSType) ||
9770       isScopedEnumerationType(RHSType)) {
9771     return InvalidOperands(Loc, LHS, RHS);
9772   }
9773   // Sanity-check shift operands
9774   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9775 
9776   // "The type of the result is that of the promoted left operand."
9777   return LHSType;
9778 }
9779 
9780 /// If two different enums are compared, raise a warning.
9781 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9782                                 Expr *RHS) {
9783   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9784   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9785 
9786   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9787   if (!LHSEnumType)
9788     return;
9789   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9790   if (!RHSEnumType)
9791     return;
9792 
9793   // Ignore anonymous enums.
9794   if (!LHSEnumType->getDecl()->getIdentifier() &&
9795       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9796     return;
9797   if (!RHSEnumType->getDecl()->getIdentifier() &&
9798       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9799     return;
9800 
9801   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9802     return;
9803 
9804   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9805       << LHSStrippedType << RHSStrippedType
9806       << LHS->getSourceRange() << RHS->getSourceRange();
9807 }
9808 
9809 /// Diagnose bad pointer comparisons.
9810 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9811                                               ExprResult &LHS, ExprResult &RHS,
9812                                               bool IsError) {
9813   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9814                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9815     << LHS.get()->getType() << RHS.get()->getType()
9816     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9817 }
9818 
9819 /// Returns false if the pointers are converted to a composite type,
9820 /// true otherwise.
9821 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9822                                            ExprResult &LHS, ExprResult &RHS) {
9823   // C++ [expr.rel]p2:
9824   //   [...] Pointer conversions (4.10) and qualification
9825   //   conversions (4.4) are performed on pointer operands (or on
9826   //   a pointer operand and a null pointer constant) to bring
9827   //   them to their composite pointer type. [...]
9828   //
9829   // C++ [expr.eq]p1 uses the same notion for (in)equality
9830   // comparisons of pointers.
9831 
9832   QualType LHSType = LHS.get()->getType();
9833   QualType RHSType = RHS.get()->getType();
9834   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9835          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9836 
9837   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9838   if (T.isNull()) {
9839     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9840         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9841       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9842     else
9843       S.InvalidOperands(Loc, LHS, RHS);
9844     return true;
9845   }
9846 
9847   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9848   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9849   return false;
9850 }
9851 
9852 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9853                                                     ExprResult &LHS,
9854                                                     ExprResult &RHS,
9855                                                     bool IsError) {
9856   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9857                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9858     << LHS.get()->getType() << RHS.get()->getType()
9859     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9860 }
9861 
9862 static bool isObjCObjectLiteral(ExprResult &E) {
9863   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9864   case Stmt::ObjCArrayLiteralClass:
9865   case Stmt::ObjCDictionaryLiteralClass:
9866   case Stmt::ObjCStringLiteralClass:
9867   case Stmt::ObjCBoxedExprClass:
9868     return true;
9869   default:
9870     // Note that ObjCBoolLiteral is NOT an object literal!
9871     return false;
9872   }
9873 }
9874 
9875 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9876   const ObjCObjectPointerType *Type =
9877     LHS->getType()->getAs<ObjCObjectPointerType>();
9878 
9879   // If this is not actually an Objective-C object, bail out.
9880   if (!Type)
9881     return false;
9882 
9883   // Get the LHS object's interface type.
9884   QualType InterfaceType = Type->getPointeeType();
9885 
9886   // If the RHS isn't an Objective-C object, bail out.
9887   if (!RHS->getType()->isObjCObjectPointerType())
9888     return false;
9889 
9890   // Try to find the -isEqual: method.
9891   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9892   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9893                                                       InterfaceType,
9894                                                       /*instance=*/true);
9895   if (!Method) {
9896     if (Type->isObjCIdType()) {
9897       // For 'id', just check the global pool.
9898       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9899                                                   /*receiverId=*/true);
9900     } else {
9901       // Check protocols.
9902       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9903                                              /*instance=*/true);
9904     }
9905   }
9906 
9907   if (!Method)
9908     return false;
9909 
9910   QualType T = Method->parameters()[0]->getType();
9911   if (!T->isObjCObjectPointerType())
9912     return false;
9913 
9914   QualType R = Method->getReturnType();
9915   if (!R->isScalarType())
9916     return false;
9917 
9918   return true;
9919 }
9920 
9921 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9922   FromE = FromE->IgnoreParenImpCasts();
9923   switch (FromE->getStmtClass()) {
9924     default:
9925       break;
9926     case Stmt::ObjCStringLiteralClass:
9927       // "string literal"
9928       return LK_String;
9929     case Stmt::ObjCArrayLiteralClass:
9930       // "array literal"
9931       return LK_Array;
9932     case Stmt::ObjCDictionaryLiteralClass:
9933       // "dictionary literal"
9934       return LK_Dictionary;
9935     case Stmt::BlockExprClass:
9936       return LK_Block;
9937     case Stmt::ObjCBoxedExprClass: {
9938       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9939       switch (Inner->getStmtClass()) {
9940         case Stmt::IntegerLiteralClass:
9941         case Stmt::FloatingLiteralClass:
9942         case Stmt::CharacterLiteralClass:
9943         case Stmt::ObjCBoolLiteralExprClass:
9944         case Stmt::CXXBoolLiteralExprClass:
9945           // "numeric literal"
9946           return LK_Numeric;
9947         case Stmt::ImplicitCastExprClass: {
9948           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9949           // Boolean literals can be represented by implicit casts.
9950           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9951             return LK_Numeric;
9952           break;
9953         }
9954         default:
9955           break;
9956       }
9957       return LK_Boxed;
9958     }
9959   }
9960   return LK_None;
9961 }
9962 
9963 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9964                                           ExprResult &LHS, ExprResult &RHS,
9965                                           BinaryOperator::Opcode Opc){
9966   Expr *Literal;
9967   Expr *Other;
9968   if (isObjCObjectLiteral(LHS)) {
9969     Literal = LHS.get();
9970     Other = RHS.get();
9971   } else {
9972     Literal = RHS.get();
9973     Other = LHS.get();
9974   }
9975 
9976   // Don't warn on comparisons against nil.
9977   Other = Other->IgnoreParenCasts();
9978   if (Other->isNullPointerConstant(S.getASTContext(),
9979                                    Expr::NPC_ValueDependentIsNotNull))
9980     return;
9981 
9982   // This should be kept in sync with warn_objc_literal_comparison.
9983   // LK_String should always be after the other literals, since it has its own
9984   // warning flag.
9985   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9986   assert(LiteralKind != Sema::LK_Block);
9987   if (LiteralKind == Sema::LK_None) {
9988     llvm_unreachable("Unknown Objective-C object literal kind");
9989   }
9990 
9991   if (LiteralKind == Sema::LK_String)
9992     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9993       << Literal->getSourceRange();
9994   else
9995     S.Diag(Loc, diag::warn_objc_literal_comparison)
9996       << LiteralKind << Literal->getSourceRange();
9997 
9998   if (BinaryOperator::isEqualityOp(Opc) &&
9999       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10000     SourceLocation Start = LHS.get()->getBeginLoc();
10001     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10002     CharSourceRange OpRange =
10003       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10004 
10005     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10006       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10007       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10008       << FixItHint::CreateInsertion(End, "]");
10009   }
10010 }
10011 
10012 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10013 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10014                                            ExprResult &RHS, SourceLocation Loc,
10015                                            BinaryOperatorKind Opc) {
10016   // Check that left hand side is !something.
10017   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10018   if (!UO || UO->getOpcode() != UO_LNot) return;
10019 
10020   // Only check if the right hand side is non-bool arithmetic type.
10021   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10022 
10023   // Make sure that the something in !something is not bool.
10024   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10025   if (SubExpr->isKnownToHaveBooleanValue()) return;
10026 
10027   // Emit warning.
10028   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10029   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10030       << Loc << IsBitwiseOp;
10031 
10032   // First note suggest !(x < y)
10033   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10034   SourceLocation FirstClose = RHS.get()->getEndLoc();
10035   FirstClose = S.getLocForEndOfToken(FirstClose);
10036   if (FirstClose.isInvalid())
10037     FirstOpen = SourceLocation();
10038   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10039       << IsBitwiseOp
10040       << FixItHint::CreateInsertion(FirstOpen, "(")
10041       << FixItHint::CreateInsertion(FirstClose, ")");
10042 
10043   // Second note suggests (!x) < y
10044   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10045   SourceLocation SecondClose = LHS.get()->getEndLoc();
10046   SecondClose = S.getLocForEndOfToken(SecondClose);
10047   if (SecondClose.isInvalid())
10048     SecondOpen = SourceLocation();
10049   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10050       << FixItHint::CreateInsertion(SecondOpen, "(")
10051       << FixItHint::CreateInsertion(SecondClose, ")");
10052 }
10053 
10054 // Get the decl for a simple expression: a reference to a variable,
10055 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10056 static ValueDecl *getCompareDecl(Expr *E) {
10057   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10058     return DR->getDecl();
10059   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10060     if (Ivar->isFreeIvar())
10061       return Ivar->getDecl();
10062   }
10063   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10064     if (Mem->isImplicitAccess())
10065       return Mem->getMemberDecl();
10066   }
10067   return nullptr;
10068 }
10069 
10070 /// Diagnose some forms of syntactically-obvious tautological comparison.
10071 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10072                                            Expr *LHS, Expr *RHS,
10073                                            BinaryOperatorKind Opc) {
10074   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10075   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10076 
10077   QualType LHSType = LHS->getType();
10078   QualType RHSType = RHS->getType();
10079   if (LHSType->hasFloatingRepresentation() ||
10080       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10081       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10082       S.inTemplateInstantiation())
10083     return;
10084 
10085   // Comparisons between two array types are ill-formed for operator<=>, so
10086   // we shouldn't emit any additional warnings about it.
10087   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10088     return;
10089 
10090   // For non-floating point types, check for self-comparisons of the form
10091   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10092   // often indicate logic errors in the program.
10093   //
10094   // NOTE: Don't warn about comparison expressions resulting from macro
10095   // expansion. Also don't warn about comparisons which are only self
10096   // comparisons within a template instantiation. The warnings should catch
10097   // obvious cases in the definition of the template anyways. The idea is to
10098   // warn when the typed comparison operator will always evaluate to the same
10099   // result.
10100   ValueDecl *DL = getCompareDecl(LHSStripped);
10101   ValueDecl *DR = getCompareDecl(RHSStripped);
10102   if (DL && DR && declaresSameEntity(DL, DR)) {
10103     StringRef Result;
10104     switch (Opc) {
10105     case BO_EQ: case BO_LE: case BO_GE:
10106       Result = "true";
10107       break;
10108     case BO_NE: case BO_LT: case BO_GT:
10109       Result = "false";
10110       break;
10111     case BO_Cmp:
10112       Result = "'std::strong_ordering::equal'";
10113       break;
10114     default:
10115       break;
10116     }
10117     S.DiagRuntimeBehavior(Loc, nullptr,
10118                           S.PDiag(diag::warn_comparison_always)
10119                               << 0 /*self-comparison*/ << !Result.empty()
10120                               << Result);
10121   } else if (DL && DR &&
10122              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10123              !DL->isWeak() && !DR->isWeak()) {
10124     // What is it always going to evaluate to?
10125     StringRef Result;
10126     switch(Opc) {
10127     case BO_EQ: // e.g. array1 == array2
10128       Result = "false";
10129       break;
10130     case BO_NE: // e.g. array1 != array2
10131       Result = "true";
10132       break;
10133     default: // e.g. array1 <= array2
10134       // The best we can say is 'a constant'
10135       break;
10136     }
10137     S.DiagRuntimeBehavior(Loc, nullptr,
10138                           S.PDiag(diag::warn_comparison_always)
10139                               << 1 /*array comparison*/
10140                               << !Result.empty() << Result);
10141   }
10142 
10143   if (isa<CastExpr>(LHSStripped))
10144     LHSStripped = LHSStripped->IgnoreParenCasts();
10145   if (isa<CastExpr>(RHSStripped))
10146     RHSStripped = RHSStripped->IgnoreParenCasts();
10147 
10148   // Warn about comparisons against a string constant (unless the other
10149   // operand is null); the user probably wants strcmp.
10150   Expr *LiteralString = nullptr;
10151   Expr *LiteralStringStripped = nullptr;
10152   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10153       !RHSStripped->isNullPointerConstant(S.Context,
10154                                           Expr::NPC_ValueDependentIsNull)) {
10155     LiteralString = LHS;
10156     LiteralStringStripped = LHSStripped;
10157   } else if ((isa<StringLiteral>(RHSStripped) ||
10158               isa<ObjCEncodeExpr>(RHSStripped)) &&
10159              !LHSStripped->isNullPointerConstant(S.Context,
10160                                           Expr::NPC_ValueDependentIsNull)) {
10161     LiteralString = RHS;
10162     LiteralStringStripped = RHSStripped;
10163   }
10164 
10165   if (LiteralString) {
10166     S.DiagRuntimeBehavior(Loc, nullptr,
10167                           S.PDiag(diag::warn_stringcompare)
10168                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10169                               << LiteralString->getSourceRange());
10170   }
10171 }
10172 
10173 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10174   switch (CK) {
10175   default: {
10176 #ifndef NDEBUG
10177     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10178                  << "\n";
10179 #endif
10180     llvm_unreachable("unhandled cast kind");
10181   }
10182   case CK_UserDefinedConversion:
10183     return ICK_Identity;
10184   case CK_LValueToRValue:
10185     return ICK_Lvalue_To_Rvalue;
10186   case CK_ArrayToPointerDecay:
10187     return ICK_Array_To_Pointer;
10188   case CK_FunctionToPointerDecay:
10189     return ICK_Function_To_Pointer;
10190   case CK_IntegralCast:
10191     return ICK_Integral_Conversion;
10192   case CK_FloatingCast:
10193     return ICK_Floating_Conversion;
10194   case CK_IntegralToFloating:
10195   case CK_FloatingToIntegral:
10196     return ICK_Floating_Integral;
10197   case CK_IntegralComplexCast:
10198   case CK_FloatingComplexCast:
10199   case CK_FloatingComplexToIntegralComplex:
10200   case CK_IntegralComplexToFloatingComplex:
10201     return ICK_Complex_Conversion;
10202   case CK_FloatingComplexToReal:
10203   case CK_FloatingRealToComplex:
10204   case CK_IntegralComplexToReal:
10205   case CK_IntegralRealToComplex:
10206     return ICK_Complex_Real;
10207   }
10208 }
10209 
10210 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10211                                              QualType FromType,
10212                                              SourceLocation Loc) {
10213   // Check for a narrowing implicit conversion.
10214   StandardConversionSequence SCS;
10215   SCS.setAsIdentityConversion();
10216   SCS.setToType(0, FromType);
10217   SCS.setToType(1, ToType);
10218   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10219     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10220 
10221   APValue PreNarrowingValue;
10222   QualType PreNarrowingType;
10223   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10224                                PreNarrowingType,
10225                                /*IgnoreFloatToIntegralConversion*/ true)) {
10226   case NK_Dependent_Narrowing:
10227     // Implicit conversion to a narrower type, but the expression is
10228     // value-dependent so we can't tell whether it's actually narrowing.
10229   case NK_Not_Narrowing:
10230     return false;
10231 
10232   case NK_Constant_Narrowing:
10233     // Implicit conversion to a narrower type, and the value is not a constant
10234     // expression.
10235     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10236         << /*Constant*/ 1
10237         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10238     return true;
10239 
10240   case NK_Variable_Narrowing:
10241     // Implicit conversion to a narrower type, and the value is not a constant
10242     // expression.
10243   case NK_Type_Narrowing:
10244     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10245         << /*Constant*/ 0 << FromType << ToType;
10246     // TODO: It's not a constant expression, but what if the user intended it
10247     // to be? Can we produce notes to help them figure out why it isn't?
10248     return true;
10249   }
10250   llvm_unreachable("unhandled case in switch");
10251 }
10252 
10253 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10254                                                          ExprResult &LHS,
10255                                                          ExprResult &RHS,
10256                                                          SourceLocation Loc) {
10257   using CCT = ComparisonCategoryType;
10258 
10259   QualType LHSType = LHS.get()->getType();
10260   QualType RHSType = RHS.get()->getType();
10261   // Dig out the original argument type and expression before implicit casts
10262   // were applied. These are the types/expressions we need to check the
10263   // [expr.spaceship] requirements against.
10264   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10265   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10266   QualType LHSStrippedType = LHSStripped.get()->getType();
10267   QualType RHSStrippedType = RHSStripped.get()->getType();
10268 
10269   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10270   // other is not, the program is ill-formed.
10271   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10272     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10273     return QualType();
10274   }
10275 
10276   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10277                     RHSStrippedType->isEnumeralType();
10278   if (NumEnumArgs == 1) {
10279     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10280     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10281     if (OtherTy->hasFloatingRepresentation()) {
10282       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10283       return QualType();
10284     }
10285   }
10286   if (NumEnumArgs == 2) {
10287     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10288     // type E, the operator yields the result of converting the operands
10289     // to the underlying type of E and applying <=> to the converted operands.
10290     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10291       S.InvalidOperands(Loc, LHS, RHS);
10292       return QualType();
10293     }
10294     QualType IntType =
10295         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10296     assert(IntType->isArithmeticType());
10297 
10298     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10299     // promote the boolean type, and all other promotable integer types, to
10300     // avoid this.
10301     if (IntType->isPromotableIntegerType())
10302       IntType = S.Context.getPromotedIntegerType(IntType);
10303 
10304     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10305     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10306     LHSType = RHSType = IntType;
10307   }
10308 
10309   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10310   // usual arithmetic conversions are applied to the operands.
10311   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10312   if (LHS.isInvalid() || RHS.isInvalid())
10313     return QualType();
10314   if (Type.isNull())
10315     return S.InvalidOperands(Loc, LHS, RHS);
10316   assert(Type->isArithmeticType() || Type->isEnumeralType());
10317 
10318   bool HasNarrowing = checkThreeWayNarrowingConversion(
10319       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10320   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10321                                                    RHS.get()->getBeginLoc());
10322   if (HasNarrowing)
10323     return QualType();
10324 
10325   assert(!Type.isNull() && "composite type for <=> has not been set");
10326 
10327   auto TypeKind = [&]() {
10328     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10329       if (CT->getElementType()->hasFloatingRepresentation())
10330         return CCT::WeakEquality;
10331       return CCT::StrongEquality;
10332     }
10333     if (Type->isIntegralOrEnumerationType())
10334       return CCT::StrongOrdering;
10335     if (Type->hasFloatingRepresentation())
10336       return CCT::PartialOrdering;
10337     llvm_unreachable("other types are unimplemented");
10338   }();
10339 
10340   return S.CheckComparisonCategoryType(TypeKind, Loc);
10341 }
10342 
10343 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10344                                                  ExprResult &RHS,
10345                                                  SourceLocation Loc,
10346                                                  BinaryOperatorKind Opc) {
10347   if (Opc == BO_Cmp)
10348     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10349 
10350   // C99 6.5.8p3 / C99 6.5.9p4
10351   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10352   if (LHS.isInvalid() || RHS.isInvalid())
10353     return QualType();
10354   if (Type.isNull())
10355     return S.InvalidOperands(Loc, LHS, RHS);
10356   assert(Type->isArithmeticType() || Type->isEnumeralType());
10357 
10358   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10359 
10360   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10361     return S.InvalidOperands(Loc, LHS, RHS);
10362 
10363   // Check for comparisons of floating point operands using != and ==.
10364   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10365     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10366 
10367   // The result of comparisons is 'bool' in C++, 'int' in C.
10368   return S.Context.getLogicalOperationType();
10369 }
10370 
10371 // C99 6.5.8, C++ [expr.rel]
10372 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10373                                     SourceLocation Loc,
10374                                     BinaryOperatorKind Opc) {
10375   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10376   bool IsThreeWay = Opc == BO_Cmp;
10377   auto IsAnyPointerType = [](ExprResult E) {
10378     QualType Ty = E.get()->getType();
10379     return Ty->isPointerType() || Ty->isMemberPointerType();
10380   };
10381 
10382   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10383   // type, array-to-pointer, ..., conversions are performed on both operands to
10384   // bring them to their composite type.
10385   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10386   // any type-related checks.
10387   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10388     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10389     if (LHS.isInvalid())
10390       return QualType();
10391     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10392     if (RHS.isInvalid())
10393       return QualType();
10394   } else {
10395     LHS = DefaultLvalueConversion(LHS.get());
10396     if (LHS.isInvalid())
10397       return QualType();
10398     RHS = DefaultLvalueConversion(RHS.get());
10399     if (RHS.isInvalid())
10400       return QualType();
10401   }
10402 
10403   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10404 
10405   // Handle vector comparisons separately.
10406   if (LHS.get()->getType()->isVectorType() ||
10407       RHS.get()->getType()->isVectorType())
10408     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10409 
10410   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10411   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10412 
10413   QualType LHSType = LHS.get()->getType();
10414   QualType RHSType = RHS.get()->getType();
10415   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10416       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10417     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10418 
10419   const Expr::NullPointerConstantKind LHSNullKind =
10420       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10421   const Expr::NullPointerConstantKind RHSNullKind =
10422       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10423   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10424   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10425 
10426   auto computeResultTy = [&]() {
10427     if (Opc != BO_Cmp)
10428       return Context.getLogicalOperationType();
10429     assert(getLangOpts().CPlusPlus);
10430     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10431 
10432     QualType CompositeTy = LHS.get()->getType();
10433     assert(!CompositeTy->isReferenceType());
10434 
10435     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10436       return CheckComparisonCategoryType(Kind, Loc);
10437     };
10438 
10439     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10440     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10441     // result is of type std::strong_equality
10442     if (CompositeTy->isFunctionPointerType() ||
10443         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10444       // FIXME: consider making the function pointer case produce
10445       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10446       // and direction polls
10447       return buildResultTy(ComparisonCategoryType::StrongEquality);
10448 
10449     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10450     // pointer type, p <=> q is of type std::strong_ordering.
10451     if (CompositeTy->isPointerType()) {
10452       // P0946R0: Comparisons between a null pointer constant and an object
10453       // pointer result in std::strong_equality
10454       if (LHSIsNull != RHSIsNull)
10455         return buildResultTy(ComparisonCategoryType::StrongEquality);
10456       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10457     }
10458     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10459     // TODO: Extend support for operator<=> to ObjC types.
10460     return InvalidOperands(Loc, LHS, RHS);
10461   };
10462 
10463 
10464   if (!IsRelational && LHSIsNull != RHSIsNull) {
10465     bool IsEquality = Opc == BO_EQ;
10466     if (RHSIsNull)
10467       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10468                                    RHS.get()->getSourceRange());
10469     else
10470       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10471                                    LHS.get()->getSourceRange());
10472   }
10473 
10474   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10475       (RHSType->isIntegerType() && !RHSIsNull)) {
10476     // Skip normal pointer conversion checks in this case; we have better
10477     // diagnostics for this below.
10478   } else if (getLangOpts().CPlusPlus) {
10479     // Equality comparison of a function pointer to a void pointer is invalid,
10480     // but we allow it as an extension.
10481     // FIXME: If we really want to allow this, should it be part of composite
10482     // pointer type computation so it works in conditionals too?
10483     if (!IsRelational &&
10484         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10485          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10486       // This is a gcc extension compatibility comparison.
10487       // In a SFINAE context, we treat this as a hard error to maintain
10488       // conformance with the C++ standard.
10489       diagnoseFunctionPointerToVoidComparison(
10490           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10491 
10492       if (isSFINAEContext())
10493         return QualType();
10494 
10495       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10496       return computeResultTy();
10497     }
10498 
10499     // C++ [expr.eq]p2:
10500     //   If at least one operand is a pointer [...] bring them to their
10501     //   composite pointer type.
10502     // C++ [expr.spaceship]p6
10503     //  If at least one of the operands is of pointer type, [...] bring them
10504     //  to their composite pointer type.
10505     // C++ [expr.rel]p2:
10506     //   If both operands are pointers, [...] bring them to their composite
10507     //   pointer type.
10508     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10509             (IsRelational ? 2 : 1) &&
10510         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10511                                          RHSType->isObjCObjectPointerType()))) {
10512       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10513         return QualType();
10514       return computeResultTy();
10515     }
10516   } else if (LHSType->isPointerType() &&
10517              RHSType->isPointerType()) { // C99 6.5.8p2
10518     // All of the following pointer-related warnings are GCC extensions, except
10519     // when handling null pointer constants.
10520     QualType LCanPointeeTy =
10521       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10522     QualType RCanPointeeTy =
10523       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10524 
10525     // C99 6.5.9p2 and C99 6.5.8p2
10526     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10527                                    RCanPointeeTy.getUnqualifiedType())) {
10528       // Valid unless a relational comparison of function pointers
10529       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10530         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10531           << LHSType << RHSType << LHS.get()->getSourceRange()
10532           << RHS.get()->getSourceRange();
10533       }
10534     } else if (!IsRelational &&
10535                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10536       // Valid unless comparison between non-null pointer and function pointer
10537       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10538           && !LHSIsNull && !RHSIsNull)
10539         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10540                                                 /*isError*/false);
10541     } else {
10542       // Invalid
10543       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10544     }
10545     if (LCanPointeeTy != RCanPointeeTy) {
10546       // Treat NULL constant as a special case in OpenCL.
10547       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10548         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10549         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10550           Diag(Loc,
10551                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10552               << LHSType << RHSType << 0 /* comparison */
10553               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10554         }
10555       }
10556       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10557       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10558       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10559                                                : CK_BitCast;
10560       if (LHSIsNull && !RHSIsNull)
10561         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10562       else
10563         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10564     }
10565     return computeResultTy();
10566   }
10567 
10568   if (getLangOpts().CPlusPlus) {
10569     // C++ [expr.eq]p4:
10570     //   Two operands of type std::nullptr_t or one operand of type
10571     //   std::nullptr_t and the other a null pointer constant compare equal.
10572     if (!IsRelational && LHSIsNull && RHSIsNull) {
10573       if (LHSType->isNullPtrType()) {
10574         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10575         return computeResultTy();
10576       }
10577       if (RHSType->isNullPtrType()) {
10578         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10579         return computeResultTy();
10580       }
10581     }
10582 
10583     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10584     // These aren't covered by the composite pointer type rules.
10585     if (!IsRelational && RHSType->isNullPtrType() &&
10586         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10587       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10588       return computeResultTy();
10589     }
10590     if (!IsRelational && LHSType->isNullPtrType() &&
10591         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10592       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10593       return computeResultTy();
10594     }
10595 
10596     if (IsRelational &&
10597         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10598          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10599       // HACK: Relational comparison of nullptr_t against a pointer type is
10600       // invalid per DR583, but we allow it within std::less<> and friends,
10601       // since otherwise common uses of it break.
10602       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10603       // friends to have std::nullptr_t overload candidates.
10604       DeclContext *DC = CurContext;
10605       if (isa<FunctionDecl>(DC))
10606         DC = DC->getParent();
10607       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10608         if (CTSD->isInStdNamespace() &&
10609             llvm::StringSwitch<bool>(CTSD->getName())
10610                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10611                 .Default(false)) {
10612           if (RHSType->isNullPtrType())
10613             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10614           else
10615             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10616           return computeResultTy();
10617         }
10618       }
10619     }
10620 
10621     // C++ [expr.eq]p2:
10622     //   If at least one operand is a pointer to member, [...] bring them to
10623     //   their composite pointer type.
10624     if (!IsRelational &&
10625         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10626       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10627         return QualType();
10628       else
10629         return computeResultTy();
10630     }
10631   }
10632 
10633   // Handle block pointer types.
10634   if (!IsRelational && LHSType->isBlockPointerType() &&
10635       RHSType->isBlockPointerType()) {
10636     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10637     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10638 
10639     if (!LHSIsNull && !RHSIsNull &&
10640         !Context.typesAreCompatible(lpointee, rpointee)) {
10641       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10642         << LHSType << RHSType << LHS.get()->getSourceRange()
10643         << RHS.get()->getSourceRange();
10644     }
10645     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10646     return computeResultTy();
10647   }
10648 
10649   // Allow block pointers to be compared with null pointer constants.
10650   if (!IsRelational
10651       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10652           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10653     if (!LHSIsNull && !RHSIsNull) {
10654       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10655              ->getPointeeType()->isVoidType())
10656             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10657                 ->getPointeeType()->isVoidType())))
10658         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10659           << LHSType << RHSType << LHS.get()->getSourceRange()
10660           << RHS.get()->getSourceRange();
10661     }
10662     if (LHSIsNull && !RHSIsNull)
10663       LHS = ImpCastExprToType(LHS.get(), RHSType,
10664                               RHSType->isPointerType() ? CK_BitCast
10665                                 : CK_AnyPointerToBlockPointerCast);
10666     else
10667       RHS = ImpCastExprToType(RHS.get(), LHSType,
10668                               LHSType->isPointerType() ? CK_BitCast
10669                                 : CK_AnyPointerToBlockPointerCast);
10670     return computeResultTy();
10671   }
10672 
10673   if (LHSType->isObjCObjectPointerType() ||
10674       RHSType->isObjCObjectPointerType()) {
10675     const PointerType *LPT = LHSType->getAs<PointerType>();
10676     const PointerType *RPT = RHSType->getAs<PointerType>();
10677     if (LPT || RPT) {
10678       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10679       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10680 
10681       if (!LPtrToVoid && !RPtrToVoid &&
10682           !Context.typesAreCompatible(LHSType, RHSType)) {
10683         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10684                                           /*isError*/false);
10685       }
10686       if (LHSIsNull && !RHSIsNull) {
10687         Expr *E = LHS.get();
10688         if (getLangOpts().ObjCAutoRefCount)
10689           CheckObjCConversion(SourceRange(), RHSType, E,
10690                               CCK_ImplicitConversion);
10691         LHS = ImpCastExprToType(E, RHSType,
10692                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10693       }
10694       else {
10695         Expr *E = RHS.get();
10696         if (getLangOpts().ObjCAutoRefCount)
10697           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10698                               /*Diagnose=*/true,
10699                               /*DiagnoseCFAudited=*/false, Opc);
10700         RHS = ImpCastExprToType(E, LHSType,
10701                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10702       }
10703       return computeResultTy();
10704     }
10705     if (LHSType->isObjCObjectPointerType() &&
10706         RHSType->isObjCObjectPointerType()) {
10707       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10708         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10709                                           /*isError*/false);
10710       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10711         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10712 
10713       if (LHSIsNull && !RHSIsNull)
10714         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10715       else
10716         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10717       return computeResultTy();
10718     }
10719 
10720     if (!IsRelational && LHSType->isBlockPointerType() &&
10721         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10722       LHS = ImpCastExprToType(LHS.get(), RHSType,
10723                               CK_BlockPointerToObjCPointerCast);
10724       return computeResultTy();
10725     } else if (!IsRelational &&
10726                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10727                RHSType->isBlockPointerType()) {
10728       RHS = ImpCastExprToType(RHS.get(), LHSType,
10729                               CK_BlockPointerToObjCPointerCast);
10730       return computeResultTy();
10731     }
10732   }
10733   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10734       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10735     unsigned DiagID = 0;
10736     bool isError = false;
10737     if (LangOpts.DebuggerSupport) {
10738       // Under a debugger, allow the comparison of pointers to integers,
10739       // since users tend to want to compare addresses.
10740     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10741                (RHSIsNull && RHSType->isIntegerType())) {
10742       if (IsRelational) {
10743         isError = getLangOpts().CPlusPlus;
10744         DiagID =
10745           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10746                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10747       }
10748     } else if (getLangOpts().CPlusPlus) {
10749       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10750       isError = true;
10751     } else if (IsRelational)
10752       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10753     else
10754       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10755 
10756     if (DiagID) {
10757       Diag(Loc, DiagID)
10758         << LHSType << RHSType << LHS.get()->getSourceRange()
10759         << RHS.get()->getSourceRange();
10760       if (isError)
10761         return QualType();
10762     }
10763 
10764     if (LHSType->isIntegerType())
10765       LHS = ImpCastExprToType(LHS.get(), RHSType,
10766                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10767     else
10768       RHS = ImpCastExprToType(RHS.get(), LHSType,
10769                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10770     return computeResultTy();
10771   }
10772 
10773   // Handle block pointers.
10774   if (!IsRelational && RHSIsNull
10775       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10776     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10777     return computeResultTy();
10778   }
10779   if (!IsRelational && LHSIsNull
10780       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10781     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10782     return computeResultTy();
10783   }
10784 
10785   if (getLangOpts().OpenCLVersion >= 200) {
10786     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10787       return computeResultTy();
10788     }
10789 
10790     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10791       return computeResultTy();
10792     }
10793 
10794     if (LHSIsNull && RHSType->isQueueT()) {
10795       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10796       return computeResultTy();
10797     }
10798 
10799     if (LHSType->isQueueT() && RHSIsNull) {
10800       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10801       return computeResultTy();
10802     }
10803   }
10804 
10805   return InvalidOperands(Loc, LHS, RHS);
10806 }
10807 
10808 // Return a signed ext_vector_type that is of identical size and number of
10809 // elements. For floating point vectors, return an integer type of identical
10810 // size and number of elements. In the non ext_vector_type case, search from
10811 // the largest type to the smallest type to avoid cases where long long == long,
10812 // where long gets picked over long long.
10813 QualType Sema::GetSignedVectorType(QualType V) {
10814   const VectorType *VTy = V->getAs<VectorType>();
10815   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10816 
10817   if (isa<ExtVectorType>(VTy)) {
10818     if (TypeSize == Context.getTypeSize(Context.CharTy))
10819       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10820     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10821       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10822     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10823       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10824     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10825       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10826     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10827            "Unhandled vector element size in vector compare");
10828     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10829   }
10830 
10831   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10832     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10833                                  VectorType::GenericVector);
10834   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10835     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10836                                  VectorType::GenericVector);
10837   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10838     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10839                                  VectorType::GenericVector);
10840   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10841     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10842                                  VectorType::GenericVector);
10843   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10844          "Unhandled vector element size in vector compare");
10845   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10846                                VectorType::GenericVector);
10847 }
10848 
10849 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10850 /// operates on extended vector types.  Instead of producing an IntTy result,
10851 /// like a scalar comparison, a vector comparison produces a vector of integer
10852 /// types.
10853 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10854                                           SourceLocation Loc,
10855                                           BinaryOperatorKind Opc) {
10856   // Check to make sure we're operating on vectors of the same type and width,
10857   // Allowing one side to be a scalar of element type.
10858   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10859                               /*AllowBothBool*/true,
10860                               /*AllowBoolConversions*/getLangOpts().ZVector);
10861   if (vType.isNull())
10862     return vType;
10863 
10864   QualType LHSType = LHS.get()->getType();
10865 
10866   // If AltiVec, the comparison results in a numeric type, i.e.
10867   // bool for C++, int for C
10868   if (getLangOpts().AltiVec &&
10869       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10870     return Context.getLogicalOperationType();
10871 
10872   // For non-floating point types, check for self-comparisons of the form
10873   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10874   // often indicate logic errors in the program.
10875   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10876 
10877   // Check for comparisons of floating point operands using != and ==.
10878   if (BinaryOperator::isEqualityOp(Opc) &&
10879       LHSType->hasFloatingRepresentation()) {
10880     assert(RHS.get()->getType()->hasFloatingRepresentation());
10881     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10882   }
10883 
10884   // Return a signed type for the vector.
10885   return GetSignedVectorType(vType);
10886 }
10887 
10888 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10889                                           SourceLocation Loc) {
10890   // Ensure that either both operands are of the same vector type, or
10891   // one operand is of a vector type and the other is of its element type.
10892   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10893                                        /*AllowBothBool*/true,
10894                                        /*AllowBoolConversions*/false);
10895   if (vType.isNull())
10896     return InvalidOperands(Loc, LHS, RHS);
10897   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10898       vType->hasFloatingRepresentation())
10899     return InvalidOperands(Loc, LHS, RHS);
10900   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10901   //        usage of the logical operators && and || with vectors in C. This
10902   //        check could be notionally dropped.
10903   if (!getLangOpts().CPlusPlus &&
10904       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10905     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10906 
10907   return GetSignedVectorType(LHS.get()->getType());
10908 }
10909 
10910 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10911                                            SourceLocation Loc,
10912                                            BinaryOperatorKind Opc) {
10913   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10914 
10915   bool IsCompAssign =
10916       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10917 
10918   if (LHS.get()->getType()->isVectorType() ||
10919       RHS.get()->getType()->isVectorType()) {
10920     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10921         RHS.get()->getType()->hasIntegerRepresentation())
10922       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10923                         /*AllowBothBool*/true,
10924                         /*AllowBoolConversions*/getLangOpts().ZVector);
10925     return InvalidOperands(Loc, LHS, RHS);
10926   }
10927 
10928   if (Opc == BO_And)
10929     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10930 
10931   ExprResult LHSResult = LHS, RHSResult = RHS;
10932   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10933                                                  IsCompAssign);
10934   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10935     return QualType();
10936   LHS = LHSResult.get();
10937   RHS = RHSResult.get();
10938 
10939   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10940     return compType;
10941   return InvalidOperands(Loc, LHS, RHS);
10942 }
10943 
10944 // C99 6.5.[13,14]
10945 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10946                                            SourceLocation Loc,
10947                                            BinaryOperatorKind Opc) {
10948   // Check vector operands differently.
10949   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10950     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10951 
10952   // Diagnose cases where the user write a logical and/or but probably meant a
10953   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10954   // is a constant.
10955   if (LHS.get()->getType()->isIntegerType() &&
10956       !LHS.get()->getType()->isBooleanType() &&
10957       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10958       // Don't warn in macros or template instantiations.
10959       !Loc.isMacroID() && !inTemplateInstantiation()) {
10960     // If the RHS can be constant folded, and if it constant folds to something
10961     // that isn't 0 or 1 (which indicate a potential logical operation that
10962     // happened to fold to true/false) then warn.
10963     // Parens on the RHS are ignored.
10964     Expr::EvalResult EVResult;
10965     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10966       llvm::APSInt Result = EVResult.Val.getInt();
10967       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10968            !RHS.get()->getExprLoc().isMacroID()) ||
10969           (Result != 0 && Result != 1)) {
10970         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10971           << RHS.get()->getSourceRange()
10972           << (Opc == BO_LAnd ? "&&" : "||");
10973         // Suggest replacing the logical operator with the bitwise version
10974         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10975             << (Opc == BO_LAnd ? "&" : "|")
10976             << FixItHint::CreateReplacement(SourceRange(
10977                                                  Loc, getLocForEndOfToken(Loc)),
10978                                             Opc == BO_LAnd ? "&" : "|");
10979         if (Opc == BO_LAnd)
10980           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10981           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10982               << FixItHint::CreateRemoval(
10983                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10984                                  RHS.get()->getEndLoc()));
10985       }
10986     }
10987   }
10988 
10989   if (!Context.getLangOpts().CPlusPlus) {
10990     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10991     // not operate on the built-in scalar and vector float types.
10992     if (Context.getLangOpts().OpenCL &&
10993         Context.getLangOpts().OpenCLVersion < 120) {
10994       if (LHS.get()->getType()->isFloatingType() ||
10995           RHS.get()->getType()->isFloatingType())
10996         return InvalidOperands(Loc, LHS, RHS);
10997     }
10998 
10999     LHS = UsualUnaryConversions(LHS.get());
11000     if (LHS.isInvalid())
11001       return QualType();
11002 
11003     RHS = UsualUnaryConversions(RHS.get());
11004     if (RHS.isInvalid())
11005       return QualType();
11006 
11007     if (!LHS.get()->getType()->isScalarType() ||
11008         !RHS.get()->getType()->isScalarType())
11009       return InvalidOperands(Loc, LHS, RHS);
11010 
11011     return Context.IntTy;
11012   }
11013 
11014   // The following is safe because we only use this method for
11015   // non-overloadable operands.
11016 
11017   // C++ [expr.log.and]p1
11018   // C++ [expr.log.or]p1
11019   // The operands are both contextually converted to type bool.
11020   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11021   if (LHSRes.isInvalid())
11022     return InvalidOperands(Loc, LHS, RHS);
11023   LHS = LHSRes;
11024 
11025   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11026   if (RHSRes.isInvalid())
11027     return InvalidOperands(Loc, LHS, RHS);
11028   RHS = RHSRes;
11029 
11030   // C++ [expr.log.and]p2
11031   // C++ [expr.log.or]p2
11032   // The result is a bool.
11033   return Context.BoolTy;
11034 }
11035 
11036 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11037   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11038   if (!ME) return false;
11039   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11040   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11041       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11042   if (!Base) return false;
11043   return Base->getMethodDecl() != nullptr;
11044 }
11045 
11046 /// Is the given expression (which must be 'const') a reference to a
11047 /// variable which was originally non-const, but which has become
11048 /// 'const' due to being captured within a block?
11049 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11050 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11051   assert(E->isLValue() && E->getType().isConstQualified());
11052   E = E->IgnoreParens();
11053 
11054   // Must be a reference to a declaration from an enclosing scope.
11055   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11056   if (!DRE) return NCCK_None;
11057   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11058 
11059   // The declaration must be a variable which is not declared 'const'.
11060   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11061   if (!var) return NCCK_None;
11062   if (var->getType().isConstQualified()) return NCCK_None;
11063   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11064 
11065   // Decide whether the first capture was for a block or a lambda.
11066   DeclContext *DC = S.CurContext, *Prev = nullptr;
11067   // Decide whether the first capture was for a block or a lambda.
11068   while (DC) {
11069     // For init-capture, it is possible that the variable belongs to the
11070     // template pattern of the current context.
11071     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11072       if (var->isInitCapture() &&
11073           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11074         break;
11075     if (DC == var->getDeclContext())
11076       break;
11077     Prev = DC;
11078     DC = DC->getParent();
11079   }
11080   // Unless we have an init-capture, we've gone one step too far.
11081   if (!var->isInitCapture())
11082     DC = Prev;
11083   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11084 }
11085 
11086 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11087   Ty = Ty.getNonReferenceType();
11088   if (IsDereference && Ty->isPointerType())
11089     Ty = Ty->getPointeeType();
11090   return !Ty.isConstQualified();
11091 }
11092 
11093 // Update err_typecheck_assign_const and note_typecheck_assign_const
11094 // when this enum is changed.
11095 enum {
11096   ConstFunction,
11097   ConstVariable,
11098   ConstMember,
11099   ConstMethod,
11100   NestedConstMember,
11101   ConstUnknown,  // Keep as last element
11102 };
11103 
11104 /// Emit the "read-only variable not assignable" error and print notes to give
11105 /// more information about why the variable is not assignable, such as pointing
11106 /// to the declaration of a const variable, showing that a method is const, or
11107 /// that the function is returning a const reference.
11108 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11109                                     SourceLocation Loc) {
11110   SourceRange ExprRange = E->getSourceRange();
11111 
11112   // Only emit one error on the first const found.  All other consts will emit
11113   // a note to the error.
11114   bool DiagnosticEmitted = false;
11115 
11116   // Track if the current expression is the result of a dereference, and if the
11117   // next checked expression is the result of a dereference.
11118   bool IsDereference = false;
11119   bool NextIsDereference = false;
11120 
11121   // Loop to process MemberExpr chains.
11122   while (true) {
11123     IsDereference = NextIsDereference;
11124 
11125     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11126     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11127       NextIsDereference = ME->isArrow();
11128       const ValueDecl *VD = ME->getMemberDecl();
11129       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11130         // Mutable fields can be modified even if the class is const.
11131         if (Field->isMutable()) {
11132           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11133           break;
11134         }
11135 
11136         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11137           if (!DiagnosticEmitted) {
11138             S.Diag(Loc, diag::err_typecheck_assign_const)
11139                 << ExprRange << ConstMember << false /*static*/ << Field
11140                 << Field->getType();
11141             DiagnosticEmitted = true;
11142           }
11143           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11144               << ConstMember << false /*static*/ << Field << Field->getType()
11145               << Field->getSourceRange();
11146         }
11147         E = ME->getBase();
11148         continue;
11149       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11150         if (VDecl->getType().isConstQualified()) {
11151           if (!DiagnosticEmitted) {
11152             S.Diag(Loc, diag::err_typecheck_assign_const)
11153                 << ExprRange << ConstMember << true /*static*/ << VDecl
11154                 << VDecl->getType();
11155             DiagnosticEmitted = true;
11156           }
11157           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11158               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11159               << VDecl->getSourceRange();
11160         }
11161         // Static fields do not inherit constness from parents.
11162         break;
11163       }
11164       break; // End MemberExpr
11165     } else if (const ArraySubscriptExpr *ASE =
11166                    dyn_cast<ArraySubscriptExpr>(E)) {
11167       E = ASE->getBase()->IgnoreParenImpCasts();
11168       continue;
11169     } else if (const ExtVectorElementExpr *EVE =
11170                    dyn_cast<ExtVectorElementExpr>(E)) {
11171       E = EVE->getBase()->IgnoreParenImpCasts();
11172       continue;
11173     }
11174     break;
11175   }
11176 
11177   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11178     // Function calls
11179     const FunctionDecl *FD = CE->getDirectCallee();
11180     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11181       if (!DiagnosticEmitted) {
11182         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11183                                                       << ConstFunction << FD;
11184         DiagnosticEmitted = true;
11185       }
11186       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11187              diag::note_typecheck_assign_const)
11188           << ConstFunction << FD << FD->getReturnType()
11189           << FD->getReturnTypeSourceRange();
11190     }
11191   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11192     // Point to variable declaration.
11193     if (const ValueDecl *VD = DRE->getDecl()) {
11194       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11195         if (!DiagnosticEmitted) {
11196           S.Diag(Loc, diag::err_typecheck_assign_const)
11197               << ExprRange << ConstVariable << VD << VD->getType();
11198           DiagnosticEmitted = true;
11199         }
11200         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11201             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11202       }
11203     }
11204   } else if (isa<CXXThisExpr>(E)) {
11205     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11206       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11207         if (MD->isConst()) {
11208           if (!DiagnosticEmitted) {
11209             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11210                                                           << ConstMethod << MD;
11211             DiagnosticEmitted = true;
11212           }
11213           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11214               << ConstMethod << MD << MD->getSourceRange();
11215         }
11216       }
11217     }
11218   }
11219 
11220   if (DiagnosticEmitted)
11221     return;
11222 
11223   // Can't determine a more specific message, so display the generic error.
11224   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11225 }
11226 
11227 enum OriginalExprKind {
11228   OEK_Variable,
11229   OEK_Member,
11230   OEK_LValue
11231 };
11232 
11233 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11234                                          const RecordType *Ty,
11235                                          SourceLocation Loc, SourceRange Range,
11236                                          OriginalExprKind OEK,
11237                                          bool &DiagnosticEmitted) {
11238   std::vector<const RecordType *> RecordTypeList;
11239   RecordTypeList.push_back(Ty);
11240   unsigned NextToCheckIndex = 0;
11241   // We walk the record hierarchy breadth-first to ensure that we print
11242   // diagnostics in field nesting order.
11243   while (RecordTypeList.size() > NextToCheckIndex) {
11244     bool IsNested = NextToCheckIndex > 0;
11245     for (const FieldDecl *Field :
11246          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11247       // First, check every field for constness.
11248       QualType FieldTy = Field->getType();
11249       if (FieldTy.isConstQualified()) {
11250         if (!DiagnosticEmitted) {
11251           S.Diag(Loc, diag::err_typecheck_assign_const)
11252               << Range << NestedConstMember << OEK << VD
11253               << IsNested << Field;
11254           DiagnosticEmitted = true;
11255         }
11256         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11257             << NestedConstMember << IsNested << Field
11258             << FieldTy << Field->getSourceRange();
11259       }
11260 
11261       // Then we append it to the list to check next in order.
11262       FieldTy = FieldTy.getCanonicalType();
11263       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11264         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11265           RecordTypeList.push_back(FieldRecTy);
11266       }
11267     }
11268     ++NextToCheckIndex;
11269   }
11270 }
11271 
11272 /// Emit an error for the case where a record we are trying to assign to has a
11273 /// const-qualified field somewhere in its hierarchy.
11274 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11275                                          SourceLocation Loc) {
11276   QualType Ty = E->getType();
11277   assert(Ty->isRecordType() && "lvalue was not record?");
11278   SourceRange Range = E->getSourceRange();
11279   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11280   bool DiagEmitted = false;
11281 
11282   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11283     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11284             Range, OEK_Member, DiagEmitted);
11285   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11286     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11287             Range, OEK_Variable, DiagEmitted);
11288   else
11289     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11290             Range, OEK_LValue, DiagEmitted);
11291   if (!DiagEmitted)
11292     DiagnoseConstAssignment(S, E, Loc);
11293 }
11294 
11295 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11296 /// emit an error and return true.  If so, return false.
11297 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11298   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11299 
11300   S.CheckShadowingDeclModification(E, Loc);
11301 
11302   SourceLocation OrigLoc = Loc;
11303   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11304                                                               &Loc);
11305   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11306     IsLV = Expr::MLV_InvalidMessageExpression;
11307   if (IsLV == Expr::MLV_Valid)
11308     return false;
11309 
11310   unsigned DiagID = 0;
11311   bool NeedType = false;
11312   switch (IsLV) { // C99 6.5.16p2
11313   case Expr::MLV_ConstQualified:
11314     // Use a specialized diagnostic when we're assigning to an object
11315     // from an enclosing function or block.
11316     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11317       if (NCCK == NCCK_Block)
11318         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11319       else
11320         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11321       break;
11322     }
11323 
11324     // In ARC, use some specialized diagnostics for occasions where we
11325     // infer 'const'.  These are always pseudo-strong variables.
11326     if (S.getLangOpts().ObjCAutoRefCount) {
11327       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11328       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11329         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11330 
11331         // Use the normal diagnostic if it's pseudo-__strong but the
11332         // user actually wrote 'const'.
11333         if (var->isARCPseudoStrong() &&
11334             (!var->getTypeSourceInfo() ||
11335              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11336           // There are three pseudo-strong cases:
11337           //  - self
11338           ObjCMethodDecl *method = S.getCurMethodDecl();
11339           if (method && var == method->getSelfDecl()) {
11340             DiagID = method->isClassMethod()
11341               ? diag::err_typecheck_arc_assign_self_class_method
11342               : diag::err_typecheck_arc_assign_self;
11343 
11344           //  - Objective-C externally_retained attribute.
11345           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11346                      isa<ParmVarDecl>(var)) {
11347             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11348 
11349           //  - fast enumeration variables
11350           } else {
11351             DiagID = diag::err_typecheck_arr_assign_enumeration;
11352           }
11353 
11354           SourceRange Assign;
11355           if (Loc != OrigLoc)
11356             Assign = SourceRange(OrigLoc, OrigLoc);
11357           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11358           // We need to preserve the AST regardless, so migration tool
11359           // can do its job.
11360           return false;
11361         }
11362       }
11363     }
11364 
11365     // If none of the special cases above are triggered, then this is a
11366     // simple const assignment.
11367     if (DiagID == 0) {
11368       DiagnoseConstAssignment(S, E, Loc);
11369       return true;
11370     }
11371 
11372     break;
11373   case Expr::MLV_ConstAddrSpace:
11374     DiagnoseConstAssignment(S, E, Loc);
11375     return true;
11376   case Expr::MLV_ConstQualifiedField:
11377     DiagnoseRecursiveConstFields(S, E, Loc);
11378     return true;
11379   case Expr::MLV_ArrayType:
11380   case Expr::MLV_ArrayTemporary:
11381     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11382     NeedType = true;
11383     break;
11384   case Expr::MLV_NotObjectType:
11385     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11386     NeedType = true;
11387     break;
11388   case Expr::MLV_LValueCast:
11389     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11390     break;
11391   case Expr::MLV_Valid:
11392     llvm_unreachable("did not take early return for MLV_Valid");
11393   case Expr::MLV_InvalidExpression:
11394   case Expr::MLV_MemberFunction:
11395   case Expr::MLV_ClassTemporary:
11396     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11397     break;
11398   case Expr::MLV_IncompleteType:
11399   case Expr::MLV_IncompleteVoidType:
11400     return S.RequireCompleteType(Loc, E->getType(),
11401              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11402   case Expr::MLV_DuplicateVectorComponents:
11403     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11404     break;
11405   case Expr::MLV_NoSetterProperty:
11406     llvm_unreachable("readonly properties should be processed differently");
11407   case Expr::MLV_InvalidMessageExpression:
11408     DiagID = diag::err_readonly_message_assignment;
11409     break;
11410   case Expr::MLV_SubObjCPropertySetting:
11411     DiagID = diag::err_no_subobject_property_setting;
11412     break;
11413   }
11414 
11415   SourceRange Assign;
11416   if (Loc != OrigLoc)
11417     Assign = SourceRange(OrigLoc, OrigLoc);
11418   if (NeedType)
11419     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11420   else
11421     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11422   return true;
11423 }
11424 
11425 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11426                                          SourceLocation Loc,
11427                                          Sema &Sema) {
11428   if (Sema.inTemplateInstantiation())
11429     return;
11430   if (Sema.isUnevaluatedContext())
11431     return;
11432   if (Loc.isInvalid() || Loc.isMacroID())
11433     return;
11434   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11435     return;
11436 
11437   // C / C++ fields
11438   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11439   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11440   if (ML && MR) {
11441     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11442       return;
11443     const ValueDecl *LHSDecl =
11444         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11445     const ValueDecl *RHSDecl =
11446         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11447     if (LHSDecl != RHSDecl)
11448       return;
11449     if (LHSDecl->getType().isVolatileQualified())
11450       return;
11451     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11452       if (RefTy->getPointeeType().isVolatileQualified())
11453         return;
11454 
11455     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11456   }
11457 
11458   // Objective-C instance variables
11459   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11460   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11461   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11462     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11463     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11464     if (RL && RR && RL->getDecl() == RR->getDecl())
11465       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11466   }
11467 }
11468 
11469 // C99 6.5.16.1
11470 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11471                                        SourceLocation Loc,
11472                                        QualType CompoundType) {
11473   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11474 
11475   // Verify that LHS is a modifiable lvalue, and emit error if not.
11476   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11477     return QualType();
11478 
11479   QualType LHSType = LHSExpr->getType();
11480   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11481                                              CompoundType;
11482   // OpenCL v1.2 s6.1.1.1 p2:
11483   // The half data type can only be used to declare a pointer to a buffer that
11484   // contains half values
11485   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11486     LHSType->isHalfType()) {
11487     Diag(Loc, diag::err_opencl_half_load_store) << 1
11488         << LHSType.getUnqualifiedType();
11489     return QualType();
11490   }
11491 
11492   AssignConvertType ConvTy;
11493   if (CompoundType.isNull()) {
11494     Expr *RHSCheck = RHS.get();
11495 
11496     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11497 
11498     QualType LHSTy(LHSType);
11499     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11500     if (RHS.isInvalid())
11501       return QualType();
11502     // Special case of NSObject attributes on c-style pointer types.
11503     if (ConvTy == IncompatiblePointer &&
11504         ((Context.isObjCNSObjectType(LHSType) &&
11505           RHSType->isObjCObjectPointerType()) ||
11506          (Context.isObjCNSObjectType(RHSType) &&
11507           LHSType->isObjCObjectPointerType())))
11508       ConvTy = Compatible;
11509 
11510     if (ConvTy == Compatible &&
11511         LHSType->isObjCObjectType())
11512         Diag(Loc, diag::err_objc_object_assignment)
11513           << LHSType;
11514 
11515     // If the RHS is a unary plus or minus, check to see if they = and + are
11516     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11517     // instead of "x += 4".
11518     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11519       RHSCheck = ICE->getSubExpr();
11520     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11521       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11522           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11523           // Only if the two operators are exactly adjacent.
11524           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11525           // And there is a space or other character before the subexpr of the
11526           // unary +/-.  We don't want to warn on "x=-1".
11527           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11528           UO->getSubExpr()->getBeginLoc().isFileID()) {
11529         Diag(Loc, diag::warn_not_compound_assign)
11530           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11531           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11532       }
11533     }
11534 
11535     if (ConvTy == Compatible) {
11536       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11537         // Warn about retain cycles where a block captures the LHS, but
11538         // not if the LHS is a simple variable into which the block is
11539         // being stored...unless that variable can be captured by reference!
11540         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11541         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11542         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11543           checkRetainCycles(LHSExpr, RHS.get());
11544       }
11545 
11546       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11547           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11548         // It is safe to assign a weak reference into a strong variable.
11549         // Although this code can still have problems:
11550         //   id x = self.weakProp;
11551         //   id y = self.weakProp;
11552         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11553         // paths through the function. This should be revisited if
11554         // -Wrepeated-use-of-weak is made flow-sensitive.
11555         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11556         // variable, which will be valid for the current autorelease scope.
11557         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11558                              RHS.get()->getBeginLoc()))
11559           getCurFunction()->markSafeWeakUse(RHS.get());
11560 
11561       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11562         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11563       }
11564     }
11565   } else {
11566     // Compound assignment "x += y"
11567     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11568   }
11569 
11570   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11571                                RHS.get(), AA_Assigning))
11572     return QualType();
11573 
11574   CheckForNullPointerDereference(*this, LHSExpr);
11575 
11576   // C99 6.5.16p3: The type of an assignment expression is the type of the
11577   // left operand unless the left operand has qualified type, in which case
11578   // it is the unqualified version of the type of the left operand.
11579   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11580   // is converted to the type of the assignment expression (above).
11581   // C++ 5.17p1: the type of the assignment expression is that of its left
11582   // operand.
11583   return (getLangOpts().CPlusPlus
11584           ? LHSType : LHSType.getUnqualifiedType());
11585 }
11586 
11587 // Only ignore explicit casts to void.
11588 static bool IgnoreCommaOperand(const Expr *E) {
11589   E = E->IgnoreParens();
11590 
11591   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11592     if (CE->getCastKind() == CK_ToVoid) {
11593       return true;
11594     }
11595 
11596     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11597     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11598         CE->getSubExpr()->getType()->isDependentType()) {
11599       return true;
11600     }
11601   }
11602 
11603   return false;
11604 }
11605 
11606 // Look for instances where it is likely the comma operator is confused with
11607 // another operator.  There is a whitelist of acceptable expressions for the
11608 // left hand side of the comma operator, otherwise emit a warning.
11609 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11610   // No warnings in macros
11611   if (Loc.isMacroID())
11612     return;
11613 
11614   // Don't warn in template instantiations.
11615   if (inTemplateInstantiation())
11616     return;
11617 
11618   // Scope isn't fine-grained enough to whitelist the specific cases, so
11619   // instead, skip more than needed, then call back into here with the
11620   // CommaVisitor in SemaStmt.cpp.
11621   // The whitelisted locations are the initialization and increment portions
11622   // of a for loop.  The additional checks are on the condition of
11623   // if statements, do/while loops, and for loops.
11624   // Differences in scope flags for C89 mode requires the extra logic.
11625   const unsigned ForIncrementFlags =
11626       getLangOpts().C99 || getLangOpts().CPlusPlus
11627           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11628           : Scope::ContinueScope | Scope::BreakScope;
11629   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11630   const unsigned ScopeFlags = getCurScope()->getFlags();
11631   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11632       (ScopeFlags & ForInitFlags) == ForInitFlags)
11633     return;
11634 
11635   // If there are multiple comma operators used together, get the RHS of the
11636   // of the comma operator as the LHS.
11637   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11638     if (BO->getOpcode() != BO_Comma)
11639       break;
11640     LHS = BO->getRHS();
11641   }
11642 
11643   // Only allow some expressions on LHS to not warn.
11644   if (IgnoreCommaOperand(LHS))
11645     return;
11646 
11647   Diag(Loc, diag::warn_comma_operator);
11648   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11649       << LHS->getSourceRange()
11650       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11651                                     LangOpts.CPlusPlus ? "static_cast<void>("
11652                                                        : "(void)(")
11653       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11654                                     ")");
11655 }
11656 
11657 // C99 6.5.17
11658 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11659                                    SourceLocation Loc) {
11660   LHS = S.CheckPlaceholderExpr(LHS.get());
11661   RHS = S.CheckPlaceholderExpr(RHS.get());
11662   if (LHS.isInvalid() || RHS.isInvalid())
11663     return QualType();
11664 
11665   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11666   // operands, but not unary promotions.
11667   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11668 
11669   // So we treat the LHS as a ignored value, and in C++ we allow the
11670   // containing site to determine what should be done with the RHS.
11671   LHS = S.IgnoredValueConversions(LHS.get());
11672   if (LHS.isInvalid())
11673     return QualType();
11674 
11675   S.DiagnoseUnusedExprResult(LHS.get());
11676 
11677   if (!S.getLangOpts().CPlusPlus) {
11678     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11679     if (RHS.isInvalid())
11680       return QualType();
11681     if (!RHS.get()->getType()->isVoidType())
11682       S.RequireCompleteType(Loc, RHS.get()->getType(),
11683                             diag::err_incomplete_type);
11684   }
11685 
11686   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11687     S.DiagnoseCommaOperator(LHS.get(), Loc);
11688 
11689   return RHS.get()->getType();
11690 }
11691 
11692 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11693 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11694 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11695                                                ExprValueKind &VK,
11696                                                ExprObjectKind &OK,
11697                                                SourceLocation OpLoc,
11698                                                bool IsInc, bool IsPrefix) {
11699   if (Op->isTypeDependent())
11700     return S.Context.DependentTy;
11701 
11702   QualType ResType = Op->getType();
11703   // Atomic types can be used for increment / decrement where the non-atomic
11704   // versions can, so ignore the _Atomic() specifier for the purpose of
11705   // checking.
11706   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11707     ResType = ResAtomicType->getValueType();
11708 
11709   assert(!ResType.isNull() && "no type for increment/decrement expression");
11710 
11711   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11712     // Decrement of bool is not allowed.
11713     if (!IsInc) {
11714       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11715       return QualType();
11716     }
11717     // Increment of bool sets it to true, but is deprecated.
11718     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11719                                               : diag::warn_increment_bool)
11720       << Op->getSourceRange();
11721   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11722     // Error on enum increments and decrements in C++ mode
11723     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11724     return QualType();
11725   } else if (ResType->isRealType()) {
11726     // OK!
11727   } else if (ResType->isPointerType()) {
11728     // C99 6.5.2.4p2, 6.5.6p2
11729     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11730       return QualType();
11731   } else if (ResType->isObjCObjectPointerType()) {
11732     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11733     // Otherwise, we just need a complete type.
11734     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11735         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11736       return QualType();
11737   } else if (ResType->isAnyComplexType()) {
11738     // C99 does not support ++/-- on complex types, we allow as an extension.
11739     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11740       << ResType << Op->getSourceRange();
11741   } else if (ResType->isPlaceholderType()) {
11742     ExprResult PR = S.CheckPlaceholderExpr(Op);
11743     if (PR.isInvalid()) return QualType();
11744     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11745                                           IsInc, IsPrefix);
11746   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11747     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11748   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11749              (ResType->getAs<VectorType>()->getVectorKind() !=
11750               VectorType::AltiVecBool)) {
11751     // The z vector extensions allow ++ and -- for non-bool vectors.
11752   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11753             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11754     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11755   } else {
11756     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11757       << ResType << int(IsInc) << Op->getSourceRange();
11758     return QualType();
11759   }
11760   // At this point, we know we have a real, complex or pointer type.
11761   // Now make sure the operand is a modifiable lvalue.
11762   if (CheckForModifiableLvalue(Op, OpLoc, S))
11763     return QualType();
11764   // In C++, a prefix increment is the same type as the operand. Otherwise
11765   // (in C or with postfix), the increment is the unqualified type of the
11766   // operand.
11767   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11768     VK = VK_LValue;
11769     OK = Op->getObjectKind();
11770     return ResType;
11771   } else {
11772     VK = VK_RValue;
11773     return ResType.getUnqualifiedType();
11774   }
11775 }
11776 
11777 
11778 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11779 /// This routine allows us to typecheck complex/recursive expressions
11780 /// where the declaration is needed for type checking. We only need to
11781 /// handle cases when the expression references a function designator
11782 /// or is an lvalue. Here are some examples:
11783 ///  - &(x) => x
11784 ///  - &*****f => f for f a function designator.
11785 ///  - &s.xx => s
11786 ///  - &s.zz[1].yy -> s, if zz is an array
11787 ///  - *(x + 1) -> x, if x is an array
11788 ///  - &"123"[2] -> 0
11789 ///  - & __real__ x -> x
11790 static ValueDecl *getPrimaryDecl(Expr *E) {
11791   switch (E->getStmtClass()) {
11792   case Stmt::DeclRefExprClass:
11793     return cast<DeclRefExpr>(E)->getDecl();
11794   case Stmt::MemberExprClass:
11795     // If this is an arrow operator, the address is an offset from
11796     // the base's value, so the object the base refers to is
11797     // irrelevant.
11798     if (cast<MemberExpr>(E)->isArrow())
11799       return nullptr;
11800     // Otherwise, the expression refers to a part of the base
11801     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11802   case Stmt::ArraySubscriptExprClass: {
11803     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11804     // promotion of register arrays earlier.
11805     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11806     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11807       if (ICE->getSubExpr()->getType()->isArrayType())
11808         return getPrimaryDecl(ICE->getSubExpr());
11809     }
11810     return nullptr;
11811   }
11812   case Stmt::UnaryOperatorClass: {
11813     UnaryOperator *UO = cast<UnaryOperator>(E);
11814 
11815     switch(UO->getOpcode()) {
11816     case UO_Real:
11817     case UO_Imag:
11818     case UO_Extension:
11819       return getPrimaryDecl(UO->getSubExpr());
11820     default:
11821       return nullptr;
11822     }
11823   }
11824   case Stmt::ParenExprClass:
11825     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11826   case Stmt::ImplicitCastExprClass:
11827     // If the result of an implicit cast is an l-value, we care about
11828     // the sub-expression; otherwise, the result here doesn't matter.
11829     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11830   default:
11831     return nullptr;
11832   }
11833 }
11834 
11835 namespace {
11836   enum {
11837     AO_Bit_Field = 0,
11838     AO_Vector_Element = 1,
11839     AO_Property_Expansion = 2,
11840     AO_Register_Variable = 3,
11841     AO_No_Error = 4
11842   };
11843 }
11844 /// Diagnose invalid operand for address of operations.
11845 ///
11846 /// \param Type The type of operand which cannot have its address taken.
11847 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11848                                          Expr *E, unsigned Type) {
11849   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11850 }
11851 
11852 /// CheckAddressOfOperand - The operand of & must be either a function
11853 /// designator or an lvalue designating an object. If it is an lvalue, the
11854 /// object cannot be declared with storage class register or be a bit field.
11855 /// Note: The usual conversions are *not* applied to the operand of the &
11856 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11857 /// In C++, the operand might be an overloaded function name, in which case
11858 /// we allow the '&' but retain the overloaded-function type.
11859 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11860   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11861     if (PTy->getKind() == BuiltinType::Overload) {
11862       Expr *E = OrigOp.get()->IgnoreParens();
11863       if (!isa<OverloadExpr>(E)) {
11864         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11865         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11866           << OrigOp.get()->getSourceRange();
11867         return QualType();
11868       }
11869 
11870       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11871       if (isa<UnresolvedMemberExpr>(Ovl))
11872         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11873           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11874             << OrigOp.get()->getSourceRange();
11875           return QualType();
11876         }
11877 
11878       return Context.OverloadTy;
11879     }
11880 
11881     if (PTy->getKind() == BuiltinType::UnknownAny)
11882       return Context.UnknownAnyTy;
11883 
11884     if (PTy->getKind() == BuiltinType::BoundMember) {
11885       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11886         << OrigOp.get()->getSourceRange();
11887       return QualType();
11888     }
11889 
11890     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11891     if (OrigOp.isInvalid()) return QualType();
11892   }
11893 
11894   if (OrigOp.get()->isTypeDependent())
11895     return Context.DependentTy;
11896 
11897   assert(!OrigOp.get()->getType()->isPlaceholderType());
11898 
11899   // Make sure to ignore parentheses in subsequent checks
11900   Expr *op = OrigOp.get()->IgnoreParens();
11901 
11902   // In OpenCL captures for blocks called as lambda functions
11903   // are located in the private address space. Blocks used in
11904   // enqueue_kernel can be located in a different address space
11905   // depending on a vendor implementation. Thus preventing
11906   // taking an address of the capture to avoid invalid AS casts.
11907   if (LangOpts.OpenCL) {
11908     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11909     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11910       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11911       return QualType();
11912     }
11913   }
11914 
11915   if (getLangOpts().C99) {
11916     // Implement C99-only parts of addressof rules.
11917     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11918       if (uOp->getOpcode() == UO_Deref)
11919         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11920         // (assuming the deref expression is valid).
11921         return uOp->getSubExpr()->getType();
11922     }
11923     // Technically, there should be a check for array subscript
11924     // expressions here, but the result of one is always an lvalue anyway.
11925   }
11926   ValueDecl *dcl = getPrimaryDecl(op);
11927 
11928   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11929     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11930                                            op->getBeginLoc()))
11931       return QualType();
11932 
11933   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11934   unsigned AddressOfError = AO_No_Error;
11935 
11936   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11937     bool sfinae = (bool)isSFINAEContext();
11938     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11939                                   : diag::ext_typecheck_addrof_temporary)
11940       << op->getType() << op->getSourceRange();
11941     if (sfinae)
11942       return QualType();
11943     // Materialize the temporary as an lvalue so that we can take its address.
11944     OrigOp = op =
11945         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11946   } else if (isa<ObjCSelectorExpr>(op)) {
11947     return Context.getPointerType(op->getType());
11948   } else if (lval == Expr::LV_MemberFunction) {
11949     // If it's an instance method, make a member pointer.
11950     // The expression must have exactly the form &A::foo.
11951 
11952     // If the underlying expression isn't a decl ref, give up.
11953     if (!isa<DeclRefExpr>(op)) {
11954       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11955         << OrigOp.get()->getSourceRange();
11956       return QualType();
11957     }
11958     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11959     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11960 
11961     // The id-expression was parenthesized.
11962     if (OrigOp.get() != DRE) {
11963       Diag(OpLoc, diag::err_parens_pointer_member_function)
11964         << OrigOp.get()->getSourceRange();
11965 
11966     // The method was named without a qualifier.
11967     } else if (!DRE->getQualifier()) {
11968       if (MD->getParent()->getName().empty())
11969         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11970           << op->getSourceRange();
11971       else {
11972         SmallString<32> Str;
11973         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11974         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11975           << op->getSourceRange()
11976           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11977       }
11978     }
11979 
11980     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11981     if (isa<CXXDestructorDecl>(MD))
11982       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11983 
11984     QualType MPTy = Context.getMemberPointerType(
11985         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11986     // Under the MS ABI, lock down the inheritance model now.
11987     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11988       (void)isCompleteType(OpLoc, MPTy);
11989     return MPTy;
11990   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11991     // C99 6.5.3.2p1
11992     // The operand must be either an l-value or a function designator
11993     if (!op->getType()->isFunctionType()) {
11994       // Use a special diagnostic for loads from property references.
11995       if (isa<PseudoObjectExpr>(op)) {
11996         AddressOfError = AO_Property_Expansion;
11997       } else {
11998         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11999           << op->getType() << op->getSourceRange();
12000         return QualType();
12001       }
12002     }
12003   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12004     // The operand cannot be a bit-field
12005     AddressOfError = AO_Bit_Field;
12006   } else if (op->getObjectKind() == OK_VectorComponent) {
12007     // The operand cannot be an element of a vector
12008     AddressOfError = AO_Vector_Element;
12009   } else if (dcl) { // C99 6.5.3.2p1
12010     // We have an lvalue with a decl. Make sure the decl is not declared
12011     // with the register storage-class specifier.
12012     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12013       // in C++ it is not error to take address of a register
12014       // variable (c++03 7.1.1P3)
12015       if (vd->getStorageClass() == SC_Register &&
12016           !getLangOpts().CPlusPlus) {
12017         AddressOfError = AO_Register_Variable;
12018       }
12019     } else if (isa<MSPropertyDecl>(dcl)) {
12020       AddressOfError = AO_Property_Expansion;
12021     } else if (isa<FunctionTemplateDecl>(dcl)) {
12022       return Context.OverloadTy;
12023     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12024       // Okay: we can take the address of a field.
12025       // Could be a pointer to member, though, if there is an explicit
12026       // scope qualifier for the class.
12027       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12028         DeclContext *Ctx = dcl->getDeclContext();
12029         if (Ctx && Ctx->isRecord()) {
12030           if (dcl->getType()->isReferenceType()) {
12031             Diag(OpLoc,
12032                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12033               << dcl->getDeclName() << dcl->getType();
12034             return QualType();
12035           }
12036 
12037           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12038             Ctx = Ctx->getParent();
12039 
12040           QualType MPTy = Context.getMemberPointerType(
12041               op->getType(),
12042               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12043           // Under the MS ABI, lock down the inheritance model now.
12044           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12045             (void)isCompleteType(OpLoc, MPTy);
12046           return MPTy;
12047         }
12048       }
12049     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12050                !isa<BindingDecl>(dcl))
12051       llvm_unreachable("Unknown/unexpected decl type");
12052   }
12053 
12054   if (AddressOfError != AO_No_Error) {
12055     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12056     return QualType();
12057   }
12058 
12059   if (lval == Expr::LV_IncompleteVoidType) {
12060     // Taking the address of a void variable is technically illegal, but we
12061     // allow it in cases which are otherwise valid.
12062     // Example: "extern void x; void* y = &x;".
12063     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12064   }
12065 
12066   // If the operand has type "type", the result has type "pointer to type".
12067   if (op->getType()->isObjCObjectType())
12068     return Context.getObjCObjectPointerType(op->getType());
12069 
12070   CheckAddressOfPackedMember(op);
12071 
12072   return Context.getPointerType(op->getType());
12073 }
12074 
12075 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12076   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12077   if (!DRE)
12078     return;
12079   const Decl *D = DRE->getDecl();
12080   if (!D)
12081     return;
12082   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12083   if (!Param)
12084     return;
12085   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12086     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12087       return;
12088   if (FunctionScopeInfo *FD = S.getCurFunction())
12089     if (!FD->ModifiedNonNullParams.count(Param))
12090       FD->ModifiedNonNullParams.insert(Param);
12091 }
12092 
12093 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12094 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12095                                         SourceLocation OpLoc) {
12096   if (Op->isTypeDependent())
12097     return S.Context.DependentTy;
12098 
12099   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12100   if (ConvResult.isInvalid())
12101     return QualType();
12102   Op = ConvResult.get();
12103   QualType OpTy = Op->getType();
12104   QualType Result;
12105 
12106   if (isa<CXXReinterpretCastExpr>(Op)) {
12107     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12108     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12109                                      Op->getSourceRange());
12110   }
12111 
12112   if (const PointerType *PT = OpTy->getAs<PointerType>())
12113   {
12114     Result = PT->getPointeeType();
12115   }
12116   else if (const ObjCObjectPointerType *OPT =
12117              OpTy->getAs<ObjCObjectPointerType>())
12118     Result = OPT->getPointeeType();
12119   else {
12120     ExprResult PR = S.CheckPlaceholderExpr(Op);
12121     if (PR.isInvalid()) return QualType();
12122     if (PR.get() != Op)
12123       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12124   }
12125 
12126   if (Result.isNull()) {
12127     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12128       << OpTy << Op->getSourceRange();
12129     return QualType();
12130   }
12131 
12132   // Note that per both C89 and C99, indirection is always legal, even if Result
12133   // is an incomplete type or void.  It would be possible to warn about
12134   // dereferencing a void pointer, but it's completely well-defined, and such a
12135   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12136   // for pointers to 'void' but is fine for any other pointer type:
12137   //
12138   // C++ [expr.unary.op]p1:
12139   //   [...] the expression to which [the unary * operator] is applied shall
12140   //   be a pointer to an object type, or a pointer to a function type
12141   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12142     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12143       << OpTy << Op->getSourceRange();
12144 
12145   // Dereferences are usually l-values...
12146   VK = VK_LValue;
12147 
12148   // ...except that certain expressions are never l-values in C.
12149   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12150     VK = VK_RValue;
12151 
12152   return Result;
12153 }
12154 
12155 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12156   BinaryOperatorKind Opc;
12157   switch (Kind) {
12158   default: llvm_unreachable("Unknown binop!");
12159   case tok::periodstar:           Opc = BO_PtrMemD; break;
12160   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12161   case tok::star:                 Opc = BO_Mul; break;
12162   case tok::slash:                Opc = BO_Div; break;
12163   case tok::percent:              Opc = BO_Rem; break;
12164   case tok::plus:                 Opc = BO_Add; break;
12165   case tok::minus:                Opc = BO_Sub; break;
12166   case tok::lessless:             Opc = BO_Shl; break;
12167   case tok::greatergreater:       Opc = BO_Shr; break;
12168   case tok::lessequal:            Opc = BO_LE; break;
12169   case tok::less:                 Opc = BO_LT; break;
12170   case tok::greaterequal:         Opc = BO_GE; break;
12171   case tok::greater:              Opc = BO_GT; break;
12172   case tok::exclaimequal:         Opc = BO_NE; break;
12173   case tok::equalequal:           Opc = BO_EQ; break;
12174   case tok::spaceship:            Opc = BO_Cmp; break;
12175   case tok::amp:                  Opc = BO_And; break;
12176   case tok::caret:                Opc = BO_Xor; break;
12177   case tok::pipe:                 Opc = BO_Or; break;
12178   case tok::ampamp:               Opc = BO_LAnd; break;
12179   case tok::pipepipe:             Opc = BO_LOr; break;
12180   case tok::equal:                Opc = BO_Assign; break;
12181   case tok::starequal:            Opc = BO_MulAssign; break;
12182   case tok::slashequal:           Opc = BO_DivAssign; break;
12183   case tok::percentequal:         Opc = BO_RemAssign; break;
12184   case tok::plusequal:            Opc = BO_AddAssign; break;
12185   case tok::minusequal:           Opc = BO_SubAssign; break;
12186   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12187   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12188   case tok::ampequal:             Opc = BO_AndAssign; break;
12189   case tok::caretequal:           Opc = BO_XorAssign; break;
12190   case tok::pipeequal:            Opc = BO_OrAssign; break;
12191   case tok::comma:                Opc = BO_Comma; break;
12192   }
12193   return Opc;
12194 }
12195 
12196 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12197   tok::TokenKind Kind) {
12198   UnaryOperatorKind Opc;
12199   switch (Kind) {
12200   default: llvm_unreachable("Unknown unary op!");
12201   case tok::plusplus:     Opc = UO_PreInc; break;
12202   case tok::minusminus:   Opc = UO_PreDec; break;
12203   case tok::amp:          Opc = UO_AddrOf; break;
12204   case tok::star:         Opc = UO_Deref; break;
12205   case tok::plus:         Opc = UO_Plus; break;
12206   case tok::minus:        Opc = UO_Minus; break;
12207   case tok::tilde:        Opc = UO_Not; break;
12208   case tok::exclaim:      Opc = UO_LNot; break;
12209   case tok::kw___real:    Opc = UO_Real; break;
12210   case tok::kw___imag:    Opc = UO_Imag; break;
12211   case tok::kw___extension__: Opc = UO_Extension; break;
12212   }
12213   return Opc;
12214 }
12215 
12216 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12217 /// This warning suppressed in the event of macro expansions.
12218 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12219                                    SourceLocation OpLoc, bool IsBuiltin) {
12220   if (S.inTemplateInstantiation())
12221     return;
12222   if (S.isUnevaluatedContext())
12223     return;
12224   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12225     return;
12226   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12227   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12228   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12229   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12230   if (!LHSDeclRef || !RHSDeclRef ||
12231       LHSDeclRef->getLocation().isMacroID() ||
12232       RHSDeclRef->getLocation().isMacroID())
12233     return;
12234   const ValueDecl *LHSDecl =
12235     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12236   const ValueDecl *RHSDecl =
12237     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12238   if (LHSDecl != RHSDecl)
12239     return;
12240   if (LHSDecl->getType().isVolatileQualified())
12241     return;
12242   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12243     if (RefTy->getPointeeType().isVolatileQualified())
12244       return;
12245 
12246   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12247                           : diag::warn_self_assignment_overloaded)
12248       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12249       << RHSExpr->getSourceRange();
12250 }
12251 
12252 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12253 /// is usually indicative of introspection within the Objective-C pointer.
12254 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12255                                           SourceLocation OpLoc) {
12256   if (!S.getLangOpts().ObjC)
12257     return;
12258 
12259   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12260   const Expr *LHS = L.get();
12261   const Expr *RHS = R.get();
12262 
12263   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12264     ObjCPointerExpr = LHS;
12265     OtherExpr = RHS;
12266   }
12267   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12268     ObjCPointerExpr = RHS;
12269     OtherExpr = LHS;
12270   }
12271 
12272   // This warning is deliberately made very specific to reduce false
12273   // positives with logic that uses '&' for hashing.  This logic mainly
12274   // looks for code trying to introspect into tagged pointers, which
12275   // code should generally never do.
12276   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12277     unsigned Diag = diag::warn_objc_pointer_masking;
12278     // Determine if we are introspecting the result of performSelectorXXX.
12279     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12280     // Special case messages to -performSelector and friends, which
12281     // can return non-pointer values boxed in a pointer value.
12282     // Some clients may wish to silence warnings in this subcase.
12283     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12284       Selector S = ME->getSelector();
12285       StringRef SelArg0 = S.getNameForSlot(0);
12286       if (SelArg0.startswith("performSelector"))
12287         Diag = diag::warn_objc_pointer_masking_performSelector;
12288     }
12289 
12290     S.Diag(OpLoc, Diag)
12291       << ObjCPointerExpr->getSourceRange();
12292   }
12293 }
12294 
12295 static NamedDecl *getDeclFromExpr(Expr *E) {
12296   if (!E)
12297     return nullptr;
12298   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12299     return DRE->getDecl();
12300   if (auto *ME = dyn_cast<MemberExpr>(E))
12301     return ME->getMemberDecl();
12302   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12303     return IRE->getDecl();
12304   return nullptr;
12305 }
12306 
12307 // This helper function promotes a binary operator's operands (which are of a
12308 // half vector type) to a vector of floats and then truncates the result to
12309 // a vector of either half or short.
12310 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12311                                       BinaryOperatorKind Opc, QualType ResultTy,
12312                                       ExprValueKind VK, ExprObjectKind OK,
12313                                       bool IsCompAssign, SourceLocation OpLoc,
12314                                       FPOptions FPFeatures) {
12315   auto &Context = S.getASTContext();
12316   assert((isVector(ResultTy, Context.HalfTy) ||
12317           isVector(ResultTy, Context.ShortTy)) &&
12318          "Result must be a vector of half or short");
12319   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12320          isVector(RHS.get()->getType(), Context.HalfTy) &&
12321          "both operands expected to be a half vector");
12322 
12323   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12324   QualType BinOpResTy = RHS.get()->getType();
12325 
12326   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12327   // change BinOpResTy to a vector of ints.
12328   if (isVector(ResultTy, Context.ShortTy))
12329     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12330 
12331   if (IsCompAssign)
12332     return new (Context) CompoundAssignOperator(
12333         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12334         OpLoc, FPFeatures);
12335 
12336   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12337   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12338                                           VK, OK, OpLoc, FPFeatures);
12339   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12340 }
12341 
12342 static std::pair<ExprResult, ExprResult>
12343 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12344                            Expr *RHSExpr) {
12345   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12346   if (!S.getLangOpts().CPlusPlus) {
12347     // C cannot handle TypoExpr nodes on either side of a binop because it
12348     // doesn't handle dependent types properly, so make sure any TypoExprs have
12349     // been dealt with before checking the operands.
12350     LHS = S.CorrectDelayedTyposInExpr(LHS);
12351     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12352       if (Opc != BO_Assign)
12353         return ExprResult(E);
12354       // Avoid correcting the RHS to the same Expr as the LHS.
12355       Decl *D = getDeclFromExpr(E);
12356       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12357     });
12358   }
12359   return std::make_pair(LHS, RHS);
12360 }
12361 
12362 /// Returns true if conversion between vectors of halfs and vectors of floats
12363 /// is needed.
12364 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12365                                      QualType SrcType) {
12366   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12367          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12368          isVector(SrcType, Ctx.HalfTy);
12369 }
12370 
12371 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12372 /// operator @p Opc at location @c TokLoc. This routine only supports
12373 /// built-in operations; ActOnBinOp handles overloaded operators.
12374 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12375                                     BinaryOperatorKind Opc,
12376                                     Expr *LHSExpr, Expr *RHSExpr) {
12377   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12378     // The syntax only allows initializer lists on the RHS of assignment,
12379     // so we don't need to worry about accepting invalid code for
12380     // non-assignment operators.
12381     // C++11 5.17p9:
12382     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12383     //   of x = {} is x = T().
12384     InitializationKind Kind = InitializationKind::CreateDirectList(
12385         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12386     InitializedEntity Entity =
12387         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12388     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12389     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12390     if (Init.isInvalid())
12391       return Init;
12392     RHSExpr = Init.get();
12393   }
12394 
12395   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12396   QualType ResultTy;     // Result type of the binary operator.
12397   // The following two variables are used for compound assignment operators
12398   QualType CompLHSTy;    // Type of LHS after promotions for computation
12399   QualType CompResultTy; // Type of computation result
12400   ExprValueKind VK = VK_RValue;
12401   ExprObjectKind OK = OK_Ordinary;
12402   bool ConvertHalfVec = false;
12403 
12404   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12405   if (!LHS.isUsable() || !RHS.isUsable())
12406     return ExprError();
12407 
12408   if (getLangOpts().OpenCL) {
12409     QualType LHSTy = LHSExpr->getType();
12410     QualType RHSTy = RHSExpr->getType();
12411     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12412     // the ATOMIC_VAR_INIT macro.
12413     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12414       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12415       if (BO_Assign == Opc)
12416         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12417       else
12418         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12419       return ExprError();
12420     }
12421 
12422     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12423     // only with a builtin functions and therefore should be disallowed here.
12424     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12425         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12426         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12427         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12428       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12429       return ExprError();
12430     }
12431   }
12432 
12433   // Diagnose operations on the unsupported types for OpenMP device compilation.
12434   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12435     if (Opc != BO_Assign && Opc != BO_Comma) {
12436       checkOpenMPDeviceExpr(LHSExpr);
12437       checkOpenMPDeviceExpr(RHSExpr);
12438     }
12439   }
12440 
12441   switch (Opc) {
12442   case BO_Assign:
12443     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12444     if (getLangOpts().CPlusPlus &&
12445         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12446       VK = LHS.get()->getValueKind();
12447       OK = LHS.get()->getObjectKind();
12448     }
12449     if (!ResultTy.isNull()) {
12450       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12451       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12452 
12453       // Avoid copying a block to the heap if the block is assigned to a local
12454       // auto variable that is declared in the same scope as the block. This
12455       // optimization is unsafe if the local variable is declared in an outer
12456       // scope. For example:
12457       //
12458       // BlockTy b;
12459       // {
12460       //   b = ^{...};
12461       // }
12462       // // It is unsafe to invoke the block here if it wasn't copied to the
12463       // // heap.
12464       // b();
12465 
12466       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12467         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12468           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12469             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12470               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12471     }
12472     RecordModifiableNonNullParam(*this, LHS.get());
12473     break;
12474   case BO_PtrMemD:
12475   case BO_PtrMemI:
12476     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12477                                             Opc == BO_PtrMemI);
12478     break;
12479   case BO_Mul:
12480   case BO_Div:
12481     ConvertHalfVec = true;
12482     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12483                                            Opc == BO_Div);
12484     break;
12485   case BO_Rem:
12486     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12487     break;
12488   case BO_Add:
12489     ConvertHalfVec = true;
12490     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12491     break;
12492   case BO_Sub:
12493     ConvertHalfVec = true;
12494     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12495     break;
12496   case BO_Shl:
12497   case BO_Shr:
12498     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12499     break;
12500   case BO_LE:
12501   case BO_LT:
12502   case BO_GE:
12503   case BO_GT:
12504     ConvertHalfVec = true;
12505     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12506     break;
12507   case BO_EQ:
12508   case BO_NE:
12509     ConvertHalfVec = true;
12510     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12511     break;
12512   case BO_Cmp:
12513     ConvertHalfVec = true;
12514     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12515     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12516     break;
12517   case BO_And:
12518     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12519     LLVM_FALLTHROUGH;
12520   case BO_Xor:
12521   case BO_Or:
12522     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12523     break;
12524   case BO_LAnd:
12525   case BO_LOr:
12526     ConvertHalfVec = true;
12527     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12528     break;
12529   case BO_MulAssign:
12530   case BO_DivAssign:
12531     ConvertHalfVec = true;
12532     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12533                                                Opc == BO_DivAssign);
12534     CompLHSTy = CompResultTy;
12535     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12536       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12537     break;
12538   case BO_RemAssign:
12539     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12540     CompLHSTy = CompResultTy;
12541     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12542       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12543     break;
12544   case BO_AddAssign:
12545     ConvertHalfVec = true;
12546     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12547     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12548       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12549     break;
12550   case BO_SubAssign:
12551     ConvertHalfVec = true;
12552     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12553     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12554       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12555     break;
12556   case BO_ShlAssign:
12557   case BO_ShrAssign:
12558     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12559     CompLHSTy = CompResultTy;
12560     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12561       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12562     break;
12563   case BO_AndAssign:
12564   case BO_OrAssign: // fallthrough
12565     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12566     LLVM_FALLTHROUGH;
12567   case BO_XorAssign:
12568     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12569     CompLHSTy = CompResultTy;
12570     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12571       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12572     break;
12573   case BO_Comma:
12574     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12575     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12576       VK = RHS.get()->getValueKind();
12577       OK = RHS.get()->getObjectKind();
12578     }
12579     break;
12580   }
12581   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12582     return ExprError();
12583 
12584   // Some of the binary operations require promoting operands of half vector to
12585   // float vectors and truncating the result back to half vector. For now, we do
12586   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12587   // arm64).
12588   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12589          isVector(LHS.get()->getType(), Context.HalfTy) &&
12590          "both sides are half vectors or neither sides are");
12591   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12592                                             LHS.get()->getType());
12593 
12594   // Check for array bounds violations for both sides of the BinaryOperator
12595   CheckArrayAccess(LHS.get());
12596   CheckArrayAccess(RHS.get());
12597 
12598   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12599     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12600                                                  &Context.Idents.get("object_setClass"),
12601                                                  SourceLocation(), LookupOrdinaryName);
12602     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12603       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12604       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12605           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12606                                         "object_setClass(")
12607           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12608                                           ",")
12609           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12610     }
12611     else
12612       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12613   }
12614   else if (const ObjCIvarRefExpr *OIRE =
12615            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12616     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12617 
12618   // Opc is not a compound assignment if CompResultTy is null.
12619   if (CompResultTy.isNull()) {
12620     if (ConvertHalfVec)
12621       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12622                                  OpLoc, FPFeatures);
12623     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12624                                         OK, OpLoc, FPFeatures);
12625   }
12626 
12627   // Handle compound assignments.
12628   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12629       OK_ObjCProperty) {
12630     VK = VK_LValue;
12631     OK = LHS.get()->getObjectKind();
12632   }
12633 
12634   if (ConvertHalfVec)
12635     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12636                                OpLoc, FPFeatures);
12637 
12638   return new (Context) CompoundAssignOperator(
12639       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12640       OpLoc, FPFeatures);
12641 }
12642 
12643 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12644 /// operators are mixed in a way that suggests that the programmer forgot that
12645 /// comparison operators have higher precedence. The most typical example of
12646 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12647 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12648                                       SourceLocation OpLoc, Expr *LHSExpr,
12649                                       Expr *RHSExpr) {
12650   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12651   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12652 
12653   // Check that one of the sides is a comparison operator and the other isn't.
12654   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12655   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12656   if (isLeftComp == isRightComp)
12657     return;
12658 
12659   // Bitwise operations are sometimes used as eager logical ops.
12660   // Don't diagnose this.
12661   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12662   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12663   if (isLeftBitwise || isRightBitwise)
12664     return;
12665 
12666   SourceRange DiagRange = isLeftComp
12667                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12668                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12669   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12670   SourceRange ParensRange =
12671       isLeftComp
12672           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12673           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12674 
12675   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12676     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12677   SuggestParentheses(Self, OpLoc,
12678     Self.PDiag(diag::note_precedence_silence) << OpStr,
12679     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12680   SuggestParentheses(Self, OpLoc,
12681     Self.PDiag(diag::note_precedence_bitwise_first)
12682       << BinaryOperator::getOpcodeStr(Opc),
12683     ParensRange);
12684 }
12685 
12686 /// It accepts a '&&' expr that is inside a '||' one.
12687 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12688 /// in parentheses.
12689 static void
12690 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12691                                        BinaryOperator *Bop) {
12692   assert(Bop->getOpcode() == BO_LAnd);
12693   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12694       << Bop->getSourceRange() << OpLoc;
12695   SuggestParentheses(Self, Bop->getOperatorLoc(),
12696     Self.PDiag(diag::note_precedence_silence)
12697       << Bop->getOpcodeStr(),
12698     Bop->getSourceRange());
12699 }
12700 
12701 /// Returns true if the given expression can be evaluated as a constant
12702 /// 'true'.
12703 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12704   bool Res;
12705   return !E->isValueDependent() &&
12706          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12707 }
12708 
12709 /// Returns true if the given expression can be evaluated as a constant
12710 /// 'false'.
12711 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12712   bool Res;
12713   return !E->isValueDependent() &&
12714          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12715 }
12716 
12717 /// Look for '&&' in the left hand of a '||' expr.
12718 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12719                                              Expr *LHSExpr, Expr *RHSExpr) {
12720   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12721     if (Bop->getOpcode() == BO_LAnd) {
12722       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12723       if (EvaluatesAsFalse(S, RHSExpr))
12724         return;
12725       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12726       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12727         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12728     } else if (Bop->getOpcode() == BO_LOr) {
12729       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12730         // If it's "a || b && 1 || c" we didn't warn earlier for
12731         // "a || b && 1", but warn now.
12732         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12733           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12734       }
12735     }
12736   }
12737 }
12738 
12739 /// Look for '&&' in the right hand of a '||' expr.
12740 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12741                                              Expr *LHSExpr, Expr *RHSExpr) {
12742   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12743     if (Bop->getOpcode() == BO_LAnd) {
12744       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12745       if (EvaluatesAsFalse(S, LHSExpr))
12746         return;
12747       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12748       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12749         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12750     }
12751   }
12752 }
12753 
12754 /// Look for bitwise op in the left or right hand of a bitwise op with
12755 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12756 /// the '&' expression in parentheses.
12757 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12758                                          SourceLocation OpLoc, Expr *SubExpr) {
12759   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12760     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12761       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12762         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12763         << Bop->getSourceRange() << OpLoc;
12764       SuggestParentheses(S, Bop->getOperatorLoc(),
12765         S.PDiag(diag::note_precedence_silence)
12766           << Bop->getOpcodeStr(),
12767         Bop->getSourceRange());
12768     }
12769   }
12770 }
12771 
12772 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12773                                     Expr *SubExpr, StringRef Shift) {
12774   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12775     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12776       StringRef Op = Bop->getOpcodeStr();
12777       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12778           << Bop->getSourceRange() << OpLoc << Shift << Op;
12779       SuggestParentheses(S, Bop->getOperatorLoc(),
12780           S.PDiag(diag::note_precedence_silence) << Op,
12781           Bop->getSourceRange());
12782     }
12783   }
12784 }
12785 
12786 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12787                                  Expr *LHSExpr, Expr *RHSExpr) {
12788   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12789   if (!OCE)
12790     return;
12791 
12792   FunctionDecl *FD = OCE->getDirectCallee();
12793   if (!FD || !FD->isOverloadedOperator())
12794     return;
12795 
12796   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12797   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12798     return;
12799 
12800   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12801       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12802       << (Kind == OO_LessLess);
12803   SuggestParentheses(S, OCE->getOperatorLoc(),
12804                      S.PDiag(diag::note_precedence_silence)
12805                          << (Kind == OO_LessLess ? "<<" : ">>"),
12806                      OCE->getSourceRange());
12807   SuggestParentheses(
12808       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12809       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12810 }
12811 
12812 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12813 /// precedence.
12814 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12815                                     SourceLocation OpLoc, Expr *LHSExpr,
12816                                     Expr *RHSExpr){
12817   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12818   if (BinaryOperator::isBitwiseOp(Opc))
12819     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12820 
12821   // Diagnose "arg1 & arg2 | arg3"
12822   if ((Opc == BO_Or || Opc == BO_Xor) &&
12823       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12824     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12825     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12826   }
12827 
12828   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12829   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12830   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12831     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12832     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12833   }
12834 
12835   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12836       || Opc == BO_Shr) {
12837     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12838     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12839     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12840   }
12841 
12842   // Warn on overloaded shift operators and comparisons, such as:
12843   // cout << 5 == 4;
12844   if (BinaryOperator::isComparisonOp(Opc))
12845     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12846 }
12847 
12848 // Binary Operators.  'Tok' is the token for the operator.
12849 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12850                             tok::TokenKind Kind,
12851                             Expr *LHSExpr, Expr *RHSExpr) {
12852   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12853   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12854   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12855 
12856   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12857   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12858 
12859   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12860 }
12861 
12862 /// Build an overloaded binary operator expression in the given scope.
12863 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12864                                        BinaryOperatorKind Opc,
12865                                        Expr *LHS, Expr *RHS) {
12866   switch (Opc) {
12867   case BO_Assign:
12868   case BO_DivAssign:
12869   case BO_RemAssign:
12870   case BO_SubAssign:
12871   case BO_AndAssign:
12872   case BO_OrAssign:
12873   case BO_XorAssign:
12874     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12875     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12876     break;
12877   default:
12878     break;
12879   }
12880 
12881   // Find all of the overloaded operators visible from this
12882   // point. We perform both an operator-name lookup from the local
12883   // scope and an argument-dependent lookup based on the types of
12884   // the arguments.
12885   UnresolvedSet<16> Functions;
12886   OverloadedOperatorKind OverOp
12887     = BinaryOperator::getOverloadedOperator(Opc);
12888   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12889     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12890                                    RHS->getType(), Functions);
12891 
12892   // Build the (potentially-overloaded, potentially-dependent)
12893   // binary operation.
12894   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12895 }
12896 
12897 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12898                             BinaryOperatorKind Opc,
12899                             Expr *LHSExpr, Expr *RHSExpr) {
12900   ExprResult LHS, RHS;
12901   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12902   if (!LHS.isUsable() || !RHS.isUsable())
12903     return ExprError();
12904   LHSExpr = LHS.get();
12905   RHSExpr = RHS.get();
12906 
12907   // We want to end up calling one of checkPseudoObjectAssignment
12908   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12909   // both expressions are overloadable or either is type-dependent),
12910   // or CreateBuiltinBinOp (in any other case).  We also want to get
12911   // any placeholder types out of the way.
12912 
12913   // Handle pseudo-objects in the LHS.
12914   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12915     // Assignments with a pseudo-object l-value need special analysis.
12916     if (pty->getKind() == BuiltinType::PseudoObject &&
12917         BinaryOperator::isAssignmentOp(Opc))
12918       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12919 
12920     // Don't resolve overloads if the other type is overloadable.
12921     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12922       // We can't actually test that if we still have a placeholder,
12923       // though.  Fortunately, none of the exceptions we see in that
12924       // code below are valid when the LHS is an overload set.  Note
12925       // that an overload set can be dependently-typed, but it never
12926       // instantiates to having an overloadable type.
12927       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12928       if (resolvedRHS.isInvalid()) return ExprError();
12929       RHSExpr = resolvedRHS.get();
12930 
12931       if (RHSExpr->isTypeDependent() ||
12932           RHSExpr->getType()->isOverloadableType())
12933         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12934     }
12935 
12936     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12937     // template, diagnose the missing 'template' keyword instead of diagnosing
12938     // an invalid use of a bound member function.
12939     //
12940     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12941     // to C++1z [over.over]/1.4, but we already checked for that case above.
12942     if (Opc == BO_LT && inTemplateInstantiation() &&
12943         (pty->getKind() == BuiltinType::BoundMember ||
12944          pty->getKind() == BuiltinType::Overload)) {
12945       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12946       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12947           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12948             return isa<FunctionTemplateDecl>(ND);
12949           })) {
12950         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12951                                 : OE->getNameLoc(),
12952              diag::err_template_kw_missing)
12953           << OE->getName().getAsString() << "";
12954         return ExprError();
12955       }
12956     }
12957 
12958     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12959     if (LHS.isInvalid()) return ExprError();
12960     LHSExpr = LHS.get();
12961   }
12962 
12963   // Handle pseudo-objects in the RHS.
12964   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12965     // An overload in the RHS can potentially be resolved by the type
12966     // being assigned to.
12967     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12968       if (getLangOpts().CPlusPlus &&
12969           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12970            LHSExpr->getType()->isOverloadableType()))
12971         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12972 
12973       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12974     }
12975 
12976     // Don't resolve overloads if the other type is overloadable.
12977     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12978         LHSExpr->getType()->isOverloadableType())
12979       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12980 
12981     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12982     if (!resolvedRHS.isUsable()) return ExprError();
12983     RHSExpr = resolvedRHS.get();
12984   }
12985 
12986   if (getLangOpts().CPlusPlus) {
12987     // If either expression is type-dependent, always build an
12988     // overloaded op.
12989     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12990       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12991 
12992     // Otherwise, build an overloaded op if either expression has an
12993     // overloadable type.
12994     if (LHSExpr->getType()->isOverloadableType() ||
12995         RHSExpr->getType()->isOverloadableType())
12996       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12997   }
12998 
12999   // Build a built-in binary operation.
13000   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13001 }
13002 
13003 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13004   if (T.isNull() || T->isDependentType())
13005     return false;
13006 
13007   if (!T->isPromotableIntegerType())
13008     return true;
13009 
13010   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13011 }
13012 
13013 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13014                                       UnaryOperatorKind Opc,
13015                                       Expr *InputExpr) {
13016   ExprResult Input = InputExpr;
13017   ExprValueKind VK = VK_RValue;
13018   ExprObjectKind OK = OK_Ordinary;
13019   QualType resultType;
13020   bool CanOverflow = false;
13021 
13022   bool ConvertHalfVec = false;
13023   if (getLangOpts().OpenCL) {
13024     QualType Ty = InputExpr->getType();
13025     // The only legal unary operation for atomics is '&'.
13026     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13027     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13028     // only with a builtin functions and therefore should be disallowed here.
13029         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13030         || Ty->isBlockPointerType())) {
13031       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13032                        << InputExpr->getType()
13033                        << Input.get()->getSourceRange());
13034     }
13035   }
13036   // Diagnose operations on the unsupported types for OpenMP device compilation.
13037   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13038     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13039         UnaryOperator::isArithmeticOp(Opc))
13040       checkOpenMPDeviceExpr(InputExpr);
13041   }
13042 
13043   switch (Opc) {
13044   case UO_PreInc:
13045   case UO_PreDec:
13046   case UO_PostInc:
13047   case UO_PostDec:
13048     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13049                                                 OpLoc,
13050                                                 Opc == UO_PreInc ||
13051                                                 Opc == UO_PostInc,
13052                                                 Opc == UO_PreInc ||
13053                                                 Opc == UO_PreDec);
13054     CanOverflow = isOverflowingIntegerType(Context, resultType);
13055     break;
13056   case UO_AddrOf:
13057     resultType = CheckAddressOfOperand(Input, OpLoc);
13058     CheckAddressOfNoDeref(InputExpr);
13059     RecordModifiableNonNullParam(*this, InputExpr);
13060     break;
13061   case UO_Deref: {
13062     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13063     if (Input.isInvalid()) return ExprError();
13064     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13065     break;
13066   }
13067   case UO_Plus:
13068   case UO_Minus:
13069     CanOverflow = Opc == UO_Minus &&
13070                   isOverflowingIntegerType(Context, Input.get()->getType());
13071     Input = UsualUnaryConversions(Input.get());
13072     if (Input.isInvalid()) return ExprError();
13073     // Unary plus and minus require promoting an operand of half vector to a
13074     // float vector and truncating the result back to a half vector. For now, we
13075     // do this only when HalfArgsAndReturns is set (that is, when the target is
13076     // arm or arm64).
13077     ConvertHalfVec =
13078         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13079 
13080     // If the operand is a half vector, promote it to a float vector.
13081     if (ConvertHalfVec)
13082       Input = convertVector(Input.get(), Context.FloatTy, *this);
13083     resultType = Input.get()->getType();
13084     if (resultType->isDependentType())
13085       break;
13086     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13087       break;
13088     else if (resultType->isVectorType() &&
13089              // The z vector extensions don't allow + or - with bool vectors.
13090              (!Context.getLangOpts().ZVector ||
13091               resultType->getAs<VectorType>()->getVectorKind() !=
13092               VectorType::AltiVecBool))
13093       break;
13094     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13095              Opc == UO_Plus &&
13096              resultType->isPointerType())
13097       break;
13098 
13099     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13100       << resultType << Input.get()->getSourceRange());
13101 
13102   case UO_Not: // bitwise complement
13103     Input = UsualUnaryConversions(Input.get());
13104     if (Input.isInvalid())
13105       return ExprError();
13106     resultType = Input.get()->getType();
13107 
13108     if (resultType->isDependentType())
13109       break;
13110     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13111     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13112       // C99 does not support '~' for complex conjugation.
13113       Diag(OpLoc, diag::ext_integer_complement_complex)
13114           << resultType << Input.get()->getSourceRange();
13115     else if (resultType->hasIntegerRepresentation())
13116       break;
13117     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13118       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13119       // on vector float types.
13120       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13121       if (!T->isIntegerType())
13122         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13123                           << resultType << Input.get()->getSourceRange());
13124     } else {
13125       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13126                        << resultType << Input.get()->getSourceRange());
13127     }
13128     break;
13129 
13130   case UO_LNot: // logical negation
13131     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13132     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13133     if (Input.isInvalid()) return ExprError();
13134     resultType = Input.get()->getType();
13135 
13136     // Though we still have to promote half FP to float...
13137     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13138       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13139       resultType = Context.FloatTy;
13140     }
13141 
13142     if (resultType->isDependentType())
13143       break;
13144     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13145       // C99 6.5.3.3p1: ok, fallthrough;
13146       if (Context.getLangOpts().CPlusPlus) {
13147         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13148         // operand contextually converted to bool.
13149         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13150                                   ScalarTypeToBooleanCastKind(resultType));
13151       } else if (Context.getLangOpts().OpenCL &&
13152                  Context.getLangOpts().OpenCLVersion < 120) {
13153         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13154         // operate on scalar float types.
13155         if (!resultType->isIntegerType() && !resultType->isPointerType())
13156           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13157                            << resultType << Input.get()->getSourceRange());
13158       }
13159     } else if (resultType->isExtVectorType()) {
13160       if (Context.getLangOpts().OpenCL &&
13161           Context.getLangOpts().OpenCLVersion < 120) {
13162         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13163         // operate on vector float types.
13164         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13165         if (!T->isIntegerType())
13166           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13167                            << resultType << Input.get()->getSourceRange());
13168       }
13169       // Vector logical not returns the signed variant of the operand type.
13170       resultType = GetSignedVectorType(resultType);
13171       break;
13172     } else {
13173       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13174       //        type in C++. We should allow that here too.
13175       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13176         << resultType << Input.get()->getSourceRange());
13177     }
13178 
13179     // LNot always has type int. C99 6.5.3.3p5.
13180     // In C++, it's bool. C++ 5.3.1p8
13181     resultType = Context.getLogicalOperationType();
13182     break;
13183   case UO_Real:
13184   case UO_Imag:
13185     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13186     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13187     // complex l-values to ordinary l-values and all other values to r-values.
13188     if (Input.isInvalid()) return ExprError();
13189     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13190       if (Input.get()->getValueKind() != VK_RValue &&
13191           Input.get()->getObjectKind() == OK_Ordinary)
13192         VK = Input.get()->getValueKind();
13193     } else if (!getLangOpts().CPlusPlus) {
13194       // In C, a volatile scalar is read by __imag. In C++, it is not.
13195       Input = DefaultLvalueConversion(Input.get());
13196     }
13197     break;
13198   case UO_Extension:
13199     resultType = Input.get()->getType();
13200     VK = Input.get()->getValueKind();
13201     OK = Input.get()->getObjectKind();
13202     break;
13203   case UO_Coawait:
13204     // It's unnecessary to represent the pass-through operator co_await in the
13205     // AST; just return the input expression instead.
13206     assert(!Input.get()->getType()->isDependentType() &&
13207                    "the co_await expression must be non-dependant before "
13208                    "building operator co_await");
13209     return Input;
13210   }
13211   if (resultType.isNull() || Input.isInvalid())
13212     return ExprError();
13213 
13214   // Check for array bounds violations in the operand of the UnaryOperator,
13215   // except for the '*' and '&' operators that have to be handled specially
13216   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13217   // that are explicitly defined as valid by the standard).
13218   if (Opc != UO_AddrOf && Opc != UO_Deref)
13219     CheckArrayAccess(Input.get());
13220 
13221   auto *UO = new (Context)
13222       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13223 
13224   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13225       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13226     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13227 
13228   // Convert the result back to a half vector.
13229   if (ConvertHalfVec)
13230     return convertVector(UO, Context.HalfTy, *this);
13231   return UO;
13232 }
13233 
13234 /// Determine whether the given expression is a qualified member
13235 /// access expression, of a form that could be turned into a pointer to member
13236 /// with the address-of operator.
13237 bool Sema::isQualifiedMemberAccess(Expr *E) {
13238   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13239     if (!DRE->getQualifier())
13240       return false;
13241 
13242     ValueDecl *VD = DRE->getDecl();
13243     if (!VD->isCXXClassMember())
13244       return false;
13245 
13246     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13247       return true;
13248     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13249       return Method->isInstance();
13250 
13251     return false;
13252   }
13253 
13254   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13255     if (!ULE->getQualifier())
13256       return false;
13257 
13258     for (NamedDecl *D : ULE->decls()) {
13259       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13260         if (Method->isInstance())
13261           return true;
13262       } else {
13263         // Overload set does not contain methods.
13264         break;
13265       }
13266     }
13267 
13268     return false;
13269   }
13270 
13271   return false;
13272 }
13273 
13274 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13275                               UnaryOperatorKind Opc, Expr *Input) {
13276   // First things first: handle placeholders so that the
13277   // overloaded-operator check considers the right type.
13278   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13279     // Increment and decrement of pseudo-object references.
13280     if (pty->getKind() == BuiltinType::PseudoObject &&
13281         UnaryOperator::isIncrementDecrementOp(Opc))
13282       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13283 
13284     // extension is always a builtin operator.
13285     if (Opc == UO_Extension)
13286       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13287 
13288     // & gets special logic for several kinds of placeholder.
13289     // The builtin code knows what to do.
13290     if (Opc == UO_AddrOf &&
13291         (pty->getKind() == BuiltinType::Overload ||
13292          pty->getKind() == BuiltinType::UnknownAny ||
13293          pty->getKind() == BuiltinType::BoundMember))
13294       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13295 
13296     // Anything else needs to be handled now.
13297     ExprResult Result = CheckPlaceholderExpr(Input);
13298     if (Result.isInvalid()) return ExprError();
13299     Input = Result.get();
13300   }
13301 
13302   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13303       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13304       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13305     // Find all of the overloaded operators visible from this
13306     // point. We perform both an operator-name lookup from the local
13307     // scope and an argument-dependent lookup based on the types of
13308     // the arguments.
13309     UnresolvedSet<16> Functions;
13310     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13311     if (S && OverOp != OO_None)
13312       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13313                                    Functions);
13314 
13315     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13316   }
13317 
13318   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13319 }
13320 
13321 // Unary Operators.  'Tok' is the token for the operator.
13322 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13323                               tok::TokenKind Op, Expr *Input) {
13324   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13325 }
13326 
13327 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13328 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13329                                 LabelDecl *TheDecl) {
13330   TheDecl->markUsed(Context);
13331   // Create the AST node.  The address of a label always has type 'void*'.
13332   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13333                                      Context.getPointerType(Context.VoidTy));
13334 }
13335 
13336 void Sema::ActOnStartStmtExpr() {
13337   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13338 }
13339 
13340 void Sema::ActOnStmtExprError() {
13341   // Note that function is also called by TreeTransform when leaving a
13342   // StmtExpr scope without rebuilding anything.
13343 
13344   DiscardCleanupsInEvaluationContext();
13345   PopExpressionEvaluationContext();
13346 }
13347 
13348 ExprResult
13349 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13350                     SourceLocation RPLoc) { // "({..})"
13351   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13352   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13353 
13354   if (hasAnyUnrecoverableErrorsInThisFunction())
13355     DiscardCleanupsInEvaluationContext();
13356   assert(!Cleanup.exprNeedsCleanups() &&
13357          "cleanups within StmtExpr not correctly bound!");
13358   PopExpressionEvaluationContext();
13359 
13360   // FIXME: there are a variety of strange constraints to enforce here, for
13361   // example, it is not possible to goto into a stmt expression apparently.
13362   // More semantic analysis is needed.
13363 
13364   // If there are sub-stmts in the compound stmt, take the type of the last one
13365   // as the type of the stmtexpr.
13366   QualType Ty = Context.VoidTy;
13367   bool StmtExprMayBindToTemp = false;
13368   if (!Compound->body_empty()) {
13369     if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
13370       if (const Expr *Value = LastStmt->getExprStmt()) {
13371         StmtExprMayBindToTemp = true;
13372         Ty = Value->getType();
13373       }
13374     }
13375   }
13376 
13377   // FIXME: Check that expression type is complete/non-abstract; statement
13378   // expressions are not lvalues.
13379   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13380   if (StmtExprMayBindToTemp)
13381     return MaybeBindToTemporary(ResStmtExpr);
13382   return ResStmtExpr;
13383 }
13384 
13385 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13386   if (ER.isInvalid())
13387     return ExprError();
13388 
13389   // Do function/array conversion on the last expression, but not
13390   // lvalue-to-rvalue.  However, initialize an unqualified type.
13391   ER = DefaultFunctionArrayConversion(ER.get());
13392   if (ER.isInvalid())
13393     return ExprError();
13394   Expr *E = ER.get();
13395 
13396   if (E->isTypeDependent())
13397     return E;
13398 
13399   // In ARC, if the final expression ends in a consume, splice
13400   // the consume out and bind it later.  In the alternate case
13401   // (when dealing with a retainable type), the result
13402   // initialization will create a produce.  In both cases the
13403   // result will be +1, and we'll need to balance that out with
13404   // a bind.
13405   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13406   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13407     return Cast->getSubExpr();
13408 
13409   // FIXME: Provide a better location for the initialization.
13410   return PerformCopyInitialization(
13411       InitializedEntity::InitializeStmtExprResult(
13412           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13413       SourceLocation(), E);
13414 }
13415 
13416 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13417                                       TypeSourceInfo *TInfo,
13418                                       ArrayRef<OffsetOfComponent> Components,
13419                                       SourceLocation RParenLoc) {
13420   QualType ArgTy = TInfo->getType();
13421   bool Dependent = ArgTy->isDependentType();
13422   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13423 
13424   // We must have at least one component that refers to the type, and the first
13425   // one is known to be a field designator.  Verify that the ArgTy represents
13426   // a struct/union/class.
13427   if (!Dependent && !ArgTy->isRecordType())
13428     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13429                        << ArgTy << TypeRange);
13430 
13431   // Type must be complete per C99 7.17p3 because a declaring a variable
13432   // with an incomplete type would be ill-formed.
13433   if (!Dependent
13434       && RequireCompleteType(BuiltinLoc, ArgTy,
13435                              diag::err_offsetof_incomplete_type, TypeRange))
13436     return ExprError();
13437 
13438   bool DidWarnAboutNonPOD = false;
13439   QualType CurrentType = ArgTy;
13440   SmallVector<OffsetOfNode, 4> Comps;
13441   SmallVector<Expr*, 4> Exprs;
13442   for (const OffsetOfComponent &OC : Components) {
13443     if (OC.isBrackets) {
13444       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13445       if (!CurrentType->isDependentType()) {
13446         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13447         if(!AT)
13448           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13449                            << CurrentType);
13450         CurrentType = AT->getElementType();
13451       } else
13452         CurrentType = Context.DependentTy;
13453 
13454       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13455       if (IdxRval.isInvalid())
13456         return ExprError();
13457       Expr *Idx = IdxRval.get();
13458 
13459       // The expression must be an integral expression.
13460       // FIXME: An integral constant expression?
13461       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13462           !Idx->getType()->isIntegerType())
13463         return ExprError(
13464             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13465             << Idx->getSourceRange());
13466 
13467       // Record this array index.
13468       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13469       Exprs.push_back(Idx);
13470       continue;
13471     }
13472 
13473     // Offset of a field.
13474     if (CurrentType->isDependentType()) {
13475       // We have the offset of a field, but we can't look into the dependent
13476       // type. Just record the identifier of the field.
13477       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13478       CurrentType = Context.DependentTy;
13479       continue;
13480     }
13481 
13482     // We need to have a complete type to look into.
13483     if (RequireCompleteType(OC.LocStart, CurrentType,
13484                             diag::err_offsetof_incomplete_type))
13485       return ExprError();
13486 
13487     // Look for the designated field.
13488     const RecordType *RC = CurrentType->getAs<RecordType>();
13489     if (!RC)
13490       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13491                        << CurrentType);
13492     RecordDecl *RD = RC->getDecl();
13493 
13494     // C++ [lib.support.types]p5:
13495     //   The macro offsetof accepts a restricted set of type arguments in this
13496     //   International Standard. type shall be a POD structure or a POD union
13497     //   (clause 9).
13498     // C++11 [support.types]p4:
13499     //   If type is not a standard-layout class (Clause 9), the results are
13500     //   undefined.
13501     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13502       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13503       unsigned DiagID =
13504         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13505                             : diag::ext_offsetof_non_pod_type;
13506 
13507       if (!IsSafe && !DidWarnAboutNonPOD &&
13508           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13509                               PDiag(DiagID)
13510                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13511                               << CurrentType))
13512         DidWarnAboutNonPOD = true;
13513     }
13514 
13515     // Look for the field.
13516     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13517     LookupQualifiedName(R, RD);
13518     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13519     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13520     if (!MemberDecl) {
13521       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13522         MemberDecl = IndirectMemberDecl->getAnonField();
13523     }
13524 
13525     if (!MemberDecl)
13526       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13527                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13528                                                               OC.LocEnd));
13529 
13530     // C99 7.17p3:
13531     //   (If the specified member is a bit-field, the behavior is undefined.)
13532     //
13533     // We diagnose this as an error.
13534     if (MemberDecl->isBitField()) {
13535       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13536         << MemberDecl->getDeclName()
13537         << SourceRange(BuiltinLoc, RParenLoc);
13538       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13539       return ExprError();
13540     }
13541 
13542     RecordDecl *Parent = MemberDecl->getParent();
13543     if (IndirectMemberDecl)
13544       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13545 
13546     // If the member was found in a base class, introduce OffsetOfNodes for
13547     // the base class indirections.
13548     CXXBasePaths Paths;
13549     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13550                       Paths)) {
13551       if (Paths.getDetectedVirtual()) {
13552         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13553           << MemberDecl->getDeclName()
13554           << SourceRange(BuiltinLoc, RParenLoc);
13555         return ExprError();
13556       }
13557 
13558       CXXBasePath &Path = Paths.front();
13559       for (const CXXBasePathElement &B : Path)
13560         Comps.push_back(OffsetOfNode(B.Base));
13561     }
13562 
13563     if (IndirectMemberDecl) {
13564       for (auto *FI : IndirectMemberDecl->chain()) {
13565         assert(isa<FieldDecl>(FI));
13566         Comps.push_back(OffsetOfNode(OC.LocStart,
13567                                      cast<FieldDecl>(FI), OC.LocEnd));
13568       }
13569     } else
13570       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13571 
13572     CurrentType = MemberDecl->getType().getNonReferenceType();
13573   }
13574 
13575   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13576                               Comps, Exprs, RParenLoc);
13577 }
13578 
13579 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13580                                       SourceLocation BuiltinLoc,
13581                                       SourceLocation TypeLoc,
13582                                       ParsedType ParsedArgTy,
13583                                       ArrayRef<OffsetOfComponent> Components,
13584                                       SourceLocation RParenLoc) {
13585 
13586   TypeSourceInfo *ArgTInfo;
13587   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13588   if (ArgTy.isNull())
13589     return ExprError();
13590 
13591   if (!ArgTInfo)
13592     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13593 
13594   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13595 }
13596 
13597 
13598 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13599                                  Expr *CondExpr,
13600                                  Expr *LHSExpr, Expr *RHSExpr,
13601                                  SourceLocation RPLoc) {
13602   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13603 
13604   ExprValueKind VK = VK_RValue;
13605   ExprObjectKind OK = OK_Ordinary;
13606   QualType resType;
13607   bool ValueDependent = false;
13608   bool CondIsTrue = false;
13609   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13610     resType = Context.DependentTy;
13611     ValueDependent = true;
13612   } else {
13613     // The conditional expression is required to be a constant expression.
13614     llvm::APSInt condEval(32);
13615     ExprResult CondICE
13616       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13617           diag::err_typecheck_choose_expr_requires_constant, false);
13618     if (CondICE.isInvalid())
13619       return ExprError();
13620     CondExpr = CondICE.get();
13621     CondIsTrue = condEval.getZExtValue();
13622 
13623     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13624     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13625 
13626     resType = ActiveExpr->getType();
13627     ValueDependent = ActiveExpr->isValueDependent();
13628     VK = ActiveExpr->getValueKind();
13629     OK = ActiveExpr->getObjectKind();
13630   }
13631 
13632   return new (Context)
13633       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13634                  CondIsTrue, resType->isDependentType(), ValueDependent);
13635 }
13636 
13637 //===----------------------------------------------------------------------===//
13638 // Clang Extensions.
13639 //===----------------------------------------------------------------------===//
13640 
13641 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13642 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13643   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13644 
13645   if (LangOpts.CPlusPlus) {
13646     Decl *ManglingContextDecl;
13647     if (MangleNumberingContext *MCtx =
13648             getCurrentMangleNumberContext(Block->getDeclContext(),
13649                                           ManglingContextDecl)) {
13650       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13651       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13652     }
13653   }
13654 
13655   PushBlockScope(CurScope, Block);
13656   CurContext->addDecl(Block);
13657   if (CurScope)
13658     PushDeclContext(CurScope, Block);
13659   else
13660     CurContext = Block;
13661 
13662   getCurBlock()->HasImplicitReturnType = true;
13663 
13664   // Enter a new evaluation context to insulate the block from any
13665   // cleanups from the enclosing full-expression.
13666   PushExpressionEvaluationContext(
13667       ExpressionEvaluationContext::PotentiallyEvaluated);
13668 }
13669 
13670 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13671                                Scope *CurScope) {
13672   assert(ParamInfo.getIdentifier() == nullptr &&
13673          "block-id should have no identifier!");
13674   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13675   BlockScopeInfo *CurBlock = getCurBlock();
13676 
13677   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13678   QualType T = Sig->getType();
13679 
13680   // FIXME: We should allow unexpanded parameter packs here, but that would,
13681   // in turn, make the block expression contain unexpanded parameter packs.
13682   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13683     // Drop the parameters.
13684     FunctionProtoType::ExtProtoInfo EPI;
13685     EPI.HasTrailingReturn = false;
13686     EPI.TypeQuals.addConst();
13687     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13688     Sig = Context.getTrivialTypeSourceInfo(T);
13689   }
13690 
13691   // GetTypeForDeclarator always produces a function type for a block
13692   // literal signature.  Furthermore, it is always a FunctionProtoType
13693   // unless the function was written with a typedef.
13694   assert(T->isFunctionType() &&
13695          "GetTypeForDeclarator made a non-function block signature");
13696 
13697   // Look for an explicit signature in that function type.
13698   FunctionProtoTypeLoc ExplicitSignature;
13699 
13700   if ((ExplicitSignature =
13701            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13702 
13703     // Check whether that explicit signature was synthesized by
13704     // GetTypeForDeclarator.  If so, don't save that as part of the
13705     // written signature.
13706     if (ExplicitSignature.getLocalRangeBegin() ==
13707         ExplicitSignature.getLocalRangeEnd()) {
13708       // This would be much cheaper if we stored TypeLocs instead of
13709       // TypeSourceInfos.
13710       TypeLoc Result = ExplicitSignature.getReturnLoc();
13711       unsigned Size = Result.getFullDataSize();
13712       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13713       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13714 
13715       ExplicitSignature = FunctionProtoTypeLoc();
13716     }
13717   }
13718 
13719   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13720   CurBlock->FunctionType = T;
13721 
13722   const FunctionType *Fn = T->getAs<FunctionType>();
13723   QualType RetTy = Fn->getReturnType();
13724   bool isVariadic =
13725     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13726 
13727   CurBlock->TheDecl->setIsVariadic(isVariadic);
13728 
13729   // Context.DependentTy is used as a placeholder for a missing block
13730   // return type.  TODO:  what should we do with declarators like:
13731   //   ^ * { ... }
13732   // If the answer is "apply template argument deduction"....
13733   if (RetTy != Context.DependentTy) {
13734     CurBlock->ReturnType = RetTy;
13735     CurBlock->TheDecl->setBlockMissingReturnType(false);
13736     CurBlock->HasImplicitReturnType = false;
13737   }
13738 
13739   // Push block parameters from the declarator if we had them.
13740   SmallVector<ParmVarDecl*, 8> Params;
13741   if (ExplicitSignature) {
13742     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13743       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13744       if (Param->getIdentifier() == nullptr &&
13745           !Param->isImplicit() &&
13746           !Param->isInvalidDecl() &&
13747           !getLangOpts().CPlusPlus)
13748         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13749       Params.push_back(Param);
13750     }
13751 
13752   // Fake up parameter variables if we have a typedef, like
13753   //   ^ fntype { ... }
13754   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13755     for (const auto &I : Fn->param_types()) {
13756       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13757           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13758       Params.push_back(Param);
13759     }
13760   }
13761 
13762   // Set the parameters on the block decl.
13763   if (!Params.empty()) {
13764     CurBlock->TheDecl->setParams(Params);
13765     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13766                              /*CheckParameterNames=*/false);
13767   }
13768 
13769   // Finally we can process decl attributes.
13770   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13771 
13772   // Put the parameter variables in scope.
13773   for (auto AI : CurBlock->TheDecl->parameters()) {
13774     AI->setOwningFunction(CurBlock->TheDecl);
13775 
13776     // If this has an identifier, add it to the scope stack.
13777     if (AI->getIdentifier()) {
13778       CheckShadow(CurBlock->TheScope, AI);
13779 
13780       PushOnScopeChains(AI, CurBlock->TheScope);
13781     }
13782   }
13783 }
13784 
13785 /// ActOnBlockError - If there is an error parsing a block, this callback
13786 /// is invoked to pop the information about the block from the action impl.
13787 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13788   // Leave the expression-evaluation context.
13789   DiscardCleanupsInEvaluationContext();
13790   PopExpressionEvaluationContext();
13791 
13792   // Pop off CurBlock, handle nested blocks.
13793   PopDeclContext();
13794   PopFunctionScopeInfo();
13795 }
13796 
13797 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13798 /// literal was successfully completed.  ^(int x){...}
13799 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13800                                     Stmt *Body, Scope *CurScope) {
13801   // If blocks are disabled, emit an error.
13802   if (!LangOpts.Blocks)
13803     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13804 
13805   // Leave the expression-evaluation context.
13806   if (hasAnyUnrecoverableErrorsInThisFunction())
13807     DiscardCleanupsInEvaluationContext();
13808   assert(!Cleanup.exprNeedsCleanups() &&
13809          "cleanups within block not correctly bound!");
13810   PopExpressionEvaluationContext();
13811 
13812   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13813   BlockDecl *BD = BSI->TheDecl;
13814 
13815   if (BSI->HasImplicitReturnType)
13816     deduceClosureReturnType(*BSI);
13817 
13818   PopDeclContext();
13819 
13820   QualType RetTy = Context.VoidTy;
13821   if (!BSI->ReturnType.isNull())
13822     RetTy = BSI->ReturnType;
13823 
13824   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13825   QualType BlockTy;
13826 
13827   // Set the captured variables on the block.
13828   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13829   SmallVector<BlockDecl::Capture, 4> Captures;
13830   for (Capture &Cap : BSI->Captures) {
13831     if (Cap.isThisCapture())
13832       continue;
13833     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13834                               Cap.isNested(), Cap.getInitExpr());
13835     Captures.push_back(NewCap);
13836   }
13837   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13838 
13839   // If the user wrote a function type in some form, try to use that.
13840   if (!BSI->FunctionType.isNull()) {
13841     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13842 
13843     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13844     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13845 
13846     // Turn protoless block types into nullary block types.
13847     if (isa<FunctionNoProtoType>(FTy)) {
13848       FunctionProtoType::ExtProtoInfo EPI;
13849       EPI.ExtInfo = Ext;
13850       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13851 
13852     // Otherwise, if we don't need to change anything about the function type,
13853     // preserve its sugar structure.
13854     } else if (FTy->getReturnType() == RetTy &&
13855                (!NoReturn || FTy->getNoReturnAttr())) {
13856       BlockTy = BSI->FunctionType;
13857 
13858     // Otherwise, make the minimal modifications to the function type.
13859     } else {
13860       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13861       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13862       EPI.TypeQuals = Qualifiers();
13863       EPI.ExtInfo = Ext;
13864       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13865     }
13866 
13867   // If we don't have a function type, just build one from nothing.
13868   } else {
13869     FunctionProtoType::ExtProtoInfo EPI;
13870     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13871     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13872   }
13873 
13874   DiagnoseUnusedParameters(BD->parameters());
13875   BlockTy = Context.getBlockPointerType(BlockTy);
13876 
13877   // If needed, diagnose invalid gotos and switches in the block.
13878   if (getCurFunction()->NeedsScopeChecking() &&
13879       !PP.isCodeCompletionEnabled())
13880     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13881 
13882   BD->setBody(cast<CompoundStmt>(Body));
13883 
13884   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13885     DiagnoseUnguardedAvailabilityViolations(BD);
13886 
13887   // Try to apply the named return value optimization. We have to check again
13888   // if we can do this, though, because blocks keep return statements around
13889   // to deduce an implicit return type.
13890   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13891       !BD->isDependentContext())
13892     computeNRVO(Body, BSI);
13893 
13894   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13895   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13896   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13897 
13898   // If the block isn't obviously global, i.e. it captures anything at
13899   // all, then we need to do a few things in the surrounding context:
13900   if (Result->getBlockDecl()->hasCaptures()) {
13901     // First, this expression has a new cleanup object.
13902     ExprCleanupObjects.push_back(Result->getBlockDecl());
13903     Cleanup.setExprNeedsCleanups(true);
13904 
13905     // It also gets a branch-protected scope if any of the captured
13906     // variables needs destruction.
13907     for (const auto &CI : Result->getBlockDecl()->captures()) {
13908       const VarDecl *var = CI.getVariable();
13909       if (var->getType().isDestructedType() != QualType::DK_none) {
13910         setFunctionHasBranchProtectedScope();
13911         break;
13912       }
13913     }
13914   }
13915 
13916   if (getCurFunction())
13917     getCurFunction()->addBlock(BD);
13918 
13919   return Result;
13920 }
13921 
13922 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13923                             SourceLocation RPLoc) {
13924   TypeSourceInfo *TInfo;
13925   GetTypeFromParser(Ty, &TInfo);
13926   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13927 }
13928 
13929 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13930                                 Expr *E, TypeSourceInfo *TInfo,
13931                                 SourceLocation RPLoc) {
13932   Expr *OrigExpr = E;
13933   bool IsMS = false;
13934 
13935   // CUDA device code does not support varargs.
13936   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13937     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13938       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13939       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13940         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13941     }
13942   }
13943 
13944   // NVPTX does not support va_arg expression.
13945   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
13946       Context.getTargetInfo().getTriple().isNVPTX())
13947     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
13948 
13949   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13950   // as Microsoft ABI on an actual Microsoft platform, where
13951   // __builtin_ms_va_list and __builtin_va_list are the same.)
13952   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13953       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13954     QualType MSVaListType = Context.getBuiltinMSVaListType();
13955     if (Context.hasSameType(MSVaListType, E->getType())) {
13956       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13957         return ExprError();
13958       IsMS = true;
13959     }
13960   }
13961 
13962   // Get the va_list type
13963   QualType VaListType = Context.getBuiltinVaListType();
13964   if (!IsMS) {
13965     if (VaListType->isArrayType()) {
13966       // Deal with implicit array decay; for example, on x86-64,
13967       // va_list is an array, but it's supposed to decay to
13968       // a pointer for va_arg.
13969       VaListType = Context.getArrayDecayedType(VaListType);
13970       // Make sure the input expression also decays appropriately.
13971       ExprResult Result = UsualUnaryConversions(E);
13972       if (Result.isInvalid())
13973         return ExprError();
13974       E = Result.get();
13975     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13976       // If va_list is a record type and we are compiling in C++ mode,
13977       // check the argument using reference binding.
13978       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13979           Context, Context.getLValueReferenceType(VaListType), false);
13980       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13981       if (Init.isInvalid())
13982         return ExprError();
13983       E = Init.getAs<Expr>();
13984     } else {
13985       // Otherwise, the va_list argument must be an l-value because
13986       // it is modified by va_arg.
13987       if (!E->isTypeDependent() &&
13988           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13989         return ExprError();
13990     }
13991   }
13992 
13993   if (!IsMS && !E->isTypeDependent() &&
13994       !Context.hasSameType(VaListType, E->getType()))
13995     return ExprError(
13996         Diag(E->getBeginLoc(),
13997              diag::err_first_argument_to_va_arg_not_of_type_va_list)
13998         << OrigExpr->getType() << E->getSourceRange());
13999 
14000   if (!TInfo->getType()->isDependentType()) {
14001     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14002                             diag::err_second_parameter_to_va_arg_incomplete,
14003                             TInfo->getTypeLoc()))
14004       return ExprError();
14005 
14006     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14007                                TInfo->getType(),
14008                                diag::err_second_parameter_to_va_arg_abstract,
14009                                TInfo->getTypeLoc()))
14010       return ExprError();
14011 
14012     if (!TInfo->getType().isPODType(Context)) {
14013       Diag(TInfo->getTypeLoc().getBeginLoc(),
14014            TInfo->getType()->isObjCLifetimeType()
14015              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14016              : diag::warn_second_parameter_to_va_arg_not_pod)
14017         << TInfo->getType()
14018         << TInfo->getTypeLoc().getSourceRange();
14019     }
14020 
14021     // Check for va_arg where arguments of the given type will be promoted
14022     // (i.e. this va_arg is guaranteed to have undefined behavior).
14023     QualType PromoteType;
14024     if (TInfo->getType()->isPromotableIntegerType()) {
14025       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14026       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14027         PromoteType = QualType();
14028     }
14029     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14030       PromoteType = Context.DoubleTy;
14031     if (!PromoteType.isNull())
14032       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14033                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14034                           << TInfo->getType()
14035                           << PromoteType
14036                           << TInfo->getTypeLoc().getSourceRange());
14037   }
14038 
14039   QualType T = TInfo->getType().getNonLValueExprType(Context);
14040   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14041 }
14042 
14043 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14044   // The type of __null will be int or long, depending on the size of
14045   // pointers on the target.
14046   QualType Ty;
14047   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14048   if (pw == Context.getTargetInfo().getIntWidth())
14049     Ty = Context.IntTy;
14050   else if (pw == Context.getTargetInfo().getLongWidth())
14051     Ty = Context.LongTy;
14052   else if (pw == Context.getTargetInfo().getLongLongWidth())
14053     Ty = Context.LongLongTy;
14054   else {
14055     llvm_unreachable("I don't know size of pointer!");
14056   }
14057 
14058   return new (Context) GNUNullExpr(Ty, TokenLoc);
14059 }
14060 
14061 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14062                                               bool Diagnose) {
14063   if (!getLangOpts().ObjC)
14064     return false;
14065 
14066   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14067   if (!PT)
14068     return false;
14069 
14070   if (!PT->isObjCIdType()) {
14071     // Check if the destination is the 'NSString' interface.
14072     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14073     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14074       return false;
14075   }
14076 
14077   // Ignore any parens, implicit casts (should only be
14078   // array-to-pointer decays), and not-so-opaque values.  The last is
14079   // important for making this trigger for property assignments.
14080   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14081   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14082     if (OV->getSourceExpr())
14083       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14084 
14085   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14086   if (!SL || !SL->isAscii())
14087     return false;
14088   if (Diagnose) {
14089     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14090         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14091     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14092   }
14093   return true;
14094 }
14095 
14096 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14097                                               const Expr *SrcExpr) {
14098   if (!DstType->isFunctionPointerType() ||
14099       !SrcExpr->getType()->isFunctionType())
14100     return false;
14101 
14102   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14103   if (!DRE)
14104     return false;
14105 
14106   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14107   if (!FD)
14108     return false;
14109 
14110   return !S.checkAddressOfFunctionIsAvailable(FD,
14111                                               /*Complain=*/true,
14112                                               SrcExpr->getBeginLoc());
14113 }
14114 
14115 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14116                                     SourceLocation Loc,
14117                                     QualType DstType, QualType SrcType,
14118                                     Expr *SrcExpr, AssignmentAction Action,
14119                                     bool *Complained) {
14120   if (Complained)
14121     *Complained = false;
14122 
14123   // Decode the result (notice that AST's are still created for extensions).
14124   bool CheckInferredResultType = false;
14125   bool isInvalid = false;
14126   unsigned DiagKind = 0;
14127   FixItHint Hint;
14128   ConversionFixItGenerator ConvHints;
14129   bool MayHaveConvFixit = false;
14130   bool MayHaveFunctionDiff = false;
14131   const ObjCInterfaceDecl *IFace = nullptr;
14132   const ObjCProtocolDecl *PDecl = nullptr;
14133 
14134   switch (ConvTy) {
14135   case Compatible:
14136       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14137       return false;
14138 
14139   case PointerToInt:
14140     DiagKind = diag::ext_typecheck_convert_pointer_int;
14141     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14142     MayHaveConvFixit = true;
14143     break;
14144   case IntToPointer:
14145     DiagKind = diag::ext_typecheck_convert_int_pointer;
14146     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14147     MayHaveConvFixit = true;
14148     break;
14149   case IncompatiblePointer:
14150     if (Action == AA_Passing_CFAudited)
14151       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14152     else if (SrcType->isFunctionPointerType() &&
14153              DstType->isFunctionPointerType())
14154       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14155     else
14156       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14157 
14158     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14159       SrcType->isObjCObjectPointerType();
14160     if (Hint.isNull() && !CheckInferredResultType) {
14161       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14162     }
14163     else if (CheckInferredResultType) {
14164       SrcType = SrcType.getUnqualifiedType();
14165       DstType = DstType.getUnqualifiedType();
14166     }
14167     MayHaveConvFixit = true;
14168     break;
14169   case IncompatiblePointerSign:
14170     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14171     break;
14172   case FunctionVoidPointer:
14173     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14174     break;
14175   case IncompatiblePointerDiscardsQualifiers: {
14176     // Perform array-to-pointer decay if necessary.
14177     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14178 
14179     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14180     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14181     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14182       DiagKind = diag::err_typecheck_incompatible_address_space;
14183       break;
14184 
14185     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14186       DiagKind = diag::err_typecheck_incompatible_ownership;
14187       break;
14188     }
14189 
14190     llvm_unreachable("unknown error case for discarding qualifiers!");
14191     // fallthrough
14192   }
14193   case CompatiblePointerDiscardsQualifiers:
14194     // If the qualifiers lost were because we were applying the
14195     // (deprecated) C++ conversion from a string literal to a char*
14196     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14197     // Ideally, this check would be performed in
14198     // checkPointerTypesForAssignment. However, that would require a
14199     // bit of refactoring (so that the second argument is an
14200     // expression, rather than a type), which should be done as part
14201     // of a larger effort to fix checkPointerTypesForAssignment for
14202     // C++ semantics.
14203     if (getLangOpts().CPlusPlus &&
14204         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14205       return false;
14206     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14207     break;
14208   case IncompatibleNestedPointerQualifiers:
14209     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14210     break;
14211   case IntToBlockPointer:
14212     DiagKind = diag::err_int_to_block_pointer;
14213     break;
14214   case IncompatibleBlockPointer:
14215     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14216     break;
14217   case IncompatibleObjCQualifiedId: {
14218     if (SrcType->isObjCQualifiedIdType()) {
14219       const ObjCObjectPointerType *srcOPT =
14220                 SrcType->getAs<ObjCObjectPointerType>();
14221       for (auto *srcProto : srcOPT->quals()) {
14222         PDecl = srcProto;
14223         break;
14224       }
14225       if (const ObjCInterfaceType *IFaceT =
14226             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14227         IFace = IFaceT->getDecl();
14228     }
14229     else if (DstType->isObjCQualifiedIdType()) {
14230       const ObjCObjectPointerType *dstOPT =
14231         DstType->getAs<ObjCObjectPointerType>();
14232       for (auto *dstProto : dstOPT->quals()) {
14233         PDecl = dstProto;
14234         break;
14235       }
14236       if (const ObjCInterfaceType *IFaceT =
14237             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14238         IFace = IFaceT->getDecl();
14239     }
14240     DiagKind = diag::warn_incompatible_qualified_id;
14241     break;
14242   }
14243   case IncompatibleVectors:
14244     DiagKind = diag::warn_incompatible_vectors;
14245     break;
14246   case IncompatibleObjCWeakRef:
14247     DiagKind = diag::err_arc_weak_unavailable_assign;
14248     break;
14249   case Incompatible:
14250     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14251       if (Complained)
14252         *Complained = true;
14253       return true;
14254     }
14255 
14256     DiagKind = diag::err_typecheck_convert_incompatible;
14257     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14258     MayHaveConvFixit = true;
14259     isInvalid = true;
14260     MayHaveFunctionDiff = true;
14261     break;
14262   }
14263 
14264   QualType FirstType, SecondType;
14265   switch (Action) {
14266   case AA_Assigning:
14267   case AA_Initializing:
14268     // The destination type comes first.
14269     FirstType = DstType;
14270     SecondType = SrcType;
14271     break;
14272 
14273   case AA_Returning:
14274   case AA_Passing:
14275   case AA_Passing_CFAudited:
14276   case AA_Converting:
14277   case AA_Sending:
14278   case AA_Casting:
14279     // The source type comes first.
14280     FirstType = SrcType;
14281     SecondType = DstType;
14282     break;
14283   }
14284 
14285   PartialDiagnostic FDiag = PDiag(DiagKind);
14286   if (Action == AA_Passing_CFAudited)
14287     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14288   else
14289     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14290 
14291   // If we can fix the conversion, suggest the FixIts.
14292   assert(ConvHints.isNull() || Hint.isNull());
14293   if (!ConvHints.isNull()) {
14294     for (FixItHint &H : ConvHints.Hints)
14295       FDiag << H;
14296   } else {
14297     FDiag << Hint;
14298   }
14299   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14300 
14301   if (MayHaveFunctionDiff)
14302     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14303 
14304   Diag(Loc, FDiag);
14305   if (DiagKind == diag::warn_incompatible_qualified_id &&
14306       PDecl && IFace && !IFace->hasDefinition())
14307       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14308         << IFace << PDecl;
14309 
14310   if (SecondType == Context.OverloadTy)
14311     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14312                               FirstType, /*TakingAddress=*/true);
14313 
14314   if (CheckInferredResultType)
14315     EmitRelatedResultTypeNote(SrcExpr);
14316 
14317   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14318     EmitRelatedResultTypeNoteForReturn(DstType);
14319 
14320   if (Complained)
14321     *Complained = true;
14322   return isInvalid;
14323 }
14324 
14325 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14326                                                  llvm::APSInt *Result) {
14327   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14328   public:
14329     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14330       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14331     }
14332   } Diagnoser;
14333 
14334   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14335 }
14336 
14337 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14338                                                  llvm::APSInt *Result,
14339                                                  unsigned DiagID,
14340                                                  bool AllowFold) {
14341   class IDDiagnoser : public VerifyICEDiagnoser {
14342     unsigned DiagID;
14343 
14344   public:
14345     IDDiagnoser(unsigned DiagID)
14346       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14347 
14348     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14349       S.Diag(Loc, DiagID) << SR;
14350     }
14351   } Diagnoser(DiagID);
14352 
14353   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14354 }
14355 
14356 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14357                                             SourceRange SR) {
14358   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14359 }
14360 
14361 ExprResult
14362 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14363                                       VerifyICEDiagnoser &Diagnoser,
14364                                       bool AllowFold) {
14365   SourceLocation DiagLoc = E->getBeginLoc();
14366 
14367   if (getLangOpts().CPlusPlus11) {
14368     // C++11 [expr.const]p5:
14369     //   If an expression of literal class type is used in a context where an
14370     //   integral constant expression is required, then that class type shall
14371     //   have a single non-explicit conversion function to an integral or
14372     //   unscoped enumeration type
14373     ExprResult Converted;
14374     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14375     public:
14376       CXX11ConvertDiagnoser(bool Silent)
14377           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14378                                 Silent, true) {}
14379 
14380       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14381                                            QualType T) override {
14382         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14383       }
14384 
14385       SemaDiagnosticBuilder diagnoseIncomplete(
14386           Sema &S, SourceLocation Loc, QualType T) override {
14387         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14388       }
14389 
14390       SemaDiagnosticBuilder diagnoseExplicitConv(
14391           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14392         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14393       }
14394 
14395       SemaDiagnosticBuilder noteExplicitConv(
14396           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14397         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14398                  << ConvTy->isEnumeralType() << ConvTy;
14399       }
14400 
14401       SemaDiagnosticBuilder diagnoseAmbiguous(
14402           Sema &S, SourceLocation Loc, QualType T) override {
14403         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14404       }
14405 
14406       SemaDiagnosticBuilder noteAmbiguous(
14407           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14408         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14409                  << ConvTy->isEnumeralType() << ConvTy;
14410       }
14411 
14412       SemaDiagnosticBuilder diagnoseConversion(
14413           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14414         llvm_unreachable("conversion functions are permitted");
14415       }
14416     } ConvertDiagnoser(Diagnoser.Suppress);
14417 
14418     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14419                                                     ConvertDiagnoser);
14420     if (Converted.isInvalid())
14421       return Converted;
14422     E = Converted.get();
14423     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14424       return ExprError();
14425   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14426     // An ICE must be of integral or unscoped enumeration type.
14427     if (!Diagnoser.Suppress)
14428       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14429     return ExprError();
14430   }
14431 
14432   if (!isa<ConstantExpr>(E))
14433     E = ConstantExpr::Create(Context, E);
14434 
14435   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14436   // in the non-ICE case.
14437   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14438     if (Result)
14439       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14440     return E;
14441   }
14442 
14443   Expr::EvalResult EvalResult;
14444   SmallVector<PartialDiagnosticAt, 8> Notes;
14445   EvalResult.Diag = &Notes;
14446 
14447   // Try to evaluate the expression, and produce diagnostics explaining why it's
14448   // not a constant expression as a side-effect.
14449   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14450                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14451 
14452   // In C++11, we can rely on diagnostics being produced for any expression
14453   // which is not a constant expression. If no diagnostics were produced, then
14454   // this is a constant expression.
14455   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14456     if (Result)
14457       *Result = EvalResult.Val.getInt();
14458     return E;
14459   }
14460 
14461   // If our only note is the usual "invalid subexpression" note, just point
14462   // the caret at its location rather than producing an essentially
14463   // redundant note.
14464   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14465         diag::note_invalid_subexpr_in_const_expr) {
14466     DiagLoc = Notes[0].first;
14467     Notes.clear();
14468   }
14469 
14470   if (!Folded || !AllowFold) {
14471     if (!Diagnoser.Suppress) {
14472       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14473       for (const PartialDiagnosticAt &Note : Notes)
14474         Diag(Note.first, Note.second);
14475     }
14476 
14477     return ExprError();
14478   }
14479 
14480   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14481   for (const PartialDiagnosticAt &Note : Notes)
14482     Diag(Note.first, Note.second);
14483 
14484   if (Result)
14485     *Result = EvalResult.Val.getInt();
14486   return E;
14487 }
14488 
14489 namespace {
14490   // Handle the case where we conclude a expression which we speculatively
14491   // considered to be unevaluated is actually evaluated.
14492   class TransformToPE : public TreeTransform<TransformToPE> {
14493     typedef TreeTransform<TransformToPE> BaseTransform;
14494 
14495   public:
14496     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14497 
14498     // Make sure we redo semantic analysis
14499     bool AlwaysRebuild() { return true; }
14500 
14501     // We need to special-case DeclRefExprs referring to FieldDecls which
14502     // are not part of a member pointer formation; normal TreeTransforming
14503     // doesn't catch this case because of the way we represent them in the AST.
14504     // FIXME: This is a bit ugly; is it really the best way to handle this
14505     // case?
14506     //
14507     // Error on DeclRefExprs referring to FieldDecls.
14508     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14509       if (isa<FieldDecl>(E->getDecl()) &&
14510           !SemaRef.isUnevaluatedContext())
14511         return SemaRef.Diag(E->getLocation(),
14512                             diag::err_invalid_non_static_member_use)
14513             << E->getDecl() << E->getSourceRange();
14514 
14515       return BaseTransform::TransformDeclRefExpr(E);
14516     }
14517 
14518     // Exception: filter out member pointer formation
14519     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14520       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14521         return E;
14522 
14523       return BaseTransform::TransformUnaryOperator(E);
14524     }
14525 
14526     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14527       // Lambdas never need to be transformed.
14528       return E;
14529     }
14530   };
14531 }
14532 
14533 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14534   assert(isUnevaluatedContext() &&
14535          "Should only transform unevaluated expressions");
14536   ExprEvalContexts.back().Context =
14537       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14538   if (isUnevaluatedContext())
14539     return E;
14540   return TransformToPE(*this).TransformExpr(E);
14541 }
14542 
14543 void
14544 Sema::PushExpressionEvaluationContext(
14545     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14546     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14547   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14548                                 LambdaContextDecl, ExprContext);
14549   Cleanup.reset();
14550   if (!MaybeODRUseExprs.empty())
14551     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14552 }
14553 
14554 void
14555 Sema::PushExpressionEvaluationContext(
14556     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14557     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14558   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14559   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14560 }
14561 
14562 namespace {
14563 
14564 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14565   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14566   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14567     if (E->getOpcode() == UO_Deref)
14568       return CheckPossibleDeref(S, E->getSubExpr());
14569   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14570     return CheckPossibleDeref(S, E->getBase());
14571   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14572     return CheckPossibleDeref(S, E->getBase());
14573   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14574     QualType Inner;
14575     QualType Ty = E->getType();
14576     if (const auto *Ptr = Ty->getAs<PointerType>())
14577       Inner = Ptr->getPointeeType();
14578     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14579       Inner = Arr->getElementType();
14580     else
14581       return nullptr;
14582 
14583     if (Inner->hasAttr(attr::NoDeref))
14584       return E;
14585   }
14586   return nullptr;
14587 }
14588 
14589 } // namespace
14590 
14591 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14592   for (const Expr *E : Rec.PossibleDerefs) {
14593     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14594     if (DeclRef) {
14595       const ValueDecl *Decl = DeclRef->getDecl();
14596       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14597           << Decl->getName() << E->getSourceRange();
14598       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14599     } else {
14600       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14601           << E->getSourceRange();
14602     }
14603   }
14604   Rec.PossibleDerefs.clear();
14605 }
14606 
14607 void Sema::PopExpressionEvaluationContext() {
14608   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14609   unsigned NumTypos = Rec.NumTypos;
14610 
14611   if (!Rec.Lambdas.empty()) {
14612     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14613     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14614         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14615       unsigned D;
14616       if (Rec.isUnevaluated()) {
14617         // C++11 [expr.prim.lambda]p2:
14618         //   A lambda-expression shall not appear in an unevaluated operand
14619         //   (Clause 5).
14620         D = diag::err_lambda_unevaluated_operand;
14621       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14622         // C++1y [expr.const]p2:
14623         //   A conditional-expression e is a core constant expression unless the
14624         //   evaluation of e, following the rules of the abstract machine, would
14625         //   evaluate [...] a lambda-expression.
14626         D = diag::err_lambda_in_constant_expression;
14627       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14628         // C++17 [expr.prim.lamda]p2:
14629         // A lambda-expression shall not appear [...] in a template-argument.
14630         D = diag::err_lambda_in_invalid_context;
14631       } else
14632         llvm_unreachable("Couldn't infer lambda error message.");
14633 
14634       for (const auto *L : Rec.Lambdas)
14635         Diag(L->getBeginLoc(), D);
14636     } else {
14637       // Mark the capture expressions odr-used. This was deferred
14638       // during lambda expression creation.
14639       for (auto *Lambda : Rec.Lambdas) {
14640         for (auto *C : Lambda->capture_inits())
14641           MarkDeclarationsReferencedInExpr(C);
14642       }
14643     }
14644   }
14645 
14646   WarnOnPendingNoDerefs(Rec);
14647 
14648   // When are coming out of an unevaluated context, clear out any
14649   // temporaries that we may have created as part of the evaluation of
14650   // the expression in that context: they aren't relevant because they
14651   // will never be constructed.
14652   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14653     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14654                              ExprCleanupObjects.end());
14655     Cleanup = Rec.ParentCleanup;
14656     CleanupVarDeclMarking();
14657     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14658   // Otherwise, merge the contexts together.
14659   } else {
14660     Cleanup.mergeFrom(Rec.ParentCleanup);
14661     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14662                             Rec.SavedMaybeODRUseExprs.end());
14663   }
14664 
14665   // Pop the current expression evaluation context off the stack.
14666   ExprEvalContexts.pop_back();
14667 
14668   // The global expression evaluation context record is never popped.
14669   ExprEvalContexts.back().NumTypos += NumTypos;
14670 }
14671 
14672 void Sema::DiscardCleanupsInEvaluationContext() {
14673   ExprCleanupObjects.erase(
14674          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14675          ExprCleanupObjects.end());
14676   Cleanup.reset();
14677   MaybeODRUseExprs.clear();
14678 }
14679 
14680 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14681   ExprResult Result = CheckPlaceholderExpr(E);
14682   if (Result.isInvalid())
14683     return ExprError();
14684   E = Result.get();
14685   if (!E->getType()->isVariablyModifiedType())
14686     return E;
14687   return TransformToPotentiallyEvaluated(E);
14688 }
14689 
14690 /// Are we within a context in which some evaluation could be performed (be it
14691 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14692 /// captured by C++'s idea of an "unevaluated context".
14693 static bool isEvaluatableContext(Sema &SemaRef) {
14694   switch (SemaRef.ExprEvalContexts.back().Context) {
14695     case Sema::ExpressionEvaluationContext::Unevaluated:
14696     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14697       // Expressions in this context are never evaluated.
14698       return false;
14699 
14700     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14701     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14702     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14703     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14704       // Expressions in this context could be evaluated.
14705       return true;
14706 
14707     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14708       // Referenced declarations will only be used if the construct in the
14709       // containing expression is used, at which point we'll be given another
14710       // turn to mark them.
14711       return false;
14712   }
14713   llvm_unreachable("Invalid context");
14714 }
14715 
14716 /// Are we within a context in which references to resolved functions or to
14717 /// variables result in odr-use?
14718 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14719   // An expression in a template is not really an expression until it's been
14720   // instantiated, so it doesn't trigger odr-use.
14721   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14722     return false;
14723 
14724   switch (SemaRef.ExprEvalContexts.back().Context) {
14725     case Sema::ExpressionEvaluationContext::Unevaluated:
14726     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14727     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14728     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14729       return false;
14730 
14731     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14732     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14733       return true;
14734 
14735     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14736       return false;
14737   }
14738   llvm_unreachable("Invalid context");
14739 }
14740 
14741 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14742   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14743   return Func->isConstexpr() &&
14744          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14745 }
14746 
14747 /// Mark a function referenced, and check whether it is odr-used
14748 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14749 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14750                                   bool MightBeOdrUse) {
14751   assert(Func && "No function?");
14752 
14753   Func->setReferenced();
14754 
14755   // C++11 [basic.def.odr]p3:
14756   //   A function whose name appears as a potentially-evaluated expression is
14757   //   odr-used if it is the unique lookup result or the selected member of a
14758   //   set of overloaded functions [...].
14759   //
14760   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14761   // can just check that here.
14762   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14763 
14764   // Determine whether we require a function definition to exist, per
14765   // C++11 [temp.inst]p3:
14766   //   Unless a function template specialization has been explicitly
14767   //   instantiated or explicitly specialized, the function template
14768   //   specialization is implicitly instantiated when the specialization is
14769   //   referenced in a context that requires a function definition to exist.
14770   //
14771   // That is either when this is an odr-use, or when a usage of a constexpr
14772   // function occurs within an evaluatable context.
14773   bool NeedDefinition =
14774       OdrUse || (isEvaluatableContext(*this) &&
14775                  isImplicitlyDefinableConstexprFunction(Func));
14776 
14777   // C++14 [temp.expl.spec]p6:
14778   //   If a template [...] is explicitly specialized then that specialization
14779   //   shall be declared before the first use of that specialization that would
14780   //   cause an implicit instantiation to take place, in every translation unit
14781   //   in which such a use occurs
14782   if (NeedDefinition &&
14783       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14784        Func->getMemberSpecializationInfo()))
14785     checkSpecializationVisibility(Loc, Func);
14786 
14787   // C++14 [except.spec]p17:
14788   //   An exception-specification is considered to be needed when:
14789   //   - the function is odr-used or, if it appears in an unevaluated operand,
14790   //     would be odr-used if the expression were potentially-evaluated;
14791   //
14792   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14793   // function is a pure virtual function we're calling, and in that case the
14794   // function was selected by overload resolution and we need to resolve its
14795   // exception specification for a different reason.
14796   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14797   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14798     ResolveExceptionSpec(Loc, FPT);
14799 
14800   if (getLangOpts().CUDA)
14801     CheckCUDACall(Loc, Func);
14802 
14803   // If we don't need to mark the function as used, and we don't need to
14804   // try to provide a definition, there's nothing more to do.
14805   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14806       (!NeedDefinition || Func->getBody()))
14807     return;
14808 
14809   // Note that this declaration has been used.
14810   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14811     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14812     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14813       if (Constructor->isDefaultConstructor()) {
14814         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14815           return;
14816         DefineImplicitDefaultConstructor(Loc, Constructor);
14817       } else if (Constructor->isCopyConstructor()) {
14818         DefineImplicitCopyConstructor(Loc, Constructor);
14819       } else if (Constructor->isMoveConstructor()) {
14820         DefineImplicitMoveConstructor(Loc, Constructor);
14821       }
14822     } else if (Constructor->getInheritedConstructor()) {
14823       DefineInheritingConstructor(Loc, Constructor);
14824     }
14825   } else if (CXXDestructorDecl *Destructor =
14826                  dyn_cast<CXXDestructorDecl>(Func)) {
14827     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14828     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14829       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14830         return;
14831       DefineImplicitDestructor(Loc, Destructor);
14832     }
14833     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14834       MarkVTableUsed(Loc, Destructor->getParent());
14835   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14836     if (MethodDecl->isOverloadedOperator() &&
14837         MethodDecl->getOverloadedOperator() == OO_Equal) {
14838       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14839       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14840         if (MethodDecl->isCopyAssignmentOperator())
14841           DefineImplicitCopyAssignment(Loc, MethodDecl);
14842         else if (MethodDecl->isMoveAssignmentOperator())
14843           DefineImplicitMoveAssignment(Loc, MethodDecl);
14844       }
14845     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14846                MethodDecl->getParent()->isLambda()) {
14847       CXXConversionDecl *Conversion =
14848           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14849       if (Conversion->isLambdaToBlockPointerConversion())
14850         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14851       else
14852         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14853     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14854       MarkVTableUsed(Loc, MethodDecl->getParent());
14855   }
14856 
14857   // Recursive functions should be marked when used from another function.
14858   // FIXME: Is this really right?
14859   if (CurContext == Func) return;
14860 
14861   // Implicit instantiation of function templates and member functions of
14862   // class templates.
14863   if (Func->isImplicitlyInstantiable()) {
14864     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14865     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14866     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14867     if (FirstInstantiation) {
14868       PointOfInstantiation = Loc;
14869       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14870     } else if (TSK != TSK_ImplicitInstantiation) {
14871       // Use the point of use as the point of instantiation, instead of the
14872       // point of explicit instantiation (which we track as the actual point of
14873       // instantiation). This gives better backtraces in diagnostics.
14874       PointOfInstantiation = Loc;
14875     }
14876 
14877     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14878         Func->isConstexpr()) {
14879       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14880           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14881           CodeSynthesisContexts.size())
14882         PendingLocalImplicitInstantiations.push_back(
14883             std::make_pair(Func, PointOfInstantiation));
14884       else if (Func->isConstexpr())
14885         // Do not defer instantiations of constexpr functions, to avoid the
14886         // expression evaluator needing to call back into Sema if it sees a
14887         // call to such a function.
14888         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14889       else {
14890         Func->setInstantiationIsPending(true);
14891         PendingInstantiations.push_back(std::make_pair(Func,
14892                                                        PointOfInstantiation));
14893         // Notify the consumer that a function was implicitly instantiated.
14894         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14895       }
14896     }
14897   } else {
14898     // Walk redefinitions, as some of them may be instantiable.
14899     for (auto i : Func->redecls()) {
14900       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14901         MarkFunctionReferenced(Loc, i, OdrUse);
14902     }
14903   }
14904 
14905   if (!OdrUse) return;
14906 
14907   // Keep track of used but undefined functions.
14908   if (!Func->isDefined()) {
14909     if (mightHaveNonExternalLinkage(Func))
14910       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14911     else if (Func->getMostRecentDecl()->isInlined() &&
14912              !LangOpts.GNUInline &&
14913              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14914       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14915     else if (isExternalWithNoLinkageType(Func))
14916       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14917   }
14918 
14919   Func->markUsed(Context);
14920 
14921   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
14922     checkOpenMPDeviceFunction(Loc, Func);
14923 }
14924 
14925 static void
14926 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14927                                    ValueDecl *var, DeclContext *DC) {
14928   DeclContext *VarDC = var->getDeclContext();
14929 
14930   //  If the parameter still belongs to the translation unit, then
14931   //  we're actually just using one parameter in the declaration of
14932   //  the next.
14933   if (isa<ParmVarDecl>(var) &&
14934       isa<TranslationUnitDecl>(VarDC))
14935     return;
14936 
14937   // For C code, don't diagnose about capture if we're not actually in code
14938   // right now; it's impossible to write a non-constant expression outside of
14939   // function context, so we'll get other (more useful) diagnostics later.
14940   //
14941   // For C++, things get a bit more nasty... it would be nice to suppress this
14942   // diagnostic for certain cases like using a local variable in an array bound
14943   // for a member of a local class, but the correct predicate is not obvious.
14944   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14945     return;
14946 
14947   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14948   unsigned ContextKind = 3; // unknown
14949   if (isa<CXXMethodDecl>(VarDC) &&
14950       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14951     ContextKind = 2;
14952   } else if (isa<FunctionDecl>(VarDC)) {
14953     ContextKind = 0;
14954   } else if (isa<BlockDecl>(VarDC)) {
14955     ContextKind = 1;
14956   }
14957 
14958   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14959     << var << ValueKind << ContextKind << VarDC;
14960   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14961       << var;
14962 
14963   // FIXME: Add additional diagnostic info about class etc. which prevents
14964   // capture.
14965 }
14966 
14967 
14968 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14969                                       bool &SubCapturesAreNested,
14970                                       QualType &CaptureType,
14971                                       QualType &DeclRefType) {
14972    // Check whether we've already captured it.
14973   if (CSI->CaptureMap.count(Var)) {
14974     // If we found a capture, any subcaptures are nested.
14975     SubCapturesAreNested = true;
14976 
14977     // Retrieve the capture type for this variable.
14978     CaptureType = CSI->getCapture(Var).getCaptureType();
14979 
14980     // Compute the type of an expression that refers to this variable.
14981     DeclRefType = CaptureType.getNonReferenceType();
14982 
14983     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14984     // are mutable in the sense that user can change their value - they are
14985     // private instances of the captured declarations.
14986     const Capture &Cap = CSI->getCapture(Var);
14987     if (Cap.isCopyCapture() &&
14988         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14989         !(isa<CapturedRegionScopeInfo>(CSI) &&
14990           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14991       DeclRefType.addConst();
14992     return true;
14993   }
14994   return false;
14995 }
14996 
14997 // Only block literals, captured statements, and lambda expressions can
14998 // capture; other scopes don't work.
14999 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15000                                  SourceLocation Loc,
15001                                  const bool Diagnose, Sema &S) {
15002   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15003     return getLambdaAwareParentOfDeclContext(DC);
15004   else if (Var->hasLocalStorage()) {
15005     if (Diagnose)
15006        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15007   }
15008   return nullptr;
15009 }
15010 
15011 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15012 // certain types of variables (unnamed, variably modified types etc.)
15013 // so check for eligibility.
15014 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15015                                  SourceLocation Loc,
15016                                  const bool Diagnose, Sema &S) {
15017 
15018   bool IsBlock = isa<BlockScopeInfo>(CSI);
15019   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15020 
15021   // Lambdas are not allowed to capture unnamed variables
15022   // (e.g. anonymous unions).
15023   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15024   // assuming that's the intent.
15025   if (IsLambda && !Var->getDeclName()) {
15026     if (Diagnose) {
15027       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15028       S.Diag(Var->getLocation(), diag::note_declared_at);
15029     }
15030     return false;
15031   }
15032 
15033   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15034   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15035     if (Diagnose) {
15036       S.Diag(Loc, diag::err_ref_vm_type);
15037       S.Diag(Var->getLocation(), diag::note_previous_decl)
15038         << Var->getDeclName();
15039     }
15040     return false;
15041   }
15042   // Prohibit structs with flexible array members too.
15043   // We cannot capture what is in the tail end of the struct.
15044   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15045     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15046       if (Diagnose) {
15047         if (IsBlock)
15048           S.Diag(Loc, diag::err_ref_flexarray_type);
15049         else
15050           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15051             << Var->getDeclName();
15052         S.Diag(Var->getLocation(), diag::note_previous_decl)
15053           << Var->getDeclName();
15054       }
15055       return false;
15056     }
15057   }
15058   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15059   // Lambdas and captured statements are not allowed to capture __block
15060   // variables; they don't support the expected semantics.
15061   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15062     if (Diagnose) {
15063       S.Diag(Loc, diag::err_capture_block_variable)
15064         << Var->getDeclName() << !IsLambda;
15065       S.Diag(Var->getLocation(), diag::note_previous_decl)
15066         << Var->getDeclName();
15067     }
15068     return false;
15069   }
15070   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15071   if (S.getLangOpts().OpenCL && IsBlock &&
15072       Var->getType()->isBlockPointerType()) {
15073     if (Diagnose)
15074       S.Diag(Loc, diag::err_opencl_block_ref_block);
15075     return false;
15076   }
15077 
15078   return true;
15079 }
15080 
15081 // Returns true if the capture by block was successful.
15082 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15083                                  SourceLocation Loc,
15084                                  const bool BuildAndDiagnose,
15085                                  QualType &CaptureType,
15086                                  QualType &DeclRefType,
15087                                  const bool Nested,
15088                                  Sema &S) {
15089   Expr *CopyExpr = nullptr;
15090   bool ByRef = false;
15091 
15092   // Blocks are not allowed to capture arrays, excepting OpenCL.
15093   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15094   // (decayed to pointers).
15095   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15096     if (BuildAndDiagnose) {
15097       S.Diag(Loc, diag::err_ref_array_type);
15098       S.Diag(Var->getLocation(), diag::note_previous_decl)
15099       << Var->getDeclName();
15100     }
15101     return false;
15102   }
15103 
15104   // Forbid the block-capture of autoreleasing variables.
15105   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15106     if (BuildAndDiagnose) {
15107       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15108         << /*block*/ 0;
15109       S.Diag(Var->getLocation(), diag::note_previous_decl)
15110         << Var->getDeclName();
15111     }
15112     return false;
15113   }
15114 
15115   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15116   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15117     // This function finds out whether there is an AttributedType of kind
15118     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15119     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15120     // rather than being added implicitly by the compiler.
15121     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15122       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15123         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15124           return true;
15125 
15126         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15127         Ty = AttrTy->getModifiedType();
15128       }
15129 
15130       return false;
15131     };
15132 
15133     QualType PointeeTy = PT->getPointeeType();
15134 
15135     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
15136         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15137         !IsObjCOwnershipAttributedType(PointeeTy)) {
15138       if (BuildAndDiagnose) {
15139         SourceLocation VarLoc = Var->getLocation();
15140         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15141         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15142       }
15143     }
15144   }
15145 
15146   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15147   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15148       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15149     // Block capture by reference does not change the capture or
15150     // declaration reference types.
15151     ByRef = true;
15152   } else {
15153     // Block capture by copy introduces 'const'.
15154     CaptureType = CaptureType.getNonReferenceType().withConst();
15155     DeclRefType = CaptureType;
15156 
15157     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15158       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15159         // The capture logic needs the destructor, so make sure we mark it.
15160         // Usually this is unnecessary because most local variables have
15161         // their destructors marked at declaration time, but parameters are
15162         // an exception because it's technically only the call site that
15163         // actually requires the destructor.
15164         if (isa<ParmVarDecl>(Var))
15165           S.FinalizeVarWithDestructor(Var, Record);
15166 
15167         // Enter a new evaluation context to insulate the copy
15168         // full-expression.
15169         EnterExpressionEvaluationContext scope(
15170             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
15171 
15172         // According to the blocks spec, the capture of a variable from
15173         // the stack requires a const copy constructor.  This is not true
15174         // of the copy/move done to move a __block variable to the heap.
15175         Expr *DeclRef = new (S.Context) DeclRefExpr(
15176             S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15177 
15178         ExprResult Result
15179           = S.PerformCopyInitialization(
15180               InitializedEntity::InitializeBlock(Var->getLocation(),
15181                                                   CaptureType, false),
15182               Loc, DeclRef);
15183 
15184         // Build a full-expression copy expression if initialization
15185         // succeeded and used a non-trivial constructor.  Recover from
15186         // errors by pretending that the copy isn't necessary.
15187         if (!Result.isInvalid() &&
15188             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15189                 ->isTrivial()) {
15190           Result = S.MaybeCreateExprWithCleanups(Result);
15191           CopyExpr = Result.get();
15192         }
15193       }
15194     }
15195   }
15196 
15197   // Actually capture the variable.
15198   if (BuildAndDiagnose)
15199     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15200                     SourceLocation(), CaptureType, CopyExpr);
15201 
15202   return true;
15203 
15204 }
15205 
15206 
15207 /// Capture the given variable in the captured region.
15208 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15209                                     VarDecl *Var,
15210                                     SourceLocation Loc,
15211                                     const bool BuildAndDiagnose,
15212                                     QualType &CaptureType,
15213                                     QualType &DeclRefType,
15214                                     const bool RefersToCapturedVariable,
15215                                     Sema &S) {
15216   // By default, capture variables by reference.
15217   bool ByRef = true;
15218   // Using an LValue reference type is consistent with Lambdas (see below).
15219   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15220     if (S.isOpenMPCapturedDecl(Var)) {
15221       bool HasConst = DeclRefType.isConstQualified();
15222       DeclRefType = DeclRefType.getUnqualifiedType();
15223       // Don't lose diagnostics about assignments to const.
15224       if (HasConst)
15225         DeclRefType.addConst();
15226     }
15227     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15228   }
15229 
15230   if (ByRef)
15231     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15232   else
15233     CaptureType = DeclRefType;
15234 
15235   Expr *CopyExpr = nullptr;
15236   if (BuildAndDiagnose) {
15237     // The current implementation assumes that all variables are captured
15238     // by references. Since there is no capture by copy, no expression
15239     // evaluation will be needed.
15240     RecordDecl *RD = RSI->TheRecordDecl;
15241 
15242     FieldDecl *Field
15243       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15244                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15245                           nullptr, false, ICIS_NoInit);
15246     Field->setImplicit(true);
15247     Field->setAccess(AS_private);
15248     RD->addDecl(Field);
15249     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15250       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15251 
15252     CopyExpr = new (S.Context) DeclRefExpr(
15253         S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15254     Var->setReferenced(true);
15255     Var->markUsed(S.Context);
15256   }
15257 
15258   // Actually capture the variable.
15259   if (BuildAndDiagnose)
15260     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15261                     SourceLocation(), CaptureType, CopyExpr);
15262 
15263 
15264   return true;
15265 }
15266 
15267 /// Create a field within the lambda class for the variable
15268 /// being captured.
15269 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
15270                                     QualType FieldType, QualType DeclRefType,
15271                                     SourceLocation Loc,
15272                                     bool RefersToCapturedVariable) {
15273   CXXRecordDecl *Lambda = LSI->Lambda;
15274 
15275   // Build the non-static data member.
15276   FieldDecl *Field
15277     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15278                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15279                         nullptr, false, ICIS_NoInit);
15280   // If the variable being captured has an invalid type, mark the lambda class
15281   // as invalid as well.
15282   if (!FieldType->isDependentType()) {
15283     if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15284       Lambda->setInvalidDecl();
15285       Field->setInvalidDecl();
15286     } else {
15287       NamedDecl *Def;
15288       FieldType->isIncompleteType(&Def);
15289       if (Def && Def->isInvalidDecl()) {
15290         Lambda->setInvalidDecl();
15291         Field->setInvalidDecl();
15292       }
15293     }
15294   }
15295   Field->setImplicit(true);
15296   Field->setAccess(AS_private);
15297   Lambda->addDecl(Field);
15298 }
15299 
15300 /// Capture the given variable in the lambda.
15301 static bool captureInLambda(LambdaScopeInfo *LSI,
15302                             VarDecl *Var,
15303                             SourceLocation Loc,
15304                             const bool BuildAndDiagnose,
15305                             QualType &CaptureType,
15306                             QualType &DeclRefType,
15307                             const bool RefersToCapturedVariable,
15308                             const Sema::TryCaptureKind Kind,
15309                             SourceLocation EllipsisLoc,
15310                             const bool IsTopScope,
15311                             Sema &S) {
15312 
15313   // Determine whether we are capturing by reference or by value.
15314   bool ByRef = false;
15315   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15316     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15317   } else {
15318     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15319   }
15320 
15321   // Compute the type of the field that will capture this variable.
15322   if (ByRef) {
15323     // C++11 [expr.prim.lambda]p15:
15324     //   An entity is captured by reference if it is implicitly or
15325     //   explicitly captured but not captured by copy. It is
15326     //   unspecified whether additional unnamed non-static data
15327     //   members are declared in the closure type for entities
15328     //   captured by reference.
15329     //
15330     // FIXME: It is not clear whether we want to build an lvalue reference
15331     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15332     // to do the former, while EDG does the latter. Core issue 1249 will
15333     // clarify, but for now we follow GCC because it's a more permissive and
15334     // easily defensible position.
15335     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15336   } else {
15337     // C++11 [expr.prim.lambda]p14:
15338     //   For each entity captured by copy, an unnamed non-static
15339     //   data member is declared in the closure type. The
15340     //   declaration order of these members is unspecified. The type
15341     //   of such a data member is the type of the corresponding
15342     //   captured entity if the entity is not a reference to an
15343     //   object, or the referenced type otherwise. [Note: If the
15344     //   captured entity is a reference to a function, the
15345     //   corresponding data member is also a reference to a
15346     //   function. - end note ]
15347     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15348       if (!RefType->getPointeeType()->isFunctionType())
15349         CaptureType = RefType->getPointeeType();
15350     }
15351 
15352     // Forbid the lambda copy-capture of autoreleasing variables.
15353     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15354       if (BuildAndDiagnose) {
15355         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15356         S.Diag(Var->getLocation(), diag::note_previous_decl)
15357           << Var->getDeclName();
15358       }
15359       return false;
15360     }
15361 
15362     // Make sure that by-copy captures are of a complete and non-abstract type.
15363     if (BuildAndDiagnose) {
15364       if (!CaptureType->isDependentType() &&
15365           S.RequireCompleteType(Loc, CaptureType,
15366                                 diag::err_capture_of_incomplete_type,
15367                                 Var->getDeclName()))
15368         return false;
15369 
15370       if (S.RequireNonAbstractType(Loc, CaptureType,
15371                                    diag::err_capture_of_abstract_type))
15372         return false;
15373     }
15374   }
15375 
15376   // Capture this variable in the lambda.
15377   if (BuildAndDiagnose)
15378     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15379                             RefersToCapturedVariable);
15380 
15381   // Compute the type of a reference to this captured variable.
15382   if (ByRef)
15383     DeclRefType = CaptureType.getNonReferenceType();
15384   else {
15385     // C++ [expr.prim.lambda]p5:
15386     //   The closure type for a lambda-expression has a public inline
15387     //   function call operator [...]. This function call operator is
15388     //   declared const (9.3.1) if and only if the lambda-expression's
15389     //   parameter-declaration-clause is not followed by mutable.
15390     DeclRefType = CaptureType.getNonReferenceType();
15391     if (!LSI->Mutable && !CaptureType->isReferenceType())
15392       DeclRefType.addConst();
15393   }
15394 
15395   // Add the capture.
15396   if (BuildAndDiagnose)
15397     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15398                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15399 
15400   return true;
15401 }
15402 
15403 bool Sema::tryCaptureVariable(
15404     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15405     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15406     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15407   // An init-capture is notionally from the context surrounding its
15408   // declaration, but its parent DC is the lambda class.
15409   DeclContext *VarDC = Var->getDeclContext();
15410   if (Var->isInitCapture())
15411     VarDC = VarDC->getParent();
15412 
15413   DeclContext *DC = CurContext;
15414   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15415       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15416   // We need to sync up the Declaration Context with the
15417   // FunctionScopeIndexToStopAt
15418   if (FunctionScopeIndexToStopAt) {
15419     unsigned FSIndex = FunctionScopes.size() - 1;
15420     while (FSIndex != MaxFunctionScopesIndex) {
15421       DC = getLambdaAwareParentOfDeclContext(DC);
15422       --FSIndex;
15423     }
15424   }
15425 
15426 
15427   // If the variable is declared in the current context, there is no need to
15428   // capture it.
15429   if (VarDC == DC) return true;
15430 
15431   // Capture global variables if it is required to use private copy of this
15432   // variable.
15433   bool IsGlobal = !Var->hasLocalStorage();
15434   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15435     return true;
15436   Var = Var->getCanonicalDecl();
15437 
15438   // Walk up the stack to determine whether we can capture the variable,
15439   // performing the "simple" checks that don't depend on type. We stop when
15440   // we've either hit the declared scope of the variable or find an existing
15441   // capture of that variable.  We start from the innermost capturing-entity
15442   // (the DC) and ensure that all intervening capturing-entities
15443   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15444   // declcontext can either capture the variable or have already captured
15445   // the variable.
15446   CaptureType = Var->getType();
15447   DeclRefType = CaptureType.getNonReferenceType();
15448   bool Nested = false;
15449   bool Explicit = (Kind != TryCapture_Implicit);
15450   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15451   do {
15452     // Only block literals, captured statements, and lambda expressions can
15453     // capture; other scopes don't work.
15454     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15455                                                               ExprLoc,
15456                                                               BuildAndDiagnose,
15457                                                               *this);
15458     // We need to check for the parent *first* because, if we *have*
15459     // private-captured a global variable, we need to recursively capture it in
15460     // intermediate blocks, lambdas, etc.
15461     if (!ParentDC) {
15462       if (IsGlobal) {
15463         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15464         break;
15465       }
15466       return true;
15467     }
15468 
15469     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15470     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15471 
15472 
15473     // Check whether we've already captured it.
15474     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15475                                              DeclRefType)) {
15476       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15477       break;
15478     }
15479     // If we are instantiating a generic lambda call operator body,
15480     // we do not want to capture new variables.  What was captured
15481     // during either a lambdas transformation or initial parsing
15482     // should be used.
15483     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15484       if (BuildAndDiagnose) {
15485         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15486         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15487           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15488           Diag(Var->getLocation(), diag::note_previous_decl)
15489              << Var->getDeclName();
15490           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15491         } else
15492           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15493       }
15494       return true;
15495     }
15496     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15497     // certain types of variables (unnamed, variably modified types etc.)
15498     // so check for eligibility.
15499     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15500        return true;
15501 
15502     // Try to capture variable-length arrays types.
15503     if (Var->getType()->isVariablyModifiedType()) {
15504       // We're going to walk down into the type and look for VLA
15505       // expressions.
15506       QualType QTy = Var->getType();
15507       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15508         QTy = PVD->getOriginalType();
15509       captureVariablyModifiedType(Context, QTy, CSI);
15510     }
15511 
15512     if (getLangOpts().OpenMP) {
15513       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15514         // OpenMP private variables should not be captured in outer scope, so
15515         // just break here. Similarly, global variables that are captured in a
15516         // target region should not be captured outside the scope of the region.
15517         if (RSI->CapRegionKind == CR_OpenMP) {
15518           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15519           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15520                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15521           // When we detect target captures we are looking from inside the
15522           // target region, therefore we need to propagate the capture from the
15523           // enclosing region. Therefore, the capture is not initially nested.
15524           if (IsTargetCap)
15525             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15526 
15527           if (IsTargetCap || IsOpenMPPrivateDecl) {
15528             Nested = !IsTargetCap;
15529             DeclRefType = DeclRefType.getUnqualifiedType();
15530             CaptureType = Context.getLValueReferenceType(DeclRefType);
15531             break;
15532           }
15533         }
15534       }
15535     }
15536     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15537       // No capture-default, and this is not an explicit capture
15538       // so cannot capture this variable.
15539       if (BuildAndDiagnose) {
15540         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15541         Diag(Var->getLocation(), diag::note_previous_decl)
15542           << Var->getDeclName();
15543         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15544           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15545                diag::note_lambda_decl);
15546         // FIXME: If we error out because an outer lambda can not implicitly
15547         // capture a variable that an inner lambda explicitly captures, we
15548         // should have the inner lambda do the explicit capture - because
15549         // it makes for cleaner diagnostics later.  This would purely be done
15550         // so that the diagnostic does not misleadingly claim that a variable
15551         // can not be captured by a lambda implicitly even though it is captured
15552         // explicitly.  Suggestion:
15553         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15554         //    at the function head
15555         //  - cache the StartingDeclContext - this must be a lambda
15556         //  - captureInLambda in the innermost lambda the variable.
15557       }
15558       return true;
15559     }
15560 
15561     FunctionScopesIndex--;
15562     DC = ParentDC;
15563     Explicit = false;
15564   } while (!VarDC->Equals(DC));
15565 
15566   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15567   // computing the type of the capture at each step, checking type-specific
15568   // requirements, and adding captures if requested.
15569   // If the variable had already been captured previously, we start capturing
15570   // at the lambda nested within that one.
15571   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15572        ++I) {
15573     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15574 
15575     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15576       if (!captureInBlock(BSI, Var, ExprLoc,
15577                           BuildAndDiagnose, CaptureType,
15578                           DeclRefType, Nested, *this))
15579         return true;
15580       Nested = true;
15581     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15582       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15583                                    BuildAndDiagnose, CaptureType,
15584                                    DeclRefType, Nested, *this))
15585         return true;
15586       Nested = true;
15587     } else {
15588       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15589       if (!captureInLambda(LSI, Var, ExprLoc,
15590                            BuildAndDiagnose, CaptureType,
15591                            DeclRefType, Nested, Kind, EllipsisLoc,
15592                             /*IsTopScope*/I == N - 1, *this))
15593         return true;
15594       Nested = true;
15595     }
15596   }
15597   return false;
15598 }
15599 
15600 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15601                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15602   QualType CaptureType;
15603   QualType DeclRefType;
15604   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15605                             /*BuildAndDiagnose=*/true, CaptureType,
15606                             DeclRefType, nullptr);
15607 }
15608 
15609 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15610   QualType CaptureType;
15611   QualType DeclRefType;
15612   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15613                              /*BuildAndDiagnose=*/false, CaptureType,
15614                              DeclRefType, nullptr);
15615 }
15616 
15617 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15618   QualType CaptureType;
15619   QualType DeclRefType;
15620 
15621   // Determine whether we can capture this variable.
15622   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15623                          /*BuildAndDiagnose=*/false, CaptureType,
15624                          DeclRefType, nullptr))
15625     return QualType();
15626 
15627   return DeclRefType;
15628 }
15629 
15630 
15631 
15632 // If either the type of the variable or the initializer is dependent,
15633 // return false. Otherwise, determine whether the variable is a constant
15634 // expression. Use this if you need to know if a variable that might or
15635 // might not be dependent is truly a constant expression.
15636 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15637     ASTContext &Context) {
15638 
15639   if (Var->getType()->isDependentType())
15640     return false;
15641   const VarDecl *DefVD = nullptr;
15642   Var->getAnyInitializer(DefVD);
15643   if (!DefVD)
15644     return false;
15645   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15646   Expr *Init = cast<Expr>(Eval->Value);
15647   if (Init->isValueDependent())
15648     return false;
15649   return IsVariableAConstantExpression(Var, Context);
15650 }
15651 
15652 
15653 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15654   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15655   // an object that satisfies the requirements for appearing in a
15656   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15657   // is immediately applied."  This function handles the lvalue-to-rvalue
15658   // conversion part.
15659   MaybeODRUseExprs.erase(E->IgnoreParens());
15660 
15661   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15662   // to a variable that is a constant expression, and if so, identify it as
15663   // a reference to a variable that does not involve an odr-use of that
15664   // variable.
15665   if (LambdaScopeInfo *LSI = getCurLambda()) {
15666     Expr *SansParensExpr = E->IgnoreParens();
15667     VarDecl *Var = nullptr;
15668     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15669       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15670     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15671       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15672 
15673     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15674       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15675   }
15676 }
15677 
15678 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15679   Res = CorrectDelayedTyposInExpr(Res);
15680 
15681   if (!Res.isUsable())
15682     return Res;
15683 
15684   // If a constant-expression is a reference to a variable where we delay
15685   // deciding whether it is an odr-use, just assume we will apply the
15686   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15687   // (a non-type template argument), we have special handling anyway.
15688   UpdateMarkingForLValueToRValue(Res.get());
15689   return Res;
15690 }
15691 
15692 void Sema::CleanupVarDeclMarking() {
15693   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
15694   // call.
15695   MaybeODRUseExprSet LocalMaybeODRUseExprs;
15696   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
15697 
15698   for (Expr *E : LocalMaybeODRUseExprs) {
15699     VarDecl *Var;
15700     SourceLocation Loc;
15701     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15702       Var = cast<VarDecl>(DRE->getDecl());
15703       Loc = DRE->getLocation();
15704     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15705       Var = cast<VarDecl>(ME->getMemberDecl());
15706       Loc = ME->getMemberLoc();
15707     } else {
15708       llvm_unreachable("Unexpected expression");
15709     }
15710 
15711     MarkVarDeclODRUsed(Var, Loc, *this,
15712                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15713   }
15714 
15715   assert(MaybeODRUseExprs.empty() &&
15716          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
15717 }
15718 
15719 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15720                                     VarDecl *Var, Expr *E) {
15721   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15722          "Invalid Expr argument to DoMarkVarDeclReferenced");
15723   Var->setReferenced();
15724 
15725   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15726 
15727   bool OdrUseContext = isOdrUseContext(SemaRef);
15728   bool UsableInConstantExpr =
15729       Var->isUsableInConstantExpressions(SemaRef.Context);
15730   bool NeedDefinition =
15731       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15732 
15733   VarTemplateSpecializationDecl *VarSpec =
15734       dyn_cast<VarTemplateSpecializationDecl>(Var);
15735   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15736          "Can't instantiate a partial template specialization.");
15737 
15738   // If this might be a member specialization of a static data member, check
15739   // the specialization is visible. We already did the checks for variable
15740   // template specializations when we created them.
15741   if (NeedDefinition && TSK != TSK_Undeclared &&
15742       !isa<VarTemplateSpecializationDecl>(Var))
15743     SemaRef.checkSpecializationVisibility(Loc, Var);
15744 
15745   // Perform implicit instantiation of static data members, static data member
15746   // templates of class templates, and variable template specializations. Delay
15747   // instantiations of variable templates, except for those that could be used
15748   // in a constant expression.
15749   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15750     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15751     // instantiation declaration if a variable is usable in a constant
15752     // expression (among other cases).
15753     bool TryInstantiating =
15754         TSK == TSK_ImplicitInstantiation ||
15755         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15756 
15757     if (TryInstantiating) {
15758       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15759       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15760       if (FirstInstantiation) {
15761         PointOfInstantiation = Loc;
15762         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15763       }
15764 
15765       bool InstantiationDependent = false;
15766       bool IsNonDependent =
15767           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15768                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15769                   : true;
15770 
15771       // Do not instantiate specializations that are still type-dependent.
15772       if (IsNonDependent) {
15773         if (UsableInConstantExpr) {
15774           // Do not defer instantiations of variables that could be used in a
15775           // constant expression.
15776           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15777         } else if (FirstInstantiation ||
15778                    isa<VarTemplateSpecializationDecl>(Var)) {
15779           // FIXME: For a specialization of a variable template, we don't
15780           // distinguish between "declaration and type implicitly instantiated"
15781           // and "implicit instantiation of definition requested", so we have
15782           // no direct way to avoid enqueueing the pending instantiation
15783           // multiple times.
15784           SemaRef.PendingInstantiations
15785               .push_back(std::make_pair(Var, PointOfInstantiation));
15786         }
15787       }
15788     }
15789   }
15790 
15791   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15792   // the requirements for appearing in a constant expression (5.19) and, if
15793   // it is an object, the lvalue-to-rvalue conversion (4.1)
15794   // is immediately applied."  We check the first part here, and
15795   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15796   // Note that we use the C++11 definition everywhere because nothing in
15797   // C++03 depends on whether we get the C++03 version correct. The second
15798   // part does not apply to references, since they are not objects.
15799   if (OdrUseContext && E &&
15800       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15801     // A reference initialized by a constant expression can never be
15802     // odr-used, so simply ignore it.
15803     if (!Var->getType()->isReferenceType() ||
15804         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15805       SemaRef.MaybeODRUseExprs.insert(E);
15806   } else if (OdrUseContext) {
15807     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15808                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15809   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15810     // If this is a dependent context, we don't need to mark variables as
15811     // odr-used, but we may still need to track them for lambda capture.
15812     // FIXME: Do we also need to do this inside dependent typeid expressions
15813     // (which are modeled as unevaluated at this point)?
15814     const bool RefersToEnclosingScope =
15815         (SemaRef.CurContext != Var->getDeclContext() &&
15816          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15817     if (RefersToEnclosingScope) {
15818       LambdaScopeInfo *const LSI =
15819           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15820       if (LSI && (!LSI->CallOperator ||
15821                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15822         // If a variable could potentially be odr-used, defer marking it so
15823         // until we finish analyzing the full expression for any
15824         // lvalue-to-rvalue
15825         // or discarded value conversions that would obviate odr-use.
15826         // Add it to the list of potential captures that will be analyzed
15827         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15828         // unless the variable is a reference that was initialized by a constant
15829         // expression (this will never need to be captured or odr-used).
15830         assert(E && "Capture variable should be used in an expression.");
15831         if (!Var->getType()->isReferenceType() ||
15832             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15833           LSI->addPotentialCapture(E->IgnoreParens());
15834       }
15835     }
15836   }
15837 }
15838 
15839 /// Mark a variable referenced, and check whether it is odr-used
15840 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15841 /// used directly for normal expressions referring to VarDecl.
15842 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15843   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15844 }
15845 
15846 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15847                                Decl *D, Expr *E, bool MightBeOdrUse) {
15848   if (SemaRef.isInOpenMPDeclareTargetContext())
15849     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15850 
15851   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15852     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15853     return;
15854   }
15855 
15856   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15857 
15858   // If this is a call to a method via a cast, also mark the method in the
15859   // derived class used in case codegen can devirtualize the call.
15860   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15861   if (!ME)
15862     return;
15863   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15864   if (!MD)
15865     return;
15866   // Only attempt to devirtualize if this is truly a virtual call.
15867   bool IsVirtualCall = MD->isVirtual() &&
15868                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15869   if (!IsVirtualCall)
15870     return;
15871 
15872   // If it's possible to devirtualize the call, mark the called function
15873   // referenced.
15874   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15875       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15876   if (DM)
15877     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15878 }
15879 
15880 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15881 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15882   // TODO: update this with DR# once a defect report is filed.
15883   // C++11 defect. The address of a pure member should not be an ODR use, even
15884   // if it's a qualified reference.
15885   bool OdrUse = true;
15886   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15887     if (Method->isVirtual() &&
15888         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15889       OdrUse = false;
15890   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15891 }
15892 
15893 /// Perform reference-marking and odr-use handling for a MemberExpr.
15894 void Sema::MarkMemberReferenced(MemberExpr *E) {
15895   // C++11 [basic.def.odr]p2:
15896   //   A non-overloaded function whose name appears as a potentially-evaluated
15897   //   expression or a member of a set of candidate functions, if selected by
15898   //   overload resolution when referred to from a potentially-evaluated
15899   //   expression, is odr-used, unless it is a pure virtual function and its
15900   //   name is not explicitly qualified.
15901   bool MightBeOdrUse = true;
15902   if (E->performsVirtualDispatch(getLangOpts())) {
15903     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15904       if (Method->isPure())
15905         MightBeOdrUse = false;
15906   }
15907   SourceLocation Loc =
15908       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15909   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15910 }
15911 
15912 /// Perform marking for a reference to an arbitrary declaration.  It
15913 /// marks the declaration referenced, and performs odr-use checking for
15914 /// functions and variables. This method should not be used when building a
15915 /// normal expression which refers to a variable.
15916 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15917                                  bool MightBeOdrUse) {
15918   if (MightBeOdrUse) {
15919     if (auto *VD = dyn_cast<VarDecl>(D)) {
15920       MarkVariableReferenced(Loc, VD);
15921       return;
15922     }
15923   }
15924   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15925     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15926     return;
15927   }
15928   D->setReferenced();
15929 }
15930 
15931 namespace {
15932   // Mark all of the declarations used by a type as referenced.
15933   // FIXME: Not fully implemented yet! We need to have a better understanding
15934   // of when we're entering a context we should not recurse into.
15935   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15936   // TreeTransforms rebuilding the type in a new context. Rather than
15937   // duplicating the TreeTransform logic, we should consider reusing it here.
15938   // Currently that causes problems when rebuilding LambdaExprs.
15939   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15940     Sema &S;
15941     SourceLocation Loc;
15942 
15943   public:
15944     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15945 
15946     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15947 
15948     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15949   };
15950 }
15951 
15952 bool MarkReferencedDecls::TraverseTemplateArgument(
15953     const TemplateArgument &Arg) {
15954   {
15955     // A non-type template argument is a constant-evaluated context.
15956     EnterExpressionEvaluationContext Evaluated(
15957         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15958     if (Arg.getKind() == TemplateArgument::Declaration) {
15959       if (Decl *D = Arg.getAsDecl())
15960         S.MarkAnyDeclReferenced(Loc, D, true);
15961     } else if (Arg.getKind() == TemplateArgument::Expression) {
15962       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15963     }
15964   }
15965 
15966   return Inherited::TraverseTemplateArgument(Arg);
15967 }
15968 
15969 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15970   MarkReferencedDecls Marker(*this, Loc);
15971   Marker.TraverseType(T);
15972 }
15973 
15974 namespace {
15975   /// Helper class that marks all of the declarations referenced by
15976   /// potentially-evaluated subexpressions as "referenced".
15977   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15978     Sema &S;
15979     bool SkipLocalVariables;
15980 
15981   public:
15982     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15983 
15984     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15985       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15986 
15987     void VisitDeclRefExpr(DeclRefExpr *E) {
15988       // If we were asked not to visit local variables, don't.
15989       if (SkipLocalVariables) {
15990         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15991           if (VD->hasLocalStorage())
15992             return;
15993       }
15994 
15995       S.MarkDeclRefReferenced(E);
15996     }
15997 
15998     void VisitMemberExpr(MemberExpr *E) {
15999       S.MarkMemberReferenced(E);
16000       Inherited::VisitMemberExpr(E);
16001     }
16002 
16003     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16004       S.MarkFunctionReferenced(
16005           E->getBeginLoc(),
16006           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16007       Visit(E->getSubExpr());
16008     }
16009 
16010     void VisitCXXNewExpr(CXXNewExpr *E) {
16011       if (E->getOperatorNew())
16012         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16013       if (E->getOperatorDelete())
16014         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16015       Inherited::VisitCXXNewExpr(E);
16016     }
16017 
16018     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16019       if (E->getOperatorDelete())
16020         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16021       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16022       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16023         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16024         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16025       }
16026 
16027       Inherited::VisitCXXDeleteExpr(E);
16028     }
16029 
16030     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16031       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16032       Inherited::VisitCXXConstructExpr(E);
16033     }
16034 
16035     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16036       Visit(E->getExpr());
16037     }
16038 
16039     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
16040       Inherited::VisitImplicitCastExpr(E);
16041 
16042       if (E->getCastKind() == CK_LValueToRValue)
16043         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
16044     }
16045   };
16046 }
16047 
16048 /// Mark any declarations that appear within this expression or any
16049 /// potentially-evaluated subexpressions as "referenced".
16050 ///
16051 /// \param SkipLocalVariables If true, don't mark local variables as
16052 /// 'referenced'.
16053 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16054                                             bool SkipLocalVariables) {
16055   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16056 }
16057 
16058 /// Emit a diagnostic that describes an effect on the run-time behavior
16059 /// of the program being compiled.
16060 ///
16061 /// This routine emits the given diagnostic when the code currently being
16062 /// type-checked is "potentially evaluated", meaning that there is a
16063 /// possibility that the code will actually be executable. Code in sizeof()
16064 /// expressions, code used only during overload resolution, etc., are not
16065 /// potentially evaluated. This routine will suppress such diagnostics or,
16066 /// in the absolutely nutty case of potentially potentially evaluated
16067 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16068 /// later.
16069 ///
16070 /// This routine should be used for all diagnostics that describe the run-time
16071 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16072 /// Failure to do so will likely result in spurious diagnostics or failures
16073 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16074 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16075                                const PartialDiagnostic &PD) {
16076   switch (ExprEvalContexts.back().Context) {
16077   case ExpressionEvaluationContext::Unevaluated:
16078   case ExpressionEvaluationContext::UnevaluatedList:
16079   case ExpressionEvaluationContext::UnevaluatedAbstract:
16080   case ExpressionEvaluationContext::DiscardedStatement:
16081     // The argument will never be evaluated, so don't complain.
16082     break;
16083 
16084   case ExpressionEvaluationContext::ConstantEvaluated:
16085     // Relevant diagnostics should be produced by constant evaluation.
16086     break;
16087 
16088   case ExpressionEvaluationContext::PotentiallyEvaluated:
16089   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16090     if (Statement && getCurFunctionOrMethodDecl()) {
16091       FunctionScopes.back()->PossiblyUnreachableDiags.
16092         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
16093       return true;
16094     }
16095 
16096     // The initializer of a constexpr variable or of the first declaration of a
16097     // static data member is not syntactically a constant evaluated constant,
16098     // but nonetheless is always required to be a constant expression, so we
16099     // can skip diagnosing.
16100     // FIXME: Using the mangling context here is a hack.
16101     if (auto *VD = dyn_cast_or_null<VarDecl>(
16102             ExprEvalContexts.back().ManglingContextDecl)) {
16103       if (VD->isConstexpr() ||
16104           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16105         break;
16106       // FIXME: For any other kind of variable, we should build a CFG for its
16107       // initializer and check whether the context in question is reachable.
16108     }
16109 
16110     Diag(Loc, PD);
16111     return true;
16112   }
16113 
16114   return false;
16115 }
16116 
16117 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16118                                CallExpr *CE, FunctionDecl *FD) {
16119   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16120     return false;
16121 
16122   // If we're inside a decltype's expression, don't check for a valid return
16123   // type or construct temporaries until we know whether this is the last call.
16124   if (ExprEvalContexts.back().ExprContext ==
16125       ExpressionEvaluationContextRecord::EK_Decltype) {
16126     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16127     return false;
16128   }
16129 
16130   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16131     FunctionDecl *FD;
16132     CallExpr *CE;
16133 
16134   public:
16135     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16136       : FD(FD), CE(CE) { }
16137 
16138     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16139       if (!FD) {
16140         S.Diag(Loc, diag::err_call_incomplete_return)
16141           << T << CE->getSourceRange();
16142         return;
16143       }
16144 
16145       S.Diag(Loc, diag::err_call_function_incomplete_return)
16146         << CE->getSourceRange() << FD->getDeclName() << T;
16147       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16148           << FD->getDeclName();
16149     }
16150   } Diagnoser(FD, CE);
16151 
16152   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16153     return true;
16154 
16155   return false;
16156 }
16157 
16158 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16159 // will prevent this condition from triggering, which is what we want.
16160 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16161   SourceLocation Loc;
16162 
16163   unsigned diagnostic = diag::warn_condition_is_assignment;
16164   bool IsOrAssign = false;
16165 
16166   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16167     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16168       return;
16169 
16170     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16171 
16172     // Greylist some idioms by putting them into a warning subcategory.
16173     if (ObjCMessageExpr *ME
16174           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16175       Selector Sel = ME->getSelector();
16176 
16177       // self = [<foo> init...]
16178       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16179         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16180 
16181       // <foo> = [<bar> nextObject]
16182       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16183         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16184     }
16185 
16186     Loc = Op->getOperatorLoc();
16187   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16188     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16189       return;
16190 
16191     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16192     Loc = Op->getOperatorLoc();
16193   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16194     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16195   else {
16196     // Not an assignment.
16197     return;
16198   }
16199 
16200   Diag(Loc, diagnostic) << E->getSourceRange();
16201 
16202   SourceLocation Open = E->getBeginLoc();
16203   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16204   Diag(Loc, diag::note_condition_assign_silence)
16205         << FixItHint::CreateInsertion(Open, "(")
16206         << FixItHint::CreateInsertion(Close, ")");
16207 
16208   if (IsOrAssign)
16209     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16210       << FixItHint::CreateReplacement(Loc, "!=");
16211   else
16212     Diag(Loc, diag::note_condition_assign_to_comparison)
16213       << FixItHint::CreateReplacement(Loc, "==");
16214 }
16215 
16216 /// Redundant parentheses over an equality comparison can indicate
16217 /// that the user intended an assignment used as condition.
16218 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16219   // Don't warn if the parens came from a macro.
16220   SourceLocation parenLoc = ParenE->getBeginLoc();
16221   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16222     return;
16223   // Don't warn for dependent expressions.
16224   if (ParenE->isTypeDependent())
16225     return;
16226 
16227   Expr *E = ParenE->IgnoreParens();
16228 
16229   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16230     if (opE->getOpcode() == BO_EQ &&
16231         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16232                                                            == Expr::MLV_Valid) {
16233       SourceLocation Loc = opE->getOperatorLoc();
16234 
16235       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16236       SourceRange ParenERange = ParenE->getSourceRange();
16237       Diag(Loc, diag::note_equality_comparison_silence)
16238         << FixItHint::CreateRemoval(ParenERange.getBegin())
16239         << FixItHint::CreateRemoval(ParenERange.getEnd());
16240       Diag(Loc, diag::note_equality_comparison_to_assign)
16241         << FixItHint::CreateReplacement(Loc, "=");
16242     }
16243 }
16244 
16245 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16246                                        bool IsConstexpr) {
16247   DiagnoseAssignmentAsCondition(E);
16248   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16249     DiagnoseEqualityWithExtraParens(parenE);
16250 
16251   ExprResult result = CheckPlaceholderExpr(E);
16252   if (result.isInvalid()) return ExprError();
16253   E = result.get();
16254 
16255   if (!E->isTypeDependent()) {
16256     if (getLangOpts().CPlusPlus)
16257       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16258 
16259     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16260     if (ERes.isInvalid())
16261       return ExprError();
16262     E = ERes.get();
16263 
16264     QualType T = E->getType();
16265     if (!T->isScalarType()) { // C99 6.8.4.1p1
16266       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16267         << T << E->getSourceRange();
16268       return ExprError();
16269     }
16270     CheckBoolLikeConversion(E, Loc);
16271   }
16272 
16273   return E;
16274 }
16275 
16276 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16277                                            Expr *SubExpr, ConditionKind CK) {
16278   // Empty conditions are valid in for-statements.
16279   if (!SubExpr)
16280     return ConditionResult();
16281 
16282   ExprResult Cond;
16283   switch (CK) {
16284   case ConditionKind::Boolean:
16285     Cond = CheckBooleanCondition(Loc, SubExpr);
16286     break;
16287 
16288   case ConditionKind::ConstexprIf:
16289     Cond = CheckBooleanCondition(Loc, SubExpr, true);
16290     break;
16291 
16292   case ConditionKind::Switch:
16293     Cond = CheckSwitchCondition(Loc, SubExpr);
16294     break;
16295   }
16296   if (Cond.isInvalid())
16297     return ConditionError();
16298 
16299   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16300   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16301   if (!FullExpr.get())
16302     return ConditionError();
16303 
16304   return ConditionResult(*this, nullptr, FullExpr,
16305                          CK == ConditionKind::ConstexprIf);
16306 }
16307 
16308 namespace {
16309   /// A visitor for rebuilding a call to an __unknown_any expression
16310   /// to have an appropriate type.
16311   struct RebuildUnknownAnyFunction
16312     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16313 
16314     Sema &S;
16315 
16316     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16317 
16318     ExprResult VisitStmt(Stmt *S) {
16319       llvm_unreachable("unexpected statement!");
16320     }
16321 
16322     ExprResult VisitExpr(Expr *E) {
16323       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16324         << E->getSourceRange();
16325       return ExprError();
16326     }
16327 
16328     /// Rebuild an expression which simply semantically wraps another
16329     /// expression which it shares the type and value kind of.
16330     template <class T> ExprResult rebuildSugarExpr(T *E) {
16331       ExprResult SubResult = Visit(E->getSubExpr());
16332       if (SubResult.isInvalid()) return ExprError();
16333 
16334       Expr *SubExpr = SubResult.get();
16335       E->setSubExpr(SubExpr);
16336       E->setType(SubExpr->getType());
16337       E->setValueKind(SubExpr->getValueKind());
16338       assert(E->getObjectKind() == OK_Ordinary);
16339       return E;
16340     }
16341 
16342     ExprResult VisitParenExpr(ParenExpr *E) {
16343       return rebuildSugarExpr(E);
16344     }
16345 
16346     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16347       return rebuildSugarExpr(E);
16348     }
16349 
16350     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16351       ExprResult SubResult = Visit(E->getSubExpr());
16352       if (SubResult.isInvalid()) return ExprError();
16353 
16354       Expr *SubExpr = SubResult.get();
16355       E->setSubExpr(SubExpr);
16356       E->setType(S.Context.getPointerType(SubExpr->getType()));
16357       assert(E->getValueKind() == VK_RValue);
16358       assert(E->getObjectKind() == OK_Ordinary);
16359       return E;
16360     }
16361 
16362     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16363       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16364 
16365       E->setType(VD->getType());
16366 
16367       assert(E->getValueKind() == VK_RValue);
16368       if (S.getLangOpts().CPlusPlus &&
16369           !(isa<CXXMethodDecl>(VD) &&
16370             cast<CXXMethodDecl>(VD)->isInstance()))
16371         E->setValueKind(VK_LValue);
16372 
16373       return E;
16374     }
16375 
16376     ExprResult VisitMemberExpr(MemberExpr *E) {
16377       return resolveDecl(E, E->getMemberDecl());
16378     }
16379 
16380     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16381       return resolveDecl(E, E->getDecl());
16382     }
16383   };
16384 }
16385 
16386 /// Given a function expression of unknown-any type, try to rebuild it
16387 /// to have a function type.
16388 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16389   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16390   if (Result.isInvalid()) return ExprError();
16391   return S.DefaultFunctionArrayConversion(Result.get());
16392 }
16393 
16394 namespace {
16395   /// A visitor for rebuilding an expression of type __unknown_anytype
16396   /// into one which resolves the type directly on the referring
16397   /// expression.  Strict preservation of the original source
16398   /// structure is not a goal.
16399   struct RebuildUnknownAnyExpr
16400     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16401 
16402     Sema &S;
16403 
16404     /// The current destination type.
16405     QualType DestType;
16406 
16407     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16408       : S(S), DestType(CastType) {}
16409 
16410     ExprResult VisitStmt(Stmt *S) {
16411       llvm_unreachable("unexpected statement!");
16412     }
16413 
16414     ExprResult VisitExpr(Expr *E) {
16415       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16416         << E->getSourceRange();
16417       return ExprError();
16418     }
16419 
16420     ExprResult VisitCallExpr(CallExpr *E);
16421     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16422 
16423     /// Rebuild an expression which simply semantically wraps another
16424     /// expression which it shares the type and value kind of.
16425     template <class T> ExprResult rebuildSugarExpr(T *E) {
16426       ExprResult SubResult = Visit(E->getSubExpr());
16427       if (SubResult.isInvalid()) return ExprError();
16428       Expr *SubExpr = SubResult.get();
16429       E->setSubExpr(SubExpr);
16430       E->setType(SubExpr->getType());
16431       E->setValueKind(SubExpr->getValueKind());
16432       assert(E->getObjectKind() == OK_Ordinary);
16433       return E;
16434     }
16435 
16436     ExprResult VisitParenExpr(ParenExpr *E) {
16437       return rebuildSugarExpr(E);
16438     }
16439 
16440     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16441       return rebuildSugarExpr(E);
16442     }
16443 
16444     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16445       const PointerType *Ptr = DestType->getAs<PointerType>();
16446       if (!Ptr) {
16447         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16448           << E->getSourceRange();
16449         return ExprError();
16450       }
16451 
16452       if (isa<CallExpr>(E->getSubExpr())) {
16453         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16454           << E->getSourceRange();
16455         return ExprError();
16456       }
16457 
16458       assert(E->getValueKind() == VK_RValue);
16459       assert(E->getObjectKind() == OK_Ordinary);
16460       E->setType(DestType);
16461 
16462       // Build the sub-expression as if it were an object of the pointee type.
16463       DestType = Ptr->getPointeeType();
16464       ExprResult SubResult = Visit(E->getSubExpr());
16465       if (SubResult.isInvalid()) return ExprError();
16466       E->setSubExpr(SubResult.get());
16467       return E;
16468     }
16469 
16470     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16471 
16472     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16473 
16474     ExprResult VisitMemberExpr(MemberExpr *E) {
16475       return resolveDecl(E, E->getMemberDecl());
16476     }
16477 
16478     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16479       return resolveDecl(E, E->getDecl());
16480     }
16481   };
16482 }
16483 
16484 /// Rebuilds a call expression which yielded __unknown_anytype.
16485 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16486   Expr *CalleeExpr = E->getCallee();
16487 
16488   enum FnKind {
16489     FK_MemberFunction,
16490     FK_FunctionPointer,
16491     FK_BlockPointer
16492   };
16493 
16494   FnKind Kind;
16495   QualType CalleeType = CalleeExpr->getType();
16496   if (CalleeType == S.Context.BoundMemberTy) {
16497     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16498     Kind = FK_MemberFunction;
16499     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16500   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16501     CalleeType = Ptr->getPointeeType();
16502     Kind = FK_FunctionPointer;
16503   } else {
16504     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16505     Kind = FK_BlockPointer;
16506   }
16507   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16508 
16509   // Verify that this is a legal result type of a function.
16510   if (DestType->isArrayType() || DestType->isFunctionType()) {
16511     unsigned diagID = diag::err_func_returning_array_function;
16512     if (Kind == FK_BlockPointer)
16513       diagID = diag::err_block_returning_array_function;
16514 
16515     S.Diag(E->getExprLoc(), diagID)
16516       << DestType->isFunctionType() << DestType;
16517     return ExprError();
16518   }
16519 
16520   // Otherwise, go ahead and set DestType as the call's result.
16521   E->setType(DestType.getNonLValueExprType(S.Context));
16522   E->setValueKind(Expr::getValueKindForType(DestType));
16523   assert(E->getObjectKind() == OK_Ordinary);
16524 
16525   // Rebuild the function type, replacing the result type with DestType.
16526   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16527   if (Proto) {
16528     // __unknown_anytype(...) is a special case used by the debugger when
16529     // it has no idea what a function's signature is.
16530     //
16531     // We want to build this call essentially under the K&R
16532     // unprototyped rules, but making a FunctionNoProtoType in C++
16533     // would foul up all sorts of assumptions.  However, we cannot
16534     // simply pass all arguments as variadic arguments, nor can we
16535     // portably just call the function under a non-variadic type; see
16536     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16537     // However, it turns out that in practice it is generally safe to
16538     // call a function declared as "A foo(B,C,D);" under the prototype
16539     // "A foo(B,C,D,...);".  The only known exception is with the
16540     // Windows ABI, where any variadic function is implicitly cdecl
16541     // regardless of its normal CC.  Therefore we change the parameter
16542     // types to match the types of the arguments.
16543     //
16544     // This is a hack, but it is far superior to moving the
16545     // corresponding target-specific code from IR-gen to Sema/AST.
16546 
16547     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16548     SmallVector<QualType, 8> ArgTypes;
16549     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16550       ArgTypes.reserve(E->getNumArgs());
16551       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16552         Expr *Arg = E->getArg(i);
16553         QualType ArgType = Arg->getType();
16554         if (E->isLValue()) {
16555           ArgType = S.Context.getLValueReferenceType(ArgType);
16556         } else if (E->isXValue()) {
16557           ArgType = S.Context.getRValueReferenceType(ArgType);
16558         }
16559         ArgTypes.push_back(ArgType);
16560       }
16561       ParamTypes = ArgTypes;
16562     }
16563     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16564                                          Proto->getExtProtoInfo());
16565   } else {
16566     DestType = S.Context.getFunctionNoProtoType(DestType,
16567                                                 FnType->getExtInfo());
16568   }
16569 
16570   // Rebuild the appropriate pointer-to-function type.
16571   switch (Kind) {
16572   case FK_MemberFunction:
16573     // Nothing to do.
16574     break;
16575 
16576   case FK_FunctionPointer:
16577     DestType = S.Context.getPointerType(DestType);
16578     break;
16579 
16580   case FK_BlockPointer:
16581     DestType = S.Context.getBlockPointerType(DestType);
16582     break;
16583   }
16584 
16585   // Finally, we can recurse.
16586   ExprResult CalleeResult = Visit(CalleeExpr);
16587   if (!CalleeResult.isUsable()) return ExprError();
16588   E->setCallee(CalleeResult.get());
16589 
16590   // Bind a temporary if necessary.
16591   return S.MaybeBindToTemporary(E);
16592 }
16593 
16594 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16595   // Verify that this is a legal result type of a call.
16596   if (DestType->isArrayType() || DestType->isFunctionType()) {
16597     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16598       << DestType->isFunctionType() << DestType;
16599     return ExprError();
16600   }
16601 
16602   // Rewrite the method result type if available.
16603   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16604     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16605     Method->setReturnType(DestType);
16606   }
16607 
16608   // Change the type of the message.
16609   E->setType(DestType.getNonReferenceType());
16610   E->setValueKind(Expr::getValueKindForType(DestType));
16611 
16612   return S.MaybeBindToTemporary(E);
16613 }
16614 
16615 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16616   // The only case we should ever see here is a function-to-pointer decay.
16617   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16618     assert(E->getValueKind() == VK_RValue);
16619     assert(E->getObjectKind() == OK_Ordinary);
16620 
16621     E->setType(DestType);
16622 
16623     // Rebuild the sub-expression as the pointee (function) type.
16624     DestType = DestType->castAs<PointerType>()->getPointeeType();
16625 
16626     ExprResult Result = Visit(E->getSubExpr());
16627     if (!Result.isUsable()) return ExprError();
16628 
16629     E->setSubExpr(Result.get());
16630     return E;
16631   } else if (E->getCastKind() == CK_LValueToRValue) {
16632     assert(E->getValueKind() == VK_RValue);
16633     assert(E->getObjectKind() == OK_Ordinary);
16634 
16635     assert(isa<BlockPointerType>(E->getType()));
16636 
16637     E->setType(DestType);
16638 
16639     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16640     DestType = S.Context.getLValueReferenceType(DestType);
16641 
16642     ExprResult Result = Visit(E->getSubExpr());
16643     if (!Result.isUsable()) return ExprError();
16644 
16645     E->setSubExpr(Result.get());
16646     return E;
16647   } else {
16648     llvm_unreachable("Unhandled cast type!");
16649   }
16650 }
16651 
16652 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16653   ExprValueKind ValueKind = VK_LValue;
16654   QualType Type = DestType;
16655 
16656   // We know how to make this work for certain kinds of decls:
16657 
16658   //  - functions
16659   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16660     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16661       DestType = Ptr->getPointeeType();
16662       ExprResult Result = resolveDecl(E, VD);
16663       if (Result.isInvalid()) return ExprError();
16664       return S.ImpCastExprToType(Result.get(), Type,
16665                                  CK_FunctionToPointerDecay, VK_RValue);
16666     }
16667 
16668     if (!Type->isFunctionType()) {
16669       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16670         << VD << E->getSourceRange();
16671       return ExprError();
16672     }
16673     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16674       // We must match the FunctionDecl's type to the hack introduced in
16675       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16676       // type. See the lengthy commentary in that routine.
16677       QualType FDT = FD->getType();
16678       const FunctionType *FnType = FDT->castAs<FunctionType>();
16679       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16680       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16681       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16682         SourceLocation Loc = FD->getLocation();
16683         FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
16684                                       FD->getDeclContext(),
16685                                       Loc, Loc, FD->getNameInfo().getName(),
16686                                       DestType, FD->getTypeSourceInfo(),
16687                                       SC_None, false/*isInlineSpecified*/,
16688                                       FD->hasPrototype(),
16689                                       false/*isConstexprSpecified*/);
16690 
16691         if (FD->getQualifier())
16692           NewFD->setQualifierInfo(FD->getQualifierLoc());
16693 
16694         SmallVector<ParmVarDecl*, 16> Params;
16695         for (const auto &AI : FT->param_types()) {
16696           ParmVarDecl *Param =
16697             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16698           Param->setScopeInfo(0, Params.size());
16699           Params.push_back(Param);
16700         }
16701         NewFD->setParams(Params);
16702         DRE->setDecl(NewFD);
16703         VD = DRE->getDecl();
16704       }
16705     }
16706 
16707     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16708       if (MD->isInstance()) {
16709         ValueKind = VK_RValue;
16710         Type = S.Context.BoundMemberTy;
16711       }
16712 
16713     // Function references aren't l-values in C.
16714     if (!S.getLangOpts().CPlusPlus)
16715       ValueKind = VK_RValue;
16716 
16717   //  - variables
16718   } else if (isa<VarDecl>(VD)) {
16719     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16720       Type = RefTy->getPointeeType();
16721     } else if (Type->isFunctionType()) {
16722       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16723         << VD << E->getSourceRange();
16724       return ExprError();
16725     }
16726 
16727   //  - nothing else
16728   } else {
16729     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16730       << VD << E->getSourceRange();
16731     return ExprError();
16732   }
16733 
16734   // Modifying the declaration like this is friendly to IR-gen but
16735   // also really dangerous.
16736   VD->setType(DestType);
16737   E->setType(Type);
16738   E->setValueKind(ValueKind);
16739   return E;
16740 }
16741 
16742 /// Check a cast of an unknown-any type.  We intentionally only
16743 /// trigger this for C-style casts.
16744 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16745                                      Expr *CastExpr, CastKind &CastKind,
16746                                      ExprValueKind &VK, CXXCastPath &Path) {
16747   // The type we're casting to must be either void or complete.
16748   if (!CastType->isVoidType() &&
16749       RequireCompleteType(TypeRange.getBegin(), CastType,
16750                           diag::err_typecheck_cast_to_incomplete))
16751     return ExprError();
16752 
16753   // Rewrite the casted expression from scratch.
16754   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16755   if (!result.isUsable()) return ExprError();
16756 
16757   CastExpr = result.get();
16758   VK = CastExpr->getValueKind();
16759   CastKind = CK_NoOp;
16760 
16761   return CastExpr;
16762 }
16763 
16764 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16765   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16766 }
16767 
16768 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16769                                     Expr *arg, QualType &paramType) {
16770   // If the syntactic form of the argument is not an explicit cast of
16771   // any sort, just do default argument promotion.
16772   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16773   if (!castArg) {
16774     ExprResult result = DefaultArgumentPromotion(arg);
16775     if (result.isInvalid()) return ExprError();
16776     paramType = result.get()->getType();
16777     return result;
16778   }
16779 
16780   // Otherwise, use the type that was written in the explicit cast.
16781   assert(!arg->hasPlaceholderType());
16782   paramType = castArg->getTypeAsWritten();
16783 
16784   // Copy-initialize a parameter of that type.
16785   InitializedEntity entity =
16786     InitializedEntity::InitializeParameter(Context, paramType,
16787                                            /*consumed*/ false);
16788   return PerformCopyInitialization(entity, callLoc, arg);
16789 }
16790 
16791 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16792   Expr *orig = E;
16793   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16794   while (true) {
16795     E = E->IgnoreParenImpCasts();
16796     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16797       E = call->getCallee();
16798       diagID = diag::err_uncasted_call_of_unknown_any;
16799     } else {
16800       break;
16801     }
16802   }
16803 
16804   SourceLocation loc;
16805   NamedDecl *d;
16806   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16807     loc = ref->getLocation();
16808     d = ref->getDecl();
16809   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16810     loc = mem->getMemberLoc();
16811     d = mem->getMemberDecl();
16812   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16813     diagID = diag::err_uncasted_call_of_unknown_any;
16814     loc = msg->getSelectorStartLoc();
16815     d = msg->getMethodDecl();
16816     if (!d) {
16817       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16818         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16819         << orig->getSourceRange();
16820       return ExprError();
16821     }
16822   } else {
16823     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16824       << E->getSourceRange();
16825     return ExprError();
16826   }
16827 
16828   S.Diag(loc, diagID) << d << orig->getSourceRange();
16829 
16830   // Never recoverable.
16831   return ExprError();
16832 }
16833 
16834 /// Check for operands with placeholder types and complain if found.
16835 /// Returns ExprError() if there was an error and no recovery was possible.
16836 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16837   if (!getLangOpts().CPlusPlus) {
16838     // C cannot handle TypoExpr nodes on either side of a binop because it
16839     // doesn't handle dependent types properly, so make sure any TypoExprs have
16840     // been dealt with before checking the operands.
16841     ExprResult Result = CorrectDelayedTyposInExpr(E);
16842     if (!Result.isUsable()) return ExprError();
16843     E = Result.get();
16844   }
16845 
16846   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16847   if (!placeholderType) return E;
16848 
16849   switch (placeholderType->getKind()) {
16850 
16851   // Overloaded expressions.
16852   case BuiltinType::Overload: {
16853     // Try to resolve a single function template specialization.
16854     // This is obligatory.
16855     ExprResult Result = E;
16856     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16857       return Result;
16858 
16859     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16860     // leaves Result unchanged on failure.
16861     Result = E;
16862     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16863       return Result;
16864 
16865     // If that failed, try to recover with a call.
16866     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16867                          /*complain*/ true);
16868     return Result;
16869   }
16870 
16871   // Bound member functions.
16872   case BuiltinType::BoundMember: {
16873     ExprResult result = E;
16874     const Expr *BME = E->IgnoreParens();
16875     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16876     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16877     if (isa<CXXPseudoDestructorExpr>(BME)) {
16878       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16879     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16880       if (ME->getMemberNameInfo().getName().getNameKind() ==
16881           DeclarationName::CXXDestructorName)
16882         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16883     }
16884     tryToRecoverWithCall(result, PD,
16885                          /*complain*/ true);
16886     return result;
16887   }
16888 
16889   // ARC unbridged casts.
16890   case BuiltinType::ARCUnbridgedCast: {
16891     Expr *realCast = stripARCUnbridgedCast(E);
16892     diagnoseARCUnbridgedCast(realCast);
16893     return realCast;
16894   }
16895 
16896   // Expressions of unknown type.
16897   case BuiltinType::UnknownAny:
16898     return diagnoseUnknownAnyExpr(*this, E);
16899 
16900   // Pseudo-objects.
16901   case BuiltinType::PseudoObject:
16902     return checkPseudoObjectRValue(E);
16903 
16904   case BuiltinType::BuiltinFn: {
16905     // Accept __noop without parens by implicitly converting it to a call expr.
16906     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16907     if (DRE) {
16908       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16909       if (FD->getBuiltinID() == Builtin::BI__noop) {
16910         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16911                               CK_BuiltinFnToFnPtr)
16912                 .get();
16913         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16914                                 VK_RValue, SourceLocation());
16915       }
16916     }
16917 
16918     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16919     return ExprError();
16920   }
16921 
16922   // Expressions of unknown type.
16923   case BuiltinType::OMPArraySection:
16924     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16925     return ExprError();
16926 
16927   // Everything else should be impossible.
16928 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16929   case BuiltinType::Id:
16930 #include "clang/Basic/OpenCLImageTypes.def"
16931 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16932   case BuiltinType::Id:
16933 #include "clang/Basic/OpenCLExtensionTypes.def"
16934 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16935 #define PLACEHOLDER_TYPE(Id, SingletonId)
16936 #include "clang/AST/BuiltinTypes.def"
16937     break;
16938   }
16939 
16940   llvm_unreachable("invalid placeholder type!");
16941 }
16942 
16943 bool Sema::CheckCaseExpression(Expr *E) {
16944   if (E->isTypeDependent())
16945     return true;
16946   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16947     return E->getType()->isIntegralOrEnumerationType();
16948   return false;
16949 }
16950 
16951 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16952 ExprResult
16953 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16954   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16955          "Unknown Objective-C Boolean value!");
16956   QualType BoolT = Context.ObjCBuiltinBoolTy;
16957   if (!Context.getBOOLDecl()) {
16958     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16959                         Sema::LookupOrdinaryName);
16960     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16961       NamedDecl *ND = Result.getFoundDecl();
16962       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16963         Context.setBOOLDecl(TD);
16964     }
16965   }
16966   if (Context.getBOOLDecl())
16967     BoolT = Context.getBOOLType();
16968   return new (Context)
16969       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16970 }
16971 
16972 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16973     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16974     SourceLocation RParen) {
16975 
16976   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16977 
16978   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
16979     return Spec.getPlatform() == Platform;
16980   });
16981 
16982   VersionTuple Version;
16983   if (Spec != AvailSpecs.end())
16984     Version = Spec->getVersion();
16985 
16986   // The use of `@available` in the enclosing function should be analyzed to
16987   // warn when it's used inappropriately (i.e. not if(@available)).
16988   if (getCurFunctionOrMethodDecl())
16989     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16990   else if (getCurBlock() || getCurLambda())
16991     getCurFunction()->HasPotentialAvailabilityViolations = true;
16992 
16993   return new (Context)
16994       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16995 }
16996