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 = BuildCallExpr(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   QualType StrTy =
1687       Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1688 
1689   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1690   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1691                                              Kind, Literal.Pascal, StrTy,
1692                                              &StringTokLocs[0],
1693                                              StringTokLocs.size());
1694   if (Literal.getUDSuffix().empty())
1695     return Lit;
1696 
1697   // We're building a user-defined literal.
1698   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1699   SourceLocation UDSuffixLoc =
1700     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1701                    Literal.getUDSuffixOffset());
1702 
1703   // Make sure we're allowed user-defined literals here.
1704   if (!UDLScope)
1705     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1706 
1707   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1708   //   operator "" X (str, len)
1709   QualType SizeType = Context.getSizeType();
1710 
1711   DeclarationName OpName =
1712     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1713   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1714   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1715 
1716   QualType ArgTy[] = {
1717     Context.getArrayDecayedType(StrTy), SizeType
1718   };
1719 
1720   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1721   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1722                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1723                                 /*AllowStringTemplate*/ true,
1724                                 /*DiagnoseMissing*/ true)) {
1725 
1726   case LOLR_Cooked: {
1727     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1728     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1729                                                     StringTokLocs[0]);
1730     Expr *Args[] = { Lit, LenArg };
1731 
1732     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1733   }
1734 
1735   case LOLR_StringTemplate: {
1736     TemplateArgumentListInfo ExplicitArgs;
1737 
1738     unsigned CharBits = Context.getIntWidth(CharTy);
1739     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1740     llvm::APSInt Value(CharBits, CharIsUnsigned);
1741 
1742     TemplateArgument TypeArg(CharTy);
1743     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1744     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1745 
1746     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1747       Value = Lit->getCodeUnit(I);
1748       TemplateArgument Arg(Context, Value, CharTy);
1749       TemplateArgumentLocInfo ArgInfo;
1750       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1751     }
1752     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1753                                     &ExplicitArgs);
1754   }
1755   case LOLR_Raw:
1756   case LOLR_Template:
1757   case LOLR_ErrorNoDiagnostic:
1758     llvm_unreachable("unexpected literal operator lookup result");
1759   case LOLR_Error:
1760     return ExprError();
1761   }
1762   llvm_unreachable("unexpected literal operator lookup result");
1763 }
1764 
1765 ExprResult
1766 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1767                        SourceLocation Loc,
1768                        const CXXScopeSpec *SS) {
1769   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1770   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1771 }
1772 
1773 /// BuildDeclRefExpr - Build an expression that references a
1774 /// declaration that does not require a closure capture.
1775 ExprResult
1776 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1777                        const DeclarationNameInfo &NameInfo,
1778                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1779                        const TemplateArgumentListInfo *TemplateArgs) {
1780   bool RefersToCapturedVariable =
1781       isa<VarDecl>(D) &&
1782       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1783 
1784   DeclRefExpr *E;
1785   if (isa<VarTemplateSpecializationDecl>(D)) {
1786     VarTemplateSpecializationDecl *VarSpec =
1787         cast<VarTemplateSpecializationDecl>(D);
1788 
1789     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1790                                         : NestedNameSpecifierLoc(),
1791                             VarSpec->getTemplateKeywordLoc(), D,
1792                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1793                             FoundD, TemplateArgs);
1794   } else {
1795     assert(!TemplateArgs && "No template arguments for non-variable"
1796                             " template specialization references");
1797     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1798                                         : NestedNameSpecifierLoc(),
1799                             SourceLocation(), D, RefersToCapturedVariable,
1800                             NameInfo, Ty, VK, FoundD);
1801   }
1802 
1803   MarkDeclRefReferenced(E);
1804 
1805   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1806       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1807       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1808     getCurFunction()->recordUseOfWeak(E);
1809 
1810   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1811   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1812     FD = IFD->getAnonField();
1813   if (FD) {
1814     UnusedPrivateFields.remove(FD);
1815     // Just in case we're building an illegal pointer-to-member.
1816     if (FD->isBitField())
1817       E->setObjectKind(OK_BitField);
1818   }
1819 
1820   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1821   // designates a bit-field.
1822   if (auto *BD = dyn_cast<BindingDecl>(D))
1823     if (auto *BE = BD->getBinding())
1824       E->setObjectKind(BE->getObjectKind());
1825 
1826   return E;
1827 }
1828 
1829 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1830 /// possibly a list of template arguments.
1831 ///
1832 /// If this produces template arguments, it is permitted to call
1833 /// DecomposeTemplateName.
1834 ///
1835 /// This actually loses a lot of source location information for
1836 /// non-standard name kinds; we should consider preserving that in
1837 /// some way.
1838 void
1839 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1840                              TemplateArgumentListInfo &Buffer,
1841                              DeclarationNameInfo &NameInfo,
1842                              const TemplateArgumentListInfo *&TemplateArgs) {
1843   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1844     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1845     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1846 
1847     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1848                                        Id.TemplateId->NumArgs);
1849     translateTemplateArguments(TemplateArgsPtr, Buffer);
1850 
1851     TemplateName TName = Id.TemplateId->Template.get();
1852     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1853     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1854     TemplateArgs = &Buffer;
1855   } else {
1856     NameInfo = GetNameFromUnqualifiedId(Id);
1857     TemplateArgs = nullptr;
1858   }
1859 }
1860 
1861 static void emitEmptyLookupTypoDiagnostic(
1862     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1863     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1864     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1865   DeclContext *Ctx =
1866       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1867   if (!TC) {
1868     // Emit a special diagnostic for failed member lookups.
1869     // FIXME: computing the declaration context might fail here (?)
1870     if (Ctx)
1871       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1872                                                  << SS.getRange();
1873     else
1874       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1875     return;
1876   }
1877 
1878   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1879   bool DroppedSpecifier =
1880       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1881   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1882                         ? diag::note_implicit_param_decl
1883                         : diag::note_previous_decl;
1884   if (!Ctx)
1885     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1886                          SemaRef.PDiag(NoteID));
1887   else
1888     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1889                                  << Typo << Ctx << DroppedSpecifier
1890                                  << SS.getRange(),
1891                          SemaRef.PDiag(NoteID));
1892 }
1893 
1894 /// Diagnose an empty lookup.
1895 ///
1896 /// \return false if new lookup candidates were found
1897 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1898                                CorrectionCandidateCallback &CCC,
1899                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1900                                ArrayRef<Expr *> Args, TypoExpr **Out) {
1901   DeclarationName Name = R.getLookupName();
1902 
1903   unsigned diagnostic = diag::err_undeclared_var_use;
1904   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1905   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1906       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1907       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1908     diagnostic = diag::err_undeclared_use;
1909     diagnostic_suggest = diag::err_undeclared_use_suggest;
1910   }
1911 
1912   // If the original lookup was an unqualified lookup, fake an
1913   // unqualified lookup.  This is useful when (for example) the
1914   // original lookup would not have found something because it was a
1915   // dependent name.
1916   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1917   while (DC) {
1918     if (isa<CXXRecordDecl>(DC)) {
1919       LookupQualifiedName(R, DC);
1920 
1921       if (!R.empty()) {
1922         // Don't give errors about ambiguities in this lookup.
1923         R.suppressDiagnostics();
1924 
1925         // During a default argument instantiation the CurContext points
1926         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1927         // function parameter list, hence add an explicit check.
1928         bool isDefaultArgument =
1929             !CodeSynthesisContexts.empty() &&
1930             CodeSynthesisContexts.back().Kind ==
1931                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1932         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1933         bool isInstance = CurMethod &&
1934                           CurMethod->isInstance() &&
1935                           DC == CurMethod->getParent() && !isDefaultArgument;
1936 
1937         // Give a code modification hint to insert 'this->'.
1938         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1939         // Actually quite difficult!
1940         if (getLangOpts().MSVCCompat)
1941           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1942         if (isInstance) {
1943           Diag(R.getNameLoc(), diagnostic) << Name
1944             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1945           CheckCXXThisCapture(R.getNameLoc());
1946         } else {
1947           Diag(R.getNameLoc(), diagnostic) << Name;
1948         }
1949 
1950         // Do we really want to note all of these?
1951         for (NamedDecl *D : R)
1952           Diag(D->getLocation(), diag::note_dependent_var_use);
1953 
1954         // Return true if we are inside a default argument instantiation
1955         // and the found name refers to an instance member function, otherwise
1956         // the function calling DiagnoseEmptyLookup will try to create an
1957         // implicit member call and this is wrong for default argument.
1958         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1959           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1960           return true;
1961         }
1962 
1963         // Tell the callee to try to recover.
1964         return false;
1965       }
1966 
1967       R.clear();
1968     }
1969 
1970     // In Microsoft mode, if we are performing lookup from within a friend
1971     // function definition declared at class scope then we must set
1972     // DC to the lexical parent to be able to search into the parent
1973     // class.
1974     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1975         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1976         DC->getLexicalParent()->isRecord())
1977       DC = DC->getLexicalParent();
1978     else
1979       DC = DC->getParent();
1980   }
1981 
1982   // We didn't find anything, so try to correct for a typo.
1983   TypoCorrection Corrected;
1984   if (S && Out) {
1985     SourceLocation TypoLoc = R.getNameLoc();
1986     assert(!ExplicitTemplateArgs &&
1987            "Diagnosing an empty lookup with explicit template args!");
1988     *Out = CorrectTypoDelayed(
1989         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
1990         [=](const TypoCorrection &TC) {
1991           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1992                                         diagnostic, diagnostic_suggest);
1993         },
1994         nullptr, CTK_ErrorRecovery);
1995     if (*Out)
1996       return true;
1997   } else if (S &&
1998              (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1999                                       S, &SS, CCC, CTK_ErrorRecovery))) {
2000     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2001     bool DroppedSpecifier =
2002         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2003     R.setLookupName(Corrected.getCorrection());
2004 
2005     bool AcceptableWithRecovery = false;
2006     bool AcceptableWithoutRecovery = false;
2007     NamedDecl *ND = Corrected.getFoundDecl();
2008     if (ND) {
2009       if (Corrected.isOverloaded()) {
2010         OverloadCandidateSet OCS(R.getNameLoc(),
2011                                  OverloadCandidateSet::CSK_Normal);
2012         OverloadCandidateSet::iterator Best;
2013         for (NamedDecl *CD : Corrected) {
2014           if (FunctionTemplateDecl *FTD =
2015                    dyn_cast<FunctionTemplateDecl>(CD))
2016             AddTemplateOverloadCandidate(
2017                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2018                 Args, OCS);
2019           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2020             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2021               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2022                                    Args, OCS);
2023         }
2024         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2025         case OR_Success:
2026           ND = Best->FoundDecl;
2027           Corrected.setCorrectionDecl(ND);
2028           break;
2029         default:
2030           // FIXME: Arbitrarily pick the first declaration for the note.
2031           Corrected.setCorrectionDecl(ND);
2032           break;
2033         }
2034       }
2035       R.addDecl(ND);
2036       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2037         CXXRecordDecl *Record = nullptr;
2038         if (Corrected.getCorrectionSpecifier()) {
2039           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2040           Record = Ty->getAsCXXRecordDecl();
2041         }
2042         if (!Record)
2043           Record = cast<CXXRecordDecl>(
2044               ND->getDeclContext()->getRedeclContext());
2045         R.setNamingClass(Record);
2046       }
2047 
2048       auto *UnderlyingND = ND->getUnderlyingDecl();
2049       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2050                                isa<FunctionTemplateDecl>(UnderlyingND);
2051       // FIXME: If we ended up with a typo for a type name or
2052       // Objective-C class name, we're in trouble because the parser
2053       // is in the wrong place to recover. Suggest the typo
2054       // correction, but don't make it a fix-it since we're not going
2055       // to recover well anyway.
2056       AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2057                                   getAsTypeTemplateDecl(UnderlyingND) ||
2058                                   isa<ObjCInterfaceDecl>(UnderlyingND);
2059     } else {
2060       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2061       // because we aren't able to recover.
2062       AcceptableWithoutRecovery = true;
2063     }
2064 
2065     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2066       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2067                             ? diag::note_implicit_param_decl
2068                             : diag::note_previous_decl;
2069       if (SS.isEmpty())
2070         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2071                      PDiag(NoteID), AcceptableWithRecovery);
2072       else
2073         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2074                                   << Name << computeDeclContext(SS, false)
2075                                   << DroppedSpecifier << SS.getRange(),
2076                      PDiag(NoteID), AcceptableWithRecovery);
2077 
2078       // Tell the callee whether to try to recover.
2079       return !AcceptableWithRecovery;
2080     }
2081   }
2082   R.clear();
2083 
2084   // Emit a special diagnostic for failed member lookups.
2085   // FIXME: computing the declaration context might fail here (?)
2086   if (!SS.isEmpty()) {
2087     Diag(R.getNameLoc(), diag::err_no_member)
2088       << Name << computeDeclContext(SS, false)
2089       << SS.getRange();
2090     return true;
2091   }
2092 
2093   // Give up, we can't recover.
2094   Diag(R.getNameLoc(), diagnostic) << Name;
2095   return true;
2096 }
2097 
2098 /// In Microsoft mode, if we are inside a template class whose parent class has
2099 /// dependent base classes, and we can't resolve an unqualified identifier, then
2100 /// assume the identifier is a member of a dependent base class.  We can only
2101 /// recover successfully in static methods, instance methods, and other contexts
2102 /// where 'this' is available.  This doesn't precisely match MSVC's
2103 /// instantiation model, but it's close enough.
2104 static Expr *
2105 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2106                                DeclarationNameInfo &NameInfo,
2107                                SourceLocation TemplateKWLoc,
2108                                const TemplateArgumentListInfo *TemplateArgs) {
2109   // Only try to recover from lookup into dependent bases in static methods or
2110   // contexts where 'this' is available.
2111   QualType ThisType = S.getCurrentThisType();
2112   const CXXRecordDecl *RD = nullptr;
2113   if (!ThisType.isNull())
2114     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2115   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2116     RD = MD->getParent();
2117   if (!RD || !RD->hasAnyDependentBases())
2118     return nullptr;
2119 
2120   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2121   // is available, suggest inserting 'this->' as a fixit.
2122   SourceLocation Loc = NameInfo.getLoc();
2123   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2124   DB << NameInfo.getName() << RD;
2125 
2126   if (!ThisType.isNull()) {
2127     DB << FixItHint::CreateInsertion(Loc, "this->");
2128     return CXXDependentScopeMemberExpr::Create(
2129         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2130         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2131         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2132   }
2133 
2134   // Synthesize a fake NNS that points to the derived class.  This will
2135   // perform name lookup during template instantiation.
2136   CXXScopeSpec SS;
2137   auto *NNS =
2138       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2139   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2140   return DependentScopeDeclRefExpr::Create(
2141       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2142       TemplateArgs);
2143 }
2144 
2145 ExprResult
2146 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2147                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2148                         bool HasTrailingLParen, bool IsAddressOfOperand,
2149                         CorrectionCandidateCallback *CCC,
2150                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2151   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2152          "cannot be direct & operand and have a trailing lparen");
2153   if (SS.isInvalid())
2154     return ExprError();
2155 
2156   TemplateArgumentListInfo TemplateArgsBuffer;
2157 
2158   // Decompose the UnqualifiedId into the following data.
2159   DeclarationNameInfo NameInfo;
2160   const TemplateArgumentListInfo *TemplateArgs;
2161   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2162 
2163   DeclarationName Name = NameInfo.getName();
2164   IdentifierInfo *II = Name.getAsIdentifierInfo();
2165   SourceLocation NameLoc = NameInfo.getLoc();
2166 
2167   if (II && II->isEditorPlaceholder()) {
2168     // FIXME: When typed placeholders are supported we can create a typed
2169     // placeholder expression node.
2170     return ExprError();
2171   }
2172 
2173   // C++ [temp.dep.expr]p3:
2174   //   An id-expression is type-dependent if it contains:
2175   //     -- an identifier that was declared with a dependent type,
2176   //        (note: handled after lookup)
2177   //     -- a template-id that is dependent,
2178   //        (note: handled in BuildTemplateIdExpr)
2179   //     -- a conversion-function-id that specifies a dependent type,
2180   //     -- a nested-name-specifier that contains a class-name that
2181   //        names a dependent type.
2182   // Determine whether this is a member of an unknown specialization;
2183   // we need to handle these differently.
2184   bool DependentID = false;
2185   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2186       Name.getCXXNameType()->isDependentType()) {
2187     DependentID = true;
2188   } else if (SS.isSet()) {
2189     if (DeclContext *DC = computeDeclContext(SS, false)) {
2190       if (RequireCompleteDeclContext(SS, DC))
2191         return ExprError();
2192     } else {
2193       DependentID = true;
2194     }
2195   }
2196 
2197   if (DependentID)
2198     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2199                                       IsAddressOfOperand, TemplateArgs);
2200 
2201   // Perform the required lookup.
2202   LookupResult R(*this, NameInfo,
2203                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2204                      ? LookupObjCImplicitSelfParam
2205                      : LookupOrdinaryName);
2206   if (TemplateKWLoc.isValid() || TemplateArgs) {
2207     // Lookup the template name again to correctly establish the context in
2208     // which it was found. This is really unfortunate as we already did the
2209     // lookup to determine that it was a template name in the first place. If
2210     // this becomes a performance hit, we can work harder to preserve those
2211     // results until we get here but it's likely not worth it.
2212     bool MemberOfUnknownSpecialization;
2213     AssumedTemplateKind AssumedTemplate;
2214     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2215                            MemberOfUnknownSpecialization, TemplateKWLoc,
2216                            &AssumedTemplate))
2217       return ExprError();
2218 
2219     if (MemberOfUnknownSpecialization ||
2220         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2221       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2222                                         IsAddressOfOperand, TemplateArgs);
2223   } else {
2224     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2225     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2226 
2227     // If the result might be in a dependent base class, this is a dependent
2228     // id-expression.
2229     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2230       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2231                                         IsAddressOfOperand, TemplateArgs);
2232 
2233     // If this reference is in an Objective-C method, then we need to do
2234     // some special Objective-C lookup, too.
2235     if (IvarLookupFollowUp) {
2236       ExprResult E(LookupInObjCMethod(R, S, II, true));
2237       if (E.isInvalid())
2238         return ExprError();
2239 
2240       if (Expr *Ex = E.getAs<Expr>())
2241         return Ex;
2242     }
2243   }
2244 
2245   if (R.isAmbiguous())
2246     return ExprError();
2247 
2248   // This could be an implicitly declared function reference (legal in C90,
2249   // extension in C99, forbidden in C++).
2250   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2251     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2252     if (D) R.addDecl(D);
2253   }
2254 
2255   // Determine whether this name might be a candidate for
2256   // argument-dependent lookup.
2257   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2258 
2259   if (R.empty() && !ADL) {
2260     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2261       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2262                                                    TemplateKWLoc, TemplateArgs))
2263         return E;
2264     }
2265 
2266     // Don't diagnose an empty lookup for inline assembly.
2267     if (IsInlineAsmIdentifier)
2268       return ExprError();
2269 
2270     // If this name wasn't predeclared and if this is not a function
2271     // call, diagnose the problem.
2272     TypoExpr *TE = nullptr;
2273     DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2274                                                        : nullptr);
2275     DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2276     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2277            "Typo correction callback misconfigured");
2278     if (CCC) {
2279       // Make sure the callback knows what the typo being diagnosed is.
2280       CCC->setTypoName(II);
2281       if (SS.isValid())
2282         CCC->setTypoNNS(SS.getScopeRep());
2283     }
2284     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2285     // a template name, but we happen to have always already looked up the name
2286     // before we get here if it must be a template name.
2287     if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2288                             None, &TE)) {
2289       if (TE && KeywordReplacement) {
2290         auto &State = getTypoExprState(TE);
2291         auto BestTC = State.Consumer->getNextCorrection();
2292         if (BestTC.isKeyword()) {
2293           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2294           if (State.DiagHandler)
2295             State.DiagHandler(BestTC);
2296           KeywordReplacement->startToken();
2297           KeywordReplacement->setKind(II->getTokenID());
2298           KeywordReplacement->setIdentifierInfo(II);
2299           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2300           // Clean up the state associated with the TypoExpr, since it has
2301           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2302           clearDelayedTypo(TE);
2303           // Signal that a correction to a keyword was performed by returning a
2304           // valid-but-null ExprResult.
2305           return (Expr*)nullptr;
2306         }
2307         State.Consumer->resetCorrectionStream();
2308       }
2309       return TE ? TE : ExprError();
2310     }
2311 
2312     assert(!R.empty() &&
2313            "DiagnoseEmptyLookup returned false but added no results");
2314 
2315     // If we found an Objective-C instance variable, let
2316     // LookupInObjCMethod build the appropriate expression to
2317     // reference the ivar.
2318     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2319       R.clear();
2320       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2321       // In a hopelessly buggy code, Objective-C instance variable
2322       // lookup fails and no expression will be built to reference it.
2323       if (!E.isInvalid() && !E.get())
2324         return ExprError();
2325       return E;
2326     }
2327   }
2328 
2329   // This is guaranteed from this point on.
2330   assert(!R.empty() || ADL);
2331 
2332   // Check whether this might be a C++ implicit instance member access.
2333   // C++ [class.mfct.non-static]p3:
2334   //   When an id-expression that is not part of a class member access
2335   //   syntax and not used to form a pointer to member is used in the
2336   //   body of a non-static member function of class X, if name lookup
2337   //   resolves the name in the id-expression to a non-static non-type
2338   //   member of some class C, the id-expression is transformed into a
2339   //   class member access expression using (*this) as the
2340   //   postfix-expression to the left of the . operator.
2341   //
2342   // But we don't actually need to do this for '&' operands if R
2343   // resolved to a function or overloaded function set, because the
2344   // expression is ill-formed if it actually works out to be a
2345   // non-static member function:
2346   //
2347   // C++ [expr.ref]p4:
2348   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2349   //   [t]he expression can be used only as the left-hand operand of a
2350   //   member function call.
2351   //
2352   // There are other safeguards against such uses, but it's important
2353   // to get this right here so that we don't end up making a
2354   // spuriously dependent expression if we're inside a dependent
2355   // instance method.
2356   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2357     bool MightBeImplicitMember;
2358     if (!IsAddressOfOperand)
2359       MightBeImplicitMember = true;
2360     else if (!SS.isEmpty())
2361       MightBeImplicitMember = false;
2362     else if (R.isOverloadedResult())
2363       MightBeImplicitMember = false;
2364     else if (R.isUnresolvableResult())
2365       MightBeImplicitMember = true;
2366     else
2367       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2368                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2369                               isa<MSPropertyDecl>(R.getFoundDecl());
2370 
2371     if (MightBeImplicitMember)
2372       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2373                                              R, TemplateArgs, S);
2374   }
2375 
2376   if (TemplateArgs || TemplateKWLoc.isValid()) {
2377 
2378     // In C++1y, if this is a variable template id, then check it
2379     // in BuildTemplateIdExpr().
2380     // The single lookup result must be a variable template declaration.
2381     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2382         Id.TemplateId->Kind == TNK_Var_template) {
2383       assert(R.getAsSingle<VarTemplateDecl>() &&
2384              "There should only be one declaration found.");
2385     }
2386 
2387     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2388   }
2389 
2390   return BuildDeclarationNameExpr(SS, R, ADL);
2391 }
2392 
2393 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2394 /// declaration name, generally during template instantiation.
2395 /// There's a large number of things which don't need to be done along
2396 /// this path.
2397 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2398     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2399     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2400   DeclContext *DC = computeDeclContext(SS, false);
2401   if (!DC)
2402     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2403                                      NameInfo, /*TemplateArgs=*/nullptr);
2404 
2405   if (RequireCompleteDeclContext(SS, DC))
2406     return ExprError();
2407 
2408   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2409   LookupQualifiedName(R, DC);
2410 
2411   if (R.isAmbiguous())
2412     return ExprError();
2413 
2414   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2415     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2416                                      NameInfo, /*TemplateArgs=*/nullptr);
2417 
2418   if (R.empty()) {
2419     Diag(NameInfo.getLoc(), diag::err_no_member)
2420       << NameInfo.getName() << DC << SS.getRange();
2421     return ExprError();
2422   }
2423 
2424   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2425     // Diagnose a missing typename if this resolved unambiguously to a type in
2426     // a dependent context.  If we can recover with a type, downgrade this to
2427     // a warning in Microsoft compatibility mode.
2428     unsigned DiagID = diag::err_typename_missing;
2429     if (RecoveryTSI && getLangOpts().MSVCCompat)
2430       DiagID = diag::ext_typename_missing;
2431     SourceLocation Loc = SS.getBeginLoc();
2432     auto D = Diag(Loc, DiagID);
2433     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2434       << SourceRange(Loc, NameInfo.getEndLoc());
2435 
2436     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2437     // context.
2438     if (!RecoveryTSI)
2439       return ExprError();
2440 
2441     // Only issue the fixit if we're prepared to recover.
2442     D << FixItHint::CreateInsertion(Loc, "typename ");
2443 
2444     // Recover by pretending this was an elaborated type.
2445     QualType Ty = Context.getTypeDeclType(TD);
2446     TypeLocBuilder TLB;
2447     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2448 
2449     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2450     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2451     QTL.setElaboratedKeywordLoc(SourceLocation());
2452     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2453 
2454     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2455 
2456     return ExprEmpty();
2457   }
2458 
2459   // Defend against this resolving to an implicit member access. We usually
2460   // won't get here if this might be a legitimate a class member (we end up in
2461   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2462   // a pointer-to-member or in an unevaluated context in C++11.
2463   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2464     return BuildPossibleImplicitMemberExpr(SS,
2465                                            /*TemplateKWLoc=*/SourceLocation(),
2466                                            R, /*TemplateArgs=*/nullptr, S);
2467 
2468   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2469 }
2470 
2471 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2472 /// detected that we're currently inside an ObjC method.  Perform some
2473 /// additional lookup.
2474 ///
2475 /// Ideally, most of this would be done by lookup, but there's
2476 /// actually quite a lot of extra work involved.
2477 ///
2478 /// Returns a null sentinel to indicate trivial success.
2479 ExprResult
2480 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2481                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2482   SourceLocation Loc = Lookup.getNameLoc();
2483   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2484 
2485   // Check for error condition which is already reported.
2486   if (!CurMethod)
2487     return ExprError();
2488 
2489   // There are two cases to handle here.  1) scoped lookup could have failed,
2490   // in which case we should look for an ivar.  2) scoped lookup could have
2491   // found a decl, but that decl is outside the current instance method (i.e.
2492   // a global variable).  In these two cases, we do a lookup for an ivar with
2493   // this name, if the lookup sucedes, we replace it our current decl.
2494 
2495   // If we're in a class method, we don't normally want to look for
2496   // ivars.  But if we don't find anything else, and there's an
2497   // ivar, that's an error.
2498   bool IsClassMethod = CurMethod->isClassMethod();
2499 
2500   bool LookForIvars;
2501   if (Lookup.empty())
2502     LookForIvars = true;
2503   else if (IsClassMethod)
2504     LookForIvars = false;
2505   else
2506     LookForIvars = (Lookup.isSingleResult() &&
2507                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2508   ObjCInterfaceDecl *IFace = nullptr;
2509   if (LookForIvars) {
2510     IFace = CurMethod->getClassInterface();
2511     ObjCInterfaceDecl *ClassDeclared;
2512     ObjCIvarDecl *IV = nullptr;
2513     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2514       // Diagnose using an ivar in a class method.
2515       if (IsClassMethod)
2516         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2517                          << IV->getDeclName());
2518 
2519       // If we're referencing an invalid decl, just return this as a silent
2520       // error node.  The error diagnostic was already emitted on the decl.
2521       if (IV->isInvalidDecl())
2522         return ExprError();
2523 
2524       // Check if referencing a field with __attribute__((deprecated)).
2525       if (DiagnoseUseOfDecl(IV, Loc))
2526         return ExprError();
2527 
2528       // Diagnose the use of an ivar outside of the declaring class.
2529       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2530           !declaresSameEntity(ClassDeclared, IFace) &&
2531           !getLangOpts().DebuggerSupport)
2532         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2533 
2534       // FIXME: This should use a new expr for a direct reference, don't
2535       // turn this into Self->ivar, just return a BareIVarExpr or something.
2536       IdentifierInfo &II = Context.Idents.get("self");
2537       UnqualifiedId SelfName;
2538       SelfName.setIdentifier(&II, SourceLocation());
2539       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2540       CXXScopeSpec SelfScopeSpec;
2541       SourceLocation TemplateKWLoc;
2542       ExprResult SelfExpr =
2543           ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2544                             /*HasTrailingLParen=*/false,
2545                             /*IsAddressOfOperand=*/false);
2546       if (SelfExpr.isInvalid())
2547         return ExprError();
2548 
2549       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2550       if (SelfExpr.isInvalid())
2551         return ExprError();
2552 
2553       MarkAnyDeclReferenced(Loc, IV, true);
2554 
2555       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2556       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2557           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2558         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2559 
2560       ObjCIvarRefExpr *Result = new (Context)
2561           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2562                           IV->getLocation(), SelfExpr.get(), true, true);
2563 
2564       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2565         if (!isUnevaluatedContext() &&
2566             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2567           getCurFunction()->recordUseOfWeak(Result);
2568       }
2569       if (getLangOpts().ObjCAutoRefCount)
2570         if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2571           ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2572 
2573       return Result;
2574     }
2575   } else if (CurMethod->isInstanceMethod()) {
2576     // We should warn if a local variable hides an ivar.
2577     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2578       ObjCInterfaceDecl *ClassDeclared;
2579       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2580         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2581             declaresSameEntity(IFace, ClassDeclared))
2582           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2583       }
2584     }
2585   } else if (Lookup.isSingleResult() &&
2586              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2587     // If accessing a stand-alone ivar in a class method, this is an error.
2588     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2589       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2590                        << IV->getDeclName());
2591   }
2592 
2593   if (Lookup.empty() && II && AllowBuiltinCreation) {
2594     // FIXME. Consolidate this with similar code in LookupName.
2595     if (unsigned BuiltinID = II->getBuiltinID()) {
2596       if (!(getLangOpts().CPlusPlus &&
2597             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2598         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2599                                            S, Lookup.isForRedeclaration(),
2600                                            Lookup.getNameLoc());
2601         if (D) Lookup.addDecl(D);
2602       }
2603     }
2604   }
2605   // Sentinel value saying that we didn't do anything special.
2606   return ExprResult((Expr *)nullptr);
2607 }
2608 
2609 /// Cast a base object to a member's actual type.
2610 ///
2611 /// Logically this happens in three phases:
2612 ///
2613 /// * First we cast from the base type to the naming class.
2614 ///   The naming class is the class into which we were looking
2615 ///   when we found the member;  it's the qualifier type if a
2616 ///   qualifier was provided, and otherwise it's the base type.
2617 ///
2618 /// * Next we cast from the naming class to the declaring class.
2619 ///   If the member we found was brought into a class's scope by
2620 ///   a using declaration, this is that class;  otherwise it's
2621 ///   the class declaring the member.
2622 ///
2623 /// * Finally we cast from the declaring class to the "true"
2624 ///   declaring class of the member.  This conversion does not
2625 ///   obey access control.
2626 ExprResult
2627 Sema::PerformObjectMemberConversion(Expr *From,
2628                                     NestedNameSpecifier *Qualifier,
2629                                     NamedDecl *FoundDecl,
2630                                     NamedDecl *Member) {
2631   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2632   if (!RD)
2633     return From;
2634 
2635   QualType DestRecordType;
2636   QualType DestType;
2637   QualType FromRecordType;
2638   QualType FromType = From->getType();
2639   bool PointerConversions = false;
2640   if (isa<FieldDecl>(Member)) {
2641     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2642     auto FromPtrType = FromType->getAs<PointerType>();
2643     DestRecordType = Context.getAddrSpaceQualType(
2644         DestRecordType, FromPtrType
2645                             ? FromType->getPointeeType().getAddressSpace()
2646                             : FromType.getAddressSpace());
2647 
2648     if (FromPtrType) {
2649       DestType = Context.getPointerType(DestRecordType);
2650       FromRecordType = FromPtrType->getPointeeType();
2651       PointerConversions = true;
2652     } else {
2653       DestType = DestRecordType;
2654       FromRecordType = FromType;
2655     }
2656   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2657     if (Method->isStatic())
2658       return From;
2659 
2660     DestType = Method->getThisType();
2661     DestRecordType = DestType->getPointeeType();
2662 
2663     if (FromType->getAs<PointerType>()) {
2664       FromRecordType = FromType->getPointeeType();
2665       PointerConversions = true;
2666     } else {
2667       FromRecordType = FromType;
2668       DestType = DestRecordType;
2669     }
2670   } else {
2671     // No conversion necessary.
2672     return From;
2673   }
2674 
2675   if (DestType->isDependentType() || FromType->isDependentType())
2676     return From;
2677 
2678   // If the unqualified types are the same, no conversion is necessary.
2679   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2680     return From;
2681 
2682   SourceRange FromRange = From->getSourceRange();
2683   SourceLocation FromLoc = FromRange.getBegin();
2684 
2685   ExprValueKind VK = From->getValueKind();
2686 
2687   // C++ [class.member.lookup]p8:
2688   //   [...] Ambiguities can often be resolved by qualifying a name with its
2689   //   class name.
2690   //
2691   // If the member was a qualified name and the qualified referred to a
2692   // specific base subobject type, we'll cast to that intermediate type
2693   // first and then to the object in which the member is declared. That allows
2694   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2695   //
2696   //   class Base { public: int x; };
2697   //   class Derived1 : public Base { };
2698   //   class Derived2 : public Base { };
2699   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2700   //
2701   //   void VeryDerived::f() {
2702   //     x = 17; // error: ambiguous base subobjects
2703   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2704   //   }
2705   if (Qualifier && Qualifier->getAsType()) {
2706     QualType QType = QualType(Qualifier->getAsType(), 0);
2707     assert(QType->isRecordType() && "lookup done with non-record type");
2708 
2709     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2710 
2711     // In C++98, the qualifier type doesn't actually have to be a base
2712     // type of the object type, in which case we just ignore it.
2713     // Otherwise build the appropriate casts.
2714     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2715       CXXCastPath BasePath;
2716       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2717                                        FromLoc, FromRange, &BasePath))
2718         return ExprError();
2719 
2720       if (PointerConversions)
2721         QType = Context.getPointerType(QType);
2722       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2723                                VK, &BasePath).get();
2724 
2725       FromType = QType;
2726       FromRecordType = QRecordType;
2727 
2728       // If the qualifier type was the same as the destination type,
2729       // we're done.
2730       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2731         return From;
2732     }
2733   }
2734 
2735   bool IgnoreAccess = false;
2736 
2737   // If we actually found the member through a using declaration, cast
2738   // down to the using declaration's type.
2739   //
2740   // Pointer equality is fine here because only one declaration of a
2741   // class ever has member declarations.
2742   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2743     assert(isa<UsingShadowDecl>(FoundDecl));
2744     QualType URecordType = Context.getTypeDeclType(
2745                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2746 
2747     // We only need to do this if the naming-class to declaring-class
2748     // conversion is non-trivial.
2749     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2750       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2751       CXXCastPath BasePath;
2752       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2753                                        FromLoc, FromRange, &BasePath))
2754         return ExprError();
2755 
2756       QualType UType = URecordType;
2757       if (PointerConversions)
2758         UType = Context.getPointerType(UType);
2759       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2760                                VK, &BasePath).get();
2761       FromType = UType;
2762       FromRecordType = URecordType;
2763     }
2764 
2765     // We don't do access control for the conversion from the
2766     // declaring class to the true declaring class.
2767     IgnoreAccess = true;
2768   }
2769 
2770   CXXCastPath BasePath;
2771   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2772                                    FromLoc, FromRange, &BasePath,
2773                                    IgnoreAccess))
2774     return ExprError();
2775 
2776   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2777                            VK, &BasePath);
2778 }
2779 
2780 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2781                                       const LookupResult &R,
2782                                       bool HasTrailingLParen) {
2783   // Only when used directly as the postfix-expression of a call.
2784   if (!HasTrailingLParen)
2785     return false;
2786 
2787   // Never if a scope specifier was provided.
2788   if (SS.isSet())
2789     return false;
2790 
2791   // Only in C++ or ObjC++.
2792   if (!getLangOpts().CPlusPlus)
2793     return false;
2794 
2795   // Turn off ADL when we find certain kinds of declarations during
2796   // normal lookup:
2797   for (NamedDecl *D : R) {
2798     // C++0x [basic.lookup.argdep]p3:
2799     //     -- a declaration of a class member
2800     // Since using decls preserve this property, we check this on the
2801     // original decl.
2802     if (D->isCXXClassMember())
2803       return false;
2804 
2805     // C++0x [basic.lookup.argdep]p3:
2806     //     -- a block-scope function declaration that is not a
2807     //        using-declaration
2808     // NOTE: we also trigger this for function templates (in fact, we
2809     // don't check the decl type at all, since all other decl types
2810     // turn off ADL anyway).
2811     if (isa<UsingShadowDecl>(D))
2812       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2813     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2814       return false;
2815 
2816     // C++0x [basic.lookup.argdep]p3:
2817     //     -- a declaration that is neither a function or a function
2818     //        template
2819     // And also for builtin functions.
2820     if (isa<FunctionDecl>(D)) {
2821       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2822 
2823       // But also builtin functions.
2824       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2825         return false;
2826     } else if (!isa<FunctionTemplateDecl>(D))
2827       return false;
2828   }
2829 
2830   return true;
2831 }
2832 
2833 
2834 /// Diagnoses obvious problems with the use of the given declaration
2835 /// as an expression.  This is only actually called for lookups that
2836 /// were not overloaded, and it doesn't promise that the declaration
2837 /// will in fact be used.
2838 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2839   if (D->isInvalidDecl())
2840     return true;
2841 
2842   if (isa<TypedefNameDecl>(D)) {
2843     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2844     return true;
2845   }
2846 
2847   if (isa<ObjCInterfaceDecl>(D)) {
2848     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2849     return true;
2850   }
2851 
2852   if (isa<NamespaceDecl>(D)) {
2853     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2854     return true;
2855   }
2856 
2857   return false;
2858 }
2859 
2860 // Certain multiversion types should be treated as overloaded even when there is
2861 // only one result.
2862 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2863   assert(R.isSingleResult() && "Expected only a single result");
2864   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2865   return FD &&
2866          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2867 }
2868 
2869 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2870                                           LookupResult &R, bool NeedsADL,
2871                                           bool AcceptInvalidDecl) {
2872   // If this is a single, fully-resolved result and we don't need ADL,
2873   // just build an ordinary singleton decl ref.
2874   if (!NeedsADL && R.isSingleResult() &&
2875       !R.getAsSingle<FunctionTemplateDecl>() &&
2876       !ShouldLookupResultBeMultiVersionOverload(R))
2877     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2878                                     R.getRepresentativeDecl(), nullptr,
2879                                     AcceptInvalidDecl);
2880 
2881   // We only need to check the declaration if there's exactly one
2882   // result, because in the overloaded case the results can only be
2883   // functions and function templates.
2884   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2885       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2886     return ExprError();
2887 
2888   // Otherwise, just build an unresolved lookup expression.  Suppress
2889   // any lookup-related diagnostics; we'll hash these out later, when
2890   // we've picked a target.
2891   R.suppressDiagnostics();
2892 
2893   UnresolvedLookupExpr *ULE
2894     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2895                                    SS.getWithLocInContext(Context),
2896                                    R.getLookupNameInfo(),
2897                                    NeedsADL, R.isOverloadedResult(),
2898                                    R.begin(), R.end());
2899 
2900   return ULE;
2901 }
2902 
2903 static void
2904 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2905                                    ValueDecl *var, DeclContext *DC);
2906 
2907 /// Complete semantic analysis for a reference to the given declaration.
2908 ExprResult Sema::BuildDeclarationNameExpr(
2909     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2910     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2911     bool AcceptInvalidDecl) {
2912   assert(D && "Cannot refer to a NULL declaration");
2913   assert(!isa<FunctionTemplateDecl>(D) &&
2914          "Cannot refer unambiguously to a function template");
2915 
2916   SourceLocation Loc = NameInfo.getLoc();
2917   if (CheckDeclInExpr(*this, Loc, D))
2918     return ExprError();
2919 
2920   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2921     // Specifically diagnose references to class templates that are missing
2922     // a template argument list.
2923     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2924     return ExprError();
2925   }
2926 
2927   // Make sure that we're referring to a value.
2928   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2929   if (!VD) {
2930     Diag(Loc, diag::err_ref_non_value)
2931       << D << SS.getRange();
2932     Diag(D->getLocation(), diag::note_declared_at);
2933     return ExprError();
2934   }
2935 
2936   // Check whether this declaration can be used. Note that we suppress
2937   // this check when we're going to perform argument-dependent lookup
2938   // on this function name, because this might not be the function
2939   // that overload resolution actually selects.
2940   if (DiagnoseUseOfDecl(VD, Loc))
2941     return ExprError();
2942 
2943   // Only create DeclRefExpr's for valid Decl's.
2944   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2945     return ExprError();
2946 
2947   // Handle members of anonymous structs and unions.  If we got here,
2948   // and the reference is to a class member indirect field, then this
2949   // must be the subject of a pointer-to-member expression.
2950   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2951     if (!indirectField->isCXXClassMember())
2952       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2953                                                       indirectField);
2954 
2955   {
2956     QualType type = VD->getType();
2957     if (type.isNull())
2958       return ExprError();
2959     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2960       // C++ [except.spec]p17:
2961       //   An exception-specification is considered to be needed when:
2962       //   - in an expression, the function is the unique lookup result or
2963       //     the selected member of a set of overloaded functions.
2964       ResolveExceptionSpec(Loc, FPT);
2965       type = VD->getType();
2966     }
2967     ExprValueKind valueKind = VK_RValue;
2968 
2969     switch (D->getKind()) {
2970     // Ignore all the non-ValueDecl kinds.
2971 #define ABSTRACT_DECL(kind)
2972 #define VALUE(type, base)
2973 #define DECL(type, base) \
2974     case Decl::type:
2975 #include "clang/AST/DeclNodes.inc"
2976       llvm_unreachable("invalid value decl kind");
2977 
2978     // These shouldn't make it here.
2979     case Decl::ObjCAtDefsField:
2980       llvm_unreachable("forming non-member reference to ivar?");
2981 
2982     // Enum constants are always r-values and never references.
2983     // Unresolved using declarations are dependent.
2984     case Decl::EnumConstant:
2985     case Decl::UnresolvedUsingValue:
2986     case Decl::OMPDeclareReduction:
2987     case Decl::OMPDeclareMapper:
2988       valueKind = VK_RValue;
2989       break;
2990 
2991     // Fields and indirect fields that got here must be for
2992     // pointer-to-member expressions; we just call them l-values for
2993     // internal consistency, because this subexpression doesn't really
2994     // exist in the high-level semantics.
2995     case Decl::Field:
2996     case Decl::IndirectField:
2997     case Decl::ObjCIvar:
2998       assert(getLangOpts().CPlusPlus &&
2999              "building reference to field in C?");
3000 
3001       // These can't have reference type in well-formed programs, but
3002       // for internal consistency we do this anyway.
3003       type = type.getNonReferenceType();
3004       valueKind = VK_LValue;
3005       break;
3006 
3007     // Non-type template parameters are either l-values or r-values
3008     // depending on the type.
3009     case Decl::NonTypeTemplateParm: {
3010       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3011         type = reftype->getPointeeType();
3012         valueKind = VK_LValue; // even if the parameter is an r-value reference
3013         break;
3014       }
3015 
3016       // For non-references, we need to strip qualifiers just in case
3017       // the template parameter was declared as 'const int' or whatever.
3018       valueKind = VK_RValue;
3019       type = type.getUnqualifiedType();
3020       break;
3021     }
3022 
3023     case Decl::Var:
3024     case Decl::VarTemplateSpecialization:
3025     case Decl::VarTemplatePartialSpecialization:
3026     case Decl::Decomposition:
3027     case Decl::OMPCapturedExpr:
3028       // In C, "extern void blah;" is valid and is an r-value.
3029       if (!getLangOpts().CPlusPlus &&
3030           !type.hasQualifiers() &&
3031           type->isVoidType()) {
3032         valueKind = VK_RValue;
3033         break;
3034       }
3035       LLVM_FALLTHROUGH;
3036 
3037     case Decl::ImplicitParam:
3038     case Decl::ParmVar: {
3039       // These are always l-values.
3040       valueKind = VK_LValue;
3041       type = type.getNonReferenceType();
3042 
3043       // FIXME: Does the addition of const really only apply in
3044       // potentially-evaluated contexts? Since the variable isn't actually
3045       // captured in an unevaluated context, it seems that the answer is no.
3046       if (!isUnevaluatedContext()) {
3047         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3048         if (!CapturedType.isNull())
3049           type = CapturedType;
3050       }
3051 
3052       break;
3053     }
3054 
3055     case Decl::Binding: {
3056       // These are always lvalues.
3057       valueKind = VK_LValue;
3058       type = type.getNonReferenceType();
3059       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3060       // decides how that's supposed to work.
3061       auto *BD = cast<BindingDecl>(VD);
3062       if (BD->getDeclContext()->isFunctionOrMethod() &&
3063           BD->getDeclContext() != CurContext)
3064         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3065       break;
3066     }
3067 
3068     case Decl::Function: {
3069       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3070         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3071           type = Context.BuiltinFnTy;
3072           valueKind = VK_RValue;
3073           break;
3074         }
3075       }
3076 
3077       const FunctionType *fty = type->castAs<FunctionType>();
3078 
3079       // If we're referring to a function with an __unknown_anytype
3080       // result type, make the entire expression __unknown_anytype.
3081       if (fty->getReturnType() == Context.UnknownAnyTy) {
3082         type = Context.UnknownAnyTy;
3083         valueKind = VK_RValue;
3084         break;
3085       }
3086 
3087       // Functions are l-values in C++.
3088       if (getLangOpts().CPlusPlus) {
3089         valueKind = VK_LValue;
3090         break;
3091       }
3092 
3093       // C99 DR 316 says that, if a function type comes from a
3094       // function definition (without a prototype), that type is only
3095       // used for checking compatibility. Therefore, when referencing
3096       // the function, we pretend that we don't have the full function
3097       // type.
3098       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3099           isa<FunctionProtoType>(fty))
3100         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3101                                               fty->getExtInfo());
3102 
3103       // Functions are r-values in C.
3104       valueKind = VK_RValue;
3105       break;
3106     }
3107 
3108     case Decl::CXXDeductionGuide:
3109       llvm_unreachable("building reference to deduction guide");
3110 
3111     case Decl::MSProperty:
3112       valueKind = VK_LValue;
3113       break;
3114 
3115     case Decl::CXXMethod:
3116       // If we're referring to a method with an __unknown_anytype
3117       // result type, make the entire expression __unknown_anytype.
3118       // This should only be possible with a type written directly.
3119       if (const FunctionProtoType *proto
3120             = dyn_cast<FunctionProtoType>(VD->getType()))
3121         if (proto->getReturnType() == Context.UnknownAnyTy) {
3122           type = Context.UnknownAnyTy;
3123           valueKind = VK_RValue;
3124           break;
3125         }
3126 
3127       // C++ methods are l-values if static, r-values if non-static.
3128       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3129         valueKind = VK_LValue;
3130         break;
3131       }
3132       LLVM_FALLTHROUGH;
3133 
3134     case Decl::CXXConversion:
3135     case Decl::CXXDestructor:
3136     case Decl::CXXConstructor:
3137       valueKind = VK_RValue;
3138       break;
3139     }
3140 
3141     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3142                             TemplateArgs);
3143   }
3144 }
3145 
3146 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3147                                     SmallString<32> &Target) {
3148   Target.resize(CharByteWidth * (Source.size() + 1));
3149   char *ResultPtr = &Target[0];
3150   const llvm::UTF8 *ErrorPtr;
3151   bool success =
3152       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3153   (void)success;
3154   assert(success);
3155   Target.resize(ResultPtr - &Target[0]);
3156 }
3157 
3158 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3159                                      PredefinedExpr::IdentKind IK) {
3160   // Pick the current block, lambda, captured statement or function.
3161   Decl *currentDecl = nullptr;
3162   if (const BlockScopeInfo *BSI = getCurBlock())
3163     currentDecl = BSI->TheDecl;
3164   else if (const LambdaScopeInfo *LSI = getCurLambda())
3165     currentDecl = LSI->CallOperator;
3166   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3167     currentDecl = CSI->TheCapturedDecl;
3168   else
3169     currentDecl = getCurFunctionOrMethodDecl();
3170 
3171   if (!currentDecl) {
3172     Diag(Loc, diag::ext_predef_outside_function);
3173     currentDecl = Context.getTranslationUnitDecl();
3174   }
3175 
3176   QualType ResTy;
3177   StringLiteral *SL = nullptr;
3178   if (cast<DeclContext>(currentDecl)->isDependentContext())
3179     ResTy = Context.DependentTy;
3180   else {
3181     // Pre-defined identifiers are of type char[x], where x is the length of
3182     // the string.
3183     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3184     unsigned Length = Str.length();
3185 
3186     llvm::APInt LengthI(32, Length + 1);
3187     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3188       ResTy =
3189           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3190       SmallString<32> RawChars;
3191       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3192                               Str, RawChars);
3193       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3194                                            /*IndexTypeQuals*/ 0);
3195       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3196                                  /*Pascal*/ false, ResTy, Loc);
3197     } else {
3198       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3199       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3200                                            /*IndexTypeQuals*/ 0);
3201       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3202                                  /*Pascal*/ false, ResTy, Loc);
3203     }
3204   }
3205 
3206   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3207 }
3208 
3209 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3210   PredefinedExpr::IdentKind IK;
3211 
3212   switch (Kind) {
3213   default: llvm_unreachable("Unknown simple primary expr!");
3214   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3215   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3216   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3217   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3218   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3219   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3220   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3221   }
3222 
3223   return BuildPredefinedExpr(Loc, IK);
3224 }
3225 
3226 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3227   SmallString<16> CharBuffer;
3228   bool Invalid = false;
3229   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3230   if (Invalid)
3231     return ExprError();
3232 
3233   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3234                             PP, Tok.getKind());
3235   if (Literal.hadError())
3236     return ExprError();
3237 
3238   QualType Ty;
3239   if (Literal.isWide())
3240     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3241   else if (Literal.isUTF8() && getLangOpts().Char8)
3242     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3243   else if (Literal.isUTF16())
3244     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3245   else if (Literal.isUTF32())
3246     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3247   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3248     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3249   else
3250     Ty = Context.CharTy;  // 'x' -> char in C++
3251 
3252   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3253   if (Literal.isWide())
3254     Kind = CharacterLiteral::Wide;
3255   else if (Literal.isUTF16())
3256     Kind = CharacterLiteral::UTF16;
3257   else if (Literal.isUTF32())
3258     Kind = CharacterLiteral::UTF32;
3259   else if (Literal.isUTF8())
3260     Kind = CharacterLiteral::UTF8;
3261 
3262   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3263                                              Tok.getLocation());
3264 
3265   if (Literal.getUDSuffix().empty())
3266     return Lit;
3267 
3268   // We're building a user-defined literal.
3269   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3270   SourceLocation UDSuffixLoc =
3271     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3272 
3273   // Make sure we're allowed user-defined literals here.
3274   if (!UDLScope)
3275     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3276 
3277   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3278   //   operator "" X (ch)
3279   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3280                                         Lit, Tok.getLocation());
3281 }
3282 
3283 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3284   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3285   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3286                                 Context.IntTy, Loc);
3287 }
3288 
3289 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3290                                   QualType Ty, SourceLocation Loc) {
3291   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3292 
3293   using llvm::APFloat;
3294   APFloat Val(Format);
3295 
3296   APFloat::opStatus result = Literal.GetFloatValue(Val);
3297 
3298   // Overflow is always an error, but underflow is only an error if
3299   // we underflowed to zero (APFloat reports denormals as underflow).
3300   if ((result & APFloat::opOverflow) ||
3301       ((result & APFloat::opUnderflow) && Val.isZero())) {
3302     unsigned diagnostic;
3303     SmallString<20> buffer;
3304     if (result & APFloat::opOverflow) {
3305       diagnostic = diag::warn_float_overflow;
3306       APFloat::getLargest(Format).toString(buffer);
3307     } else {
3308       diagnostic = diag::warn_float_underflow;
3309       APFloat::getSmallest(Format).toString(buffer);
3310     }
3311 
3312     S.Diag(Loc, diagnostic)
3313       << Ty
3314       << StringRef(buffer.data(), buffer.size());
3315   }
3316 
3317   bool isExact = (result == APFloat::opOK);
3318   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3319 }
3320 
3321 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3322   assert(E && "Invalid expression");
3323 
3324   if (E->isValueDependent())
3325     return false;
3326 
3327   QualType QT = E->getType();
3328   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3329     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3330     return true;
3331   }
3332 
3333   llvm::APSInt ValueAPS;
3334   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3335 
3336   if (R.isInvalid())
3337     return true;
3338 
3339   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3340   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3341     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3342         << ValueAPS.toString(10) << ValueIsPositive;
3343     return true;
3344   }
3345 
3346   return false;
3347 }
3348 
3349 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3350   // Fast path for a single digit (which is quite common).  A single digit
3351   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3352   if (Tok.getLength() == 1) {
3353     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3354     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3355   }
3356 
3357   SmallString<128> SpellingBuffer;
3358   // NumericLiteralParser wants to overread by one character.  Add padding to
3359   // the buffer in case the token is copied to the buffer.  If getSpelling()
3360   // returns a StringRef to the memory buffer, it should have a null char at
3361   // the EOF, so it is also safe.
3362   SpellingBuffer.resize(Tok.getLength() + 1);
3363 
3364   // Get the spelling of the token, which eliminates trigraphs, etc.
3365   bool Invalid = false;
3366   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3367   if (Invalid)
3368     return ExprError();
3369 
3370   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3371   if (Literal.hadError)
3372     return ExprError();
3373 
3374   if (Literal.hasUDSuffix()) {
3375     // We're building a user-defined literal.
3376     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3377     SourceLocation UDSuffixLoc =
3378       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3379 
3380     // Make sure we're allowed user-defined literals here.
3381     if (!UDLScope)
3382       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3383 
3384     QualType CookedTy;
3385     if (Literal.isFloatingLiteral()) {
3386       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3387       // long double, the literal is treated as a call of the form
3388       //   operator "" X (f L)
3389       CookedTy = Context.LongDoubleTy;
3390     } else {
3391       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3392       // unsigned long long, the literal is treated as a call of the form
3393       //   operator "" X (n ULL)
3394       CookedTy = Context.UnsignedLongLongTy;
3395     }
3396 
3397     DeclarationName OpName =
3398       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3399     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3400     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3401 
3402     SourceLocation TokLoc = Tok.getLocation();
3403 
3404     // Perform literal operator lookup to determine if we're building a raw
3405     // literal or a cooked one.
3406     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3407     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3408                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3409                                   /*AllowStringTemplate*/ false,
3410                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3411     case LOLR_ErrorNoDiagnostic:
3412       // Lookup failure for imaginary constants isn't fatal, there's still the
3413       // GNU extension producing _Complex types.
3414       break;
3415     case LOLR_Error:
3416       return ExprError();
3417     case LOLR_Cooked: {
3418       Expr *Lit;
3419       if (Literal.isFloatingLiteral()) {
3420         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3421       } else {
3422         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3423         if (Literal.GetIntegerValue(ResultVal))
3424           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3425               << /* Unsigned */ 1;
3426         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3427                                      Tok.getLocation());
3428       }
3429       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3430     }
3431 
3432     case LOLR_Raw: {
3433       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3434       // literal is treated as a call of the form
3435       //   operator "" X ("n")
3436       unsigned Length = Literal.getUDSuffixOffset();
3437       QualType StrTy = Context.getConstantArrayType(
3438           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3439           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3440       Expr *Lit = StringLiteral::Create(
3441           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3442           /*Pascal*/false, StrTy, &TokLoc, 1);
3443       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3444     }
3445 
3446     case LOLR_Template: {
3447       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3448       // template), L is treated as a call fo the form
3449       //   operator "" X <'c1', 'c2', ... 'ck'>()
3450       // where n is the source character sequence c1 c2 ... ck.
3451       TemplateArgumentListInfo ExplicitArgs;
3452       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3453       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3454       llvm::APSInt Value(CharBits, CharIsUnsigned);
3455       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3456         Value = TokSpelling[I];
3457         TemplateArgument Arg(Context, Value, Context.CharTy);
3458         TemplateArgumentLocInfo ArgInfo;
3459         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3460       }
3461       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3462                                       &ExplicitArgs);
3463     }
3464     case LOLR_StringTemplate:
3465       llvm_unreachable("unexpected literal operator lookup result");
3466     }
3467   }
3468 
3469   Expr *Res;
3470 
3471   if (Literal.isFixedPointLiteral()) {
3472     QualType Ty;
3473 
3474     if (Literal.isAccum) {
3475       if (Literal.isHalf) {
3476         Ty = Context.ShortAccumTy;
3477       } else if (Literal.isLong) {
3478         Ty = Context.LongAccumTy;
3479       } else {
3480         Ty = Context.AccumTy;
3481       }
3482     } else if (Literal.isFract) {
3483       if (Literal.isHalf) {
3484         Ty = Context.ShortFractTy;
3485       } else if (Literal.isLong) {
3486         Ty = Context.LongFractTy;
3487       } else {
3488         Ty = Context.FractTy;
3489       }
3490     }
3491 
3492     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3493 
3494     bool isSigned = !Literal.isUnsigned;
3495     unsigned scale = Context.getFixedPointScale(Ty);
3496     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3497 
3498     llvm::APInt Val(bit_width, 0, isSigned);
3499     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3500     bool ValIsZero = Val.isNullValue() && !Overflowed;
3501 
3502     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3503     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3504       // Clause 6.4.4 - The value of a constant shall be in the range of
3505       // representable values for its type, with exception for constants of a
3506       // fract type with a value of exactly 1; such a constant shall denote
3507       // the maximal value for the type.
3508       --Val;
3509     else if (Val.ugt(MaxVal) || Overflowed)
3510       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3511 
3512     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3513                                               Tok.getLocation(), scale);
3514   } else if (Literal.isFloatingLiteral()) {
3515     QualType Ty;
3516     if (Literal.isHalf){
3517       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3518         Ty = Context.HalfTy;
3519       else {
3520         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3521         return ExprError();
3522       }
3523     } else if (Literal.isFloat)
3524       Ty = Context.FloatTy;
3525     else if (Literal.isLong)
3526       Ty = Context.LongDoubleTy;
3527     else if (Literal.isFloat16)
3528       Ty = Context.Float16Ty;
3529     else if (Literal.isFloat128)
3530       Ty = Context.Float128Ty;
3531     else
3532       Ty = Context.DoubleTy;
3533 
3534     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3535 
3536     if (Ty == Context.DoubleTy) {
3537       if (getLangOpts().SinglePrecisionConstants) {
3538         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3539         if (BTy->getKind() != BuiltinType::Float) {
3540           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3541         }
3542       } else if (getLangOpts().OpenCL &&
3543                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3544         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3545         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3546         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3547       }
3548     }
3549   } else if (!Literal.isIntegerLiteral()) {
3550     return ExprError();
3551   } else {
3552     QualType Ty;
3553 
3554     // 'long long' is a C99 or C++11 feature.
3555     if (!getLangOpts().C99 && Literal.isLongLong) {
3556       if (getLangOpts().CPlusPlus)
3557         Diag(Tok.getLocation(),
3558              getLangOpts().CPlusPlus11 ?
3559              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3560       else
3561         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3562     }
3563 
3564     // Get the value in the widest-possible width.
3565     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3566     llvm::APInt ResultVal(MaxWidth, 0);
3567 
3568     if (Literal.GetIntegerValue(ResultVal)) {
3569       // If this value didn't fit into uintmax_t, error and force to ull.
3570       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3571           << /* Unsigned */ 1;
3572       Ty = Context.UnsignedLongLongTy;
3573       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3574              "long long is not intmax_t?");
3575     } else {
3576       // If this value fits into a ULL, try to figure out what else it fits into
3577       // according to the rules of C99 6.4.4.1p5.
3578 
3579       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3580       // be an unsigned int.
3581       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3582 
3583       // Check from smallest to largest, picking the smallest type we can.
3584       unsigned Width = 0;
3585 
3586       // Microsoft specific integer suffixes are explicitly sized.
3587       if (Literal.MicrosoftInteger) {
3588         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3589           Width = 8;
3590           Ty = Context.CharTy;
3591         } else {
3592           Width = Literal.MicrosoftInteger;
3593           Ty = Context.getIntTypeForBitwidth(Width,
3594                                              /*Signed=*/!Literal.isUnsigned);
3595         }
3596       }
3597 
3598       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3599         // Are int/unsigned possibilities?
3600         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3601 
3602         // Does it fit in a unsigned int?
3603         if (ResultVal.isIntN(IntSize)) {
3604           // Does it fit in a signed int?
3605           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3606             Ty = Context.IntTy;
3607           else if (AllowUnsigned)
3608             Ty = Context.UnsignedIntTy;
3609           Width = IntSize;
3610         }
3611       }
3612 
3613       // Are long/unsigned long possibilities?
3614       if (Ty.isNull() && !Literal.isLongLong) {
3615         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3616 
3617         // Does it fit in a unsigned long?
3618         if (ResultVal.isIntN(LongSize)) {
3619           // Does it fit in a signed long?
3620           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3621             Ty = Context.LongTy;
3622           else if (AllowUnsigned)
3623             Ty = Context.UnsignedLongTy;
3624           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3625           // is compatible.
3626           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3627             const unsigned LongLongSize =
3628                 Context.getTargetInfo().getLongLongWidth();
3629             Diag(Tok.getLocation(),
3630                  getLangOpts().CPlusPlus
3631                      ? Literal.isLong
3632                            ? diag::warn_old_implicitly_unsigned_long_cxx
3633                            : /*C++98 UB*/ diag::
3634                                  ext_old_implicitly_unsigned_long_cxx
3635                      : diag::warn_old_implicitly_unsigned_long)
3636                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3637                                             : /*will be ill-formed*/ 1);
3638             Ty = Context.UnsignedLongTy;
3639           }
3640           Width = LongSize;
3641         }
3642       }
3643 
3644       // Check long long if needed.
3645       if (Ty.isNull()) {
3646         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3647 
3648         // Does it fit in a unsigned long long?
3649         if (ResultVal.isIntN(LongLongSize)) {
3650           // Does it fit in a signed long long?
3651           // To be compatible with MSVC, hex integer literals ending with the
3652           // LL or i64 suffix are always signed in Microsoft mode.
3653           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3654               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3655             Ty = Context.LongLongTy;
3656           else if (AllowUnsigned)
3657             Ty = Context.UnsignedLongLongTy;
3658           Width = LongLongSize;
3659         }
3660       }
3661 
3662       // If we still couldn't decide a type, we probably have something that
3663       // does not fit in a signed long long, but has no U suffix.
3664       if (Ty.isNull()) {
3665         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3666         Ty = Context.UnsignedLongLongTy;
3667         Width = Context.getTargetInfo().getLongLongWidth();
3668       }
3669 
3670       if (ResultVal.getBitWidth() != Width)
3671         ResultVal = ResultVal.trunc(Width);
3672     }
3673     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3674   }
3675 
3676   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3677   if (Literal.isImaginary) {
3678     Res = new (Context) ImaginaryLiteral(Res,
3679                                         Context.getComplexType(Res->getType()));
3680 
3681     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3682   }
3683   return Res;
3684 }
3685 
3686 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3687   assert(E && "ActOnParenExpr() missing expr");
3688   return new (Context) ParenExpr(L, R, E);
3689 }
3690 
3691 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3692                                          SourceLocation Loc,
3693                                          SourceRange ArgRange) {
3694   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3695   // scalar or vector data type argument..."
3696   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3697   // type (C99 6.2.5p18) or void.
3698   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3699     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3700       << T << ArgRange;
3701     return true;
3702   }
3703 
3704   assert((T->isVoidType() || !T->isIncompleteType()) &&
3705          "Scalar types should always be complete");
3706   return false;
3707 }
3708 
3709 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3710                                            SourceLocation Loc,
3711                                            SourceRange ArgRange,
3712                                            UnaryExprOrTypeTrait TraitKind) {
3713   // Invalid types must be hard errors for SFINAE in C++.
3714   if (S.LangOpts.CPlusPlus)
3715     return true;
3716 
3717   // C99 6.5.3.4p1:
3718   if (T->isFunctionType() &&
3719       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3720        TraitKind == UETT_PreferredAlignOf)) {
3721     // sizeof(function)/alignof(function) is allowed as an extension.
3722     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3723       << TraitKind << ArgRange;
3724     return false;
3725   }
3726 
3727   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3728   // this is an error (OpenCL v1.1 s6.3.k)
3729   if (T->isVoidType()) {
3730     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3731                                         : diag::ext_sizeof_alignof_void_type;
3732     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3733     return false;
3734   }
3735 
3736   return true;
3737 }
3738 
3739 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3740                                              SourceLocation Loc,
3741                                              SourceRange ArgRange,
3742                                              UnaryExprOrTypeTrait TraitKind) {
3743   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3744   // runtime doesn't allow it.
3745   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3746     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3747       << T << (TraitKind == UETT_SizeOf)
3748       << ArgRange;
3749     return true;
3750   }
3751 
3752   return false;
3753 }
3754 
3755 /// Check whether E is a pointer from a decayed array type (the decayed
3756 /// pointer type is equal to T) and emit a warning if it is.
3757 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3758                                      Expr *E) {
3759   // Don't warn if the operation changed the type.
3760   if (T != E->getType())
3761     return;
3762 
3763   // Now look for array decays.
3764   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3765   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3766     return;
3767 
3768   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3769                                              << ICE->getType()
3770                                              << ICE->getSubExpr()->getType();
3771 }
3772 
3773 /// Check the constraints on expression operands to unary type expression
3774 /// and type traits.
3775 ///
3776 /// Completes any types necessary and validates the constraints on the operand
3777 /// expression. The logic mostly mirrors the type-based overload, but may modify
3778 /// the expression as it completes the type for that expression through template
3779 /// instantiation, etc.
3780 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3781                                             UnaryExprOrTypeTrait ExprKind) {
3782   QualType ExprTy = E->getType();
3783   assert(!ExprTy->isReferenceType());
3784 
3785   if (ExprKind == UETT_VecStep)
3786     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3787                                         E->getSourceRange());
3788 
3789   // Whitelist some types as extensions
3790   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3791                                       E->getSourceRange(), ExprKind))
3792     return false;
3793 
3794   // 'alignof' applied to an expression only requires the base element type of
3795   // the expression to be complete. 'sizeof' requires the expression's type to
3796   // be complete (and will attempt to complete it if it's an array of unknown
3797   // bound).
3798   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3799     if (RequireCompleteType(E->getExprLoc(),
3800                             Context.getBaseElementType(E->getType()),
3801                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3802                             E->getSourceRange()))
3803       return true;
3804   } else {
3805     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3806                                 ExprKind, E->getSourceRange()))
3807       return true;
3808   }
3809 
3810   // Completing the expression's type may have changed it.
3811   ExprTy = E->getType();
3812   assert(!ExprTy->isReferenceType());
3813 
3814   if (ExprTy->isFunctionType()) {
3815     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3816       << ExprKind << E->getSourceRange();
3817     return true;
3818   }
3819 
3820   // The operand for sizeof and alignof is in an unevaluated expression context,
3821   // so side effects could result in unintended consequences.
3822   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3823        ExprKind == UETT_PreferredAlignOf) &&
3824       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3825     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3826 
3827   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3828                                        E->getSourceRange(), ExprKind))
3829     return true;
3830 
3831   if (ExprKind == UETT_SizeOf) {
3832     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3833       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3834         QualType OType = PVD->getOriginalType();
3835         QualType Type = PVD->getType();
3836         if (Type->isPointerType() && OType->isArrayType()) {
3837           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3838             << Type << OType;
3839           Diag(PVD->getLocation(), diag::note_declared_at);
3840         }
3841       }
3842     }
3843 
3844     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3845     // decays into a pointer and returns an unintended result. This is most
3846     // likely a typo for "sizeof(array) op x".
3847     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3848       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3849                                BO->getLHS());
3850       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3851                                BO->getRHS());
3852     }
3853   }
3854 
3855   return false;
3856 }
3857 
3858 /// Check the constraints on operands to unary expression and type
3859 /// traits.
3860 ///
3861 /// This will complete any types necessary, and validate the various constraints
3862 /// on those operands.
3863 ///
3864 /// The UsualUnaryConversions() function is *not* called by this routine.
3865 /// C99 6.3.2.1p[2-4] all state:
3866 ///   Except when it is the operand of the sizeof operator ...
3867 ///
3868 /// C++ [expr.sizeof]p4
3869 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3870 ///   standard conversions are not applied to the operand of sizeof.
3871 ///
3872 /// This policy is followed for all of the unary trait expressions.
3873 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3874                                             SourceLocation OpLoc,
3875                                             SourceRange ExprRange,
3876                                             UnaryExprOrTypeTrait ExprKind) {
3877   if (ExprType->isDependentType())
3878     return false;
3879 
3880   // C++ [expr.sizeof]p2:
3881   //     When applied to a reference or a reference type, the result
3882   //     is the size of the referenced type.
3883   // C++11 [expr.alignof]p3:
3884   //     When alignof is applied to a reference type, the result
3885   //     shall be the alignment of the referenced type.
3886   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3887     ExprType = Ref->getPointeeType();
3888 
3889   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3890   //   When alignof or _Alignof is applied to an array type, the result
3891   //   is the alignment of the element type.
3892   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3893       ExprKind == UETT_OpenMPRequiredSimdAlign)
3894     ExprType = Context.getBaseElementType(ExprType);
3895 
3896   if (ExprKind == UETT_VecStep)
3897     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3898 
3899   // Whitelist some types as extensions
3900   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3901                                       ExprKind))
3902     return false;
3903 
3904   if (RequireCompleteType(OpLoc, ExprType,
3905                           diag::err_sizeof_alignof_incomplete_type,
3906                           ExprKind, ExprRange))
3907     return true;
3908 
3909   if (ExprType->isFunctionType()) {
3910     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3911       << ExprKind << ExprRange;
3912     return true;
3913   }
3914 
3915   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3916                                        ExprKind))
3917     return true;
3918 
3919   return false;
3920 }
3921 
3922 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3923   E = E->IgnoreParens();
3924 
3925   // Cannot know anything else if the expression is dependent.
3926   if (E->isTypeDependent())
3927     return false;
3928 
3929   if (E->getObjectKind() == OK_BitField) {
3930     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3931        << 1 << E->getSourceRange();
3932     return true;
3933   }
3934 
3935   ValueDecl *D = nullptr;
3936   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3937     D = DRE->getDecl();
3938   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3939     D = ME->getMemberDecl();
3940   }
3941 
3942   // If it's a field, require the containing struct to have a
3943   // complete definition so that we can compute the layout.
3944   //
3945   // This can happen in C++11 onwards, either by naming the member
3946   // in a way that is not transformed into a member access expression
3947   // (in an unevaluated operand, for instance), or by naming the member
3948   // in a trailing-return-type.
3949   //
3950   // For the record, since __alignof__ on expressions is a GCC
3951   // extension, GCC seems to permit this but always gives the
3952   // nonsensical answer 0.
3953   //
3954   // We don't really need the layout here --- we could instead just
3955   // directly check for all the appropriate alignment-lowing
3956   // attributes --- but that would require duplicating a lot of
3957   // logic that just isn't worth duplicating for such a marginal
3958   // use-case.
3959   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3960     // Fast path this check, since we at least know the record has a
3961     // definition if we can find a member of it.
3962     if (!FD->getParent()->isCompleteDefinition()) {
3963       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3964         << E->getSourceRange();
3965       return true;
3966     }
3967 
3968     // Otherwise, if it's a field, and the field doesn't have
3969     // reference type, then it must have a complete type (or be a
3970     // flexible array member, which we explicitly want to
3971     // white-list anyway), which makes the following checks trivial.
3972     if (!FD->getType()->isReferenceType())
3973       return false;
3974   }
3975 
3976   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3977 }
3978 
3979 bool Sema::CheckVecStepExpr(Expr *E) {
3980   E = E->IgnoreParens();
3981 
3982   // Cannot know anything else if the expression is dependent.
3983   if (E->isTypeDependent())
3984     return false;
3985 
3986   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3987 }
3988 
3989 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3990                                         CapturingScopeInfo *CSI) {
3991   assert(T->isVariablyModifiedType());
3992   assert(CSI != nullptr);
3993 
3994   // We're going to walk down into the type and look for VLA expressions.
3995   do {
3996     const Type *Ty = T.getTypePtr();
3997     switch (Ty->getTypeClass()) {
3998 #define TYPE(Class, Base)
3999 #define ABSTRACT_TYPE(Class, Base)
4000 #define NON_CANONICAL_TYPE(Class, Base)
4001 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4002 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4003 #include "clang/AST/TypeNodes.def"
4004       T = QualType();
4005       break;
4006     // These types are never variably-modified.
4007     case Type::Builtin:
4008     case Type::Complex:
4009     case Type::Vector:
4010     case Type::ExtVector:
4011     case Type::Record:
4012     case Type::Enum:
4013     case Type::Elaborated:
4014     case Type::TemplateSpecialization:
4015     case Type::ObjCObject:
4016     case Type::ObjCInterface:
4017     case Type::ObjCObjectPointer:
4018     case Type::ObjCTypeParam:
4019     case Type::Pipe:
4020       llvm_unreachable("type class is never variably-modified!");
4021     case Type::Adjusted:
4022       T = cast<AdjustedType>(Ty)->getOriginalType();
4023       break;
4024     case Type::Decayed:
4025       T = cast<DecayedType>(Ty)->getPointeeType();
4026       break;
4027     case Type::Pointer:
4028       T = cast<PointerType>(Ty)->getPointeeType();
4029       break;
4030     case Type::BlockPointer:
4031       T = cast<BlockPointerType>(Ty)->getPointeeType();
4032       break;
4033     case Type::LValueReference:
4034     case Type::RValueReference:
4035       T = cast<ReferenceType>(Ty)->getPointeeType();
4036       break;
4037     case Type::MemberPointer:
4038       T = cast<MemberPointerType>(Ty)->getPointeeType();
4039       break;
4040     case Type::ConstantArray:
4041     case Type::IncompleteArray:
4042       // Losing element qualification here is fine.
4043       T = cast<ArrayType>(Ty)->getElementType();
4044       break;
4045     case Type::VariableArray: {
4046       // Losing element qualification here is fine.
4047       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4048 
4049       // Unknown size indication requires no size computation.
4050       // Otherwise, evaluate and record it.
4051       if (auto Size = VAT->getSizeExpr()) {
4052         if (!CSI->isVLATypeCaptured(VAT)) {
4053           RecordDecl *CapRecord = nullptr;
4054           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
4055             CapRecord = LSI->Lambda;
4056           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
4057             CapRecord = CRSI->TheRecordDecl;
4058           }
4059           if (CapRecord) {
4060             auto ExprLoc = Size->getExprLoc();
4061             auto SizeType = Context.getSizeType();
4062             // Build the non-static data member.
4063             auto Field =
4064                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
4065                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
4066                                   /*BW*/ nullptr, /*Mutable*/ false,
4067                                   /*InitStyle*/ ICIS_NoInit);
4068             Field->setImplicit(true);
4069             Field->setAccess(AS_private);
4070             Field->setCapturedVLAType(VAT);
4071             CapRecord->addDecl(Field);
4072 
4073             CSI->addVLATypeCapture(ExprLoc, SizeType);
4074           }
4075         }
4076       }
4077       T = VAT->getElementType();
4078       break;
4079     }
4080     case Type::FunctionProto:
4081     case Type::FunctionNoProto:
4082       T = cast<FunctionType>(Ty)->getReturnType();
4083       break;
4084     case Type::Paren:
4085     case Type::TypeOf:
4086     case Type::UnaryTransform:
4087     case Type::Attributed:
4088     case Type::SubstTemplateTypeParm:
4089     case Type::PackExpansion:
4090     case Type::MacroQualified:
4091       // Keep walking after single level desugaring.
4092       T = T.getSingleStepDesugaredType(Context);
4093       break;
4094     case Type::Typedef:
4095       T = cast<TypedefType>(Ty)->desugar();
4096       break;
4097     case Type::Decltype:
4098       T = cast<DecltypeType>(Ty)->desugar();
4099       break;
4100     case Type::Auto:
4101     case Type::DeducedTemplateSpecialization:
4102       T = cast<DeducedType>(Ty)->getDeducedType();
4103       break;
4104     case Type::TypeOfExpr:
4105       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4106       break;
4107     case Type::Atomic:
4108       T = cast<AtomicType>(Ty)->getValueType();
4109       break;
4110     }
4111   } while (!T.isNull() && T->isVariablyModifiedType());
4112 }
4113 
4114 /// Build a sizeof or alignof expression given a type operand.
4115 ExprResult
4116 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4117                                      SourceLocation OpLoc,
4118                                      UnaryExprOrTypeTrait ExprKind,
4119                                      SourceRange R) {
4120   if (!TInfo)
4121     return ExprError();
4122 
4123   QualType T = TInfo->getType();
4124 
4125   if (!T->isDependentType() &&
4126       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4127     return ExprError();
4128 
4129   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4130     if (auto *TT = T->getAs<TypedefType>()) {
4131       for (auto I = FunctionScopes.rbegin(),
4132                 E = std::prev(FunctionScopes.rend());
4133            I != E; ++I) {
4134         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4135         if (CSI == nullptr)
4136           break;
4137         DeclContext *DC = nullptr;
4138         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4139           DC = LSI->CallOperator;
4140         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4141           DC = CRSI->TheCapturedDecl;
4142         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4143           DC = BSI->TheDecl;
4144         if (DC) {
4145           if (DC->containsDecl(TT->getDecl()))
4146             break;
4147           captureVariablyModifiedType(Context, T, CSI);
4148         }
4149       }
4150     }
4151   }
4152 
4153   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4154   return new (Context) UnaryExprOrTypeTraitExpr(
4155       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4156 }
4157 
4158 /// Build a sizeof or alignof expression given an expression
4159 /// operand.
4160 ExprResult
4161 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4162                                      UnaryExprOrTypeTrait ExprKind) {
4163   ExprResult PE = CheckPlaceholderExpr(E);
4164   if (PE.isInvalid())
4165     return ExprError();
4166 
4167   E = PE.get();
4168 
4169   // Verify that the operand is valid.
4170   bool isInvalid = false;
4171   if (E->isTypeDependent()) {
4172     // Delay type-checking for type-dependent expressions.
4173   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4174     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4175   } else if (ExprKind == UETT_VecStep) {
4176     isInvalid = CheckVecStepExpr(E);
4177   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4178       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4179       isInvalid = true;
4180   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4181     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4182     isInvalid = true;
4183   } else {
4184     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4185   }
4186 
4187   if (isInvalid)
4188     return ExprError();
4189 
4190   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4191     PE = TransformToPotentiallyEvaluated(E);
4192     if (PE.isInvalid()) return ExprError();
4193     E = PE.get();
4194   }
4195 
4196   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4197   return new (Context) UnaryExprOrTypeTraitExpr(
4198       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4199 }
4200 
4201 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4202 /// expr and the same for @c alignof and @c __alignof
4203 /// Note that the ArgRange is invalid if isType is false.
4204 ExprResult
4205 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4206                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4207                                     void *TyOrEx, SourceRange ArgRange) {
4208   // If error parsing type, ignore.
4209   if (!TyOrEx) return ExprError();
4210 
4211   if (IsType) {
4212     TypeSourceInfo *TInfo;
4213     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4214     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4215   }
4216 
4217   Expr *ArgEx = (Expr *)TyOrEx;
4218   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4219   return Result;
4220 }
4221 
4222 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4223                                      bool IsReal) {
4224   if (V.get()->isTypeDependent())
4225     return S.Context.DependentTy;
4226 
4227   // _Real and _Imag are only l-values for normal l-values.
4228   if (V.get()->getObjectKind() != OK_Ordinary) {
4229     V = S.DefaultLvalueConversion(V.get());
4230     if (V.isInvalid())
4231       return QualType();
4232   }
4233 
4234   // These operators return the element type of a complex type.
4235   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4236     return CT->getElementType();
4237 
4238   // Otherwise they pass through real integer and floating point types here.
4239   if (V.get()->getType()->isArithmeticType())
4240     return V.get()->getType();
4241 
4242   // Test for placeholders.
4243   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4244   if (PR.isInvalid()) return QualType();
4245   if (PR.get() != V.get()) {
4246     V = PR;
4247     return CheckRealImagOperand(S, V, Loc, IsReal);
4248   }
4249 
4250   // Reject anything else.
4251   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4252     << (IsReal ? "__real" : "__imag");
4253   return QualType();
4254 }
4255 
4256 
4257 
4258 ExprResult
4259 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4260                           tok::TokenKind Kind, Expr *Input) {
4261   UnaryOperatorKind Opc;
4262   switch (Kind) {
4263   default: llvm_unreachable("Unknown unary op!");
4264   case tok::plusplus:   Opc = UO_PostInc; break;
4265   case tok::minusminus: Opc = UO_PostDec; break;
4266   }
4267 
4268   // Since this might is a postfix expression, get rid of ParenListExprs.
4269   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4270   if (Result.isInvalid()) return ExprError();
4271   Input = Result.get();
4272 
4273   return BuildUnaryOp(S, OpLoc, Opc, Input);
4274 }
4275 
4276 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4277 ///
4278 /// \return true on error
4279 static bool checkArithmeticOnObjCPointer(Sema &S,
4280                                          SourceLocation opLoc,
4281                                          Expr *op) {
4282   assert(op->getType()->isObjCObjectPointerType());
4283   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4284       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4285     return false;
4286 
4287   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4288     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4289     << op->getSourceRange();
4290   return true;
4291 }
4292 
4293 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4294   auto *BaseNoParens = Base->IgnoreParens();
4295   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4296     return MSProp->getPropertyDecl()->getType()->isArrayType();
4297   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4298 }
4299 
4300 ExprResult
4301 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4302                               Expr *idx, SourceLocation rbLoc) {
4303   if (base && !base->getType().isNull() &&
4304       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4305     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4306                                     /*Length=*/nullptr, rbLoc);
4307 
4308   // Since this might be a postfix expression, get rid of ParenListExprs.
4309   if (isa<ParenListExpr>(base)) {
4310     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4311     if (result.isInvalid()) return ExprError();
4312     base = result.get();
4313   }
4314 
4315   // Handle any non-overload placeholder types in the base and index
4316   // expressions.  We can't handle overloads here because the other
4317   // operand might be an overloadable type, in which case the overload
4318   // resolution for the operator overload should get the first crack
4319   // at the overload.
4320   bool IsMSPropertySubscript = false;
4321   if (base->getType()->isNonOverloadPlaceholderType()) {
4322     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4323     if (!IsMSPropertySubscript) {
4324       ExprResult result = CheckPlaceholderExpr(base);
4325       if (result.isInvalid())
4326         return ExprError();
4327       base = result.get();
4328     }
4329   }
4330   if (idx->getType()->isNonOverloadPlaceholderType()) {
4331     ExprResult result = CheckPlaceholderExpr(idx);
4332     if (result.isInvalid()) return ExprError();
4333     idx = result.get();
4334   }
4335 
4336   // Build an unanalyzed expression if either operand is type-dependent.
4337   if (getLangOpts().CPlusPlus &&
4338       (base->isTypeDependent() || idx->isTypeDependent())) {
4339     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4340                                             VK_LValue, OK_Ordinary, rbLoc);
4341   }
4342 
4343   // MSDN, property (C++)
4344   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4345   // This attribute can also be used in the declaration of an empty array in a
4346   // class or structure definition. For example:
4347   // __declspec(property(get=GetX, put=PutX)) int x[];
4348   // The above statement indicates that x[] can be used with one or more array
4349   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4350   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4351   if (IsMSPropertySubscript) {
4352     // Build MS property subscript expression if base is MS property reference
4353     // or MS property subscript.
4354     return new (Context) MSPropertySubscriptExpr(
4355         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4356   }
4357 
4358   // Use C++ overloaded-operator rules if either operand has record
4359   // type.  The spec says to do this if either type is *overloadable*,
4360   // but enum types can't declare subscript operators or conversion
4361   // operators, so there's nothing interesting for overload resolution
4362   // to do if there aren't any record types involved.
4363   //
4364   // ObjC pointers have their own subscripting logic that is not tied
4365   // to overload resolution and so should not take this path.
4366   if (getLangOpts().CPlusPlus &&
4367       (base->getType()->isRecordType() ||
4368        (!base->getType()->isObjCObjectPointerType() &&
4369         idx->getType()->isRecordType()))) {
4370     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4371   }
4372 
4373   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4374 
4375   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4376     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4377 
4378   return Res;
4379 }
4380 
4381 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4382   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4383   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4384 
4385   // For expressions like `&(*s).b`, the base is recorded and what should be
4386   // checked.
4387   const MemberExpr *Member = nullptr;
4388   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4389     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4390 
4391   LastRecord.PossibleDerefs.erase(StrippedExpr);
4392 }
4393 
4394 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4395   QualType ResultTy = E->getType();
4396   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4397 
4398   // Bail if the element is an array since it is not memory access.
4399   if (isa<ArrayType>(ResultTy))
4400     return;
4401 
4402   if (ResultTy->hasAttr(attr::NoDeref)) {
4403     LastRecord.PossibleDerefs.insert(E);
4404     return;
4405   }
4406 
4407   // Check if the base type is a pointer to a member access of a struct
4408   // marked with noderef.
4409   const Expr *Base = E->getBase();
4410   QualType BaseTy = Base->getType();
4411   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4412     // Not a pointer access
4413     return;
4414 
4415   const MemberExpr *Member = nullptr;
4416   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4417          Member->isArrow())
4418     Base = Member->getBase();
4419 
4420   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4421     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4422       LastRecord.PossibleDerefs.insert(E);
4423   }
4424 }
4425 
4426 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4427                                           Expr *LowerBound,
4428                                           SourceLocation ColonLoc, Expr *Length,
4429                                           SourceLocation RBLoc) {
4430   if (Base->getType()->isPlaceholderType() &&
4431       !Base->getType()->isSpecificPlaceholderType(
4432           BuiltinType::OMPArraySection)) {
4433     ExprResult Result = CheckPlaceholderExpr(Base);
4434     if (Result.isInvalid())
4435       return ExprError();
4436     Base = Result.get();
4437   }
4438   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4439     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4440     if (Result.isInvalid())
4441       return ExprError();
4442     Result = DefaultLvalueConversion(Result.get());
4443     if (Result.isInvalid())
4444       return ExprError();
4445     LowerBound = Result.get();
4446   }
4447   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4448     ExprResult Result = CheckPlaceholderExpr(Length);
4449     if (Result.isInvalid())
4450       return ExprError();
4451     Result = DefaultLvalueConversion(Result.get());
4452     if (Result.isInvalid())
4453       return ExprError();
4454     Length = Result.get();
4455   }
4456 
4457   // Build an unanalyzed expression if either operand is type-dependent.
4458   if (Base->isTypeDependent() ||
4459       (LowerBound &&
4460        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4461       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4462     return new (Context)
4463         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4464                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4465   }
4466 
4467   // Perform default conversions.
4468   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4469   QualType ResultTy;
4470   if (OriginalTy->isAnyPointerType()) {
4471     ResultTy = OriginalTy->getPointeeType();
4472   } else if (OriginalTy->isArrayType()) {
4473     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4474   } else {
4475     return ExprError(
4476         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4477         << Base->getSourceRange());
4478   }
4479   // C99 6.5.2.1p1
4480   if (LowerBound) {
4481     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4482                                                       LowerBound);
4483     if (Res.isInvalid())
4484       return ExprError(Diag(LowerBound->getExprLoc(),
4485                             diag::err_omp_typecheck_section_not_integer)
4486                        << 0 << LowerBound->getSourceRange());
4487     LowerBound = Res.get();
4488 
4489     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4490         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4491       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4492           << 0 << LowerBound->getSourceRange();
4493   }
4494   if (Length) {
4495     auto Res =
4496         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4497     if (Res.isInvalid())
4498       return ExprError(Diag(Length->getExprLoc(),
4499                             diag::err_omp_typecheck_section_not_integer)
4500                        << 1 << Length->getSourceRange());
4501     Length = Res.get();
4502 
4503     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4504         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4505       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4506           << 1 << Length->getSourceRange();
4507   }
4508 
4509   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4510   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4511   // type. Note that functions are not objects, and that (in C99 parlance)
4512   // incomplete types are not object types.
4513   if (ResultTy->isFunctionType()) {
4514     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4515         << ResultTy << Base->getSourceRange();
4516     return ExprError();
4517   }
4518 
4519   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4520                           diag::err_omp_section_incomplete_type, Base))
4521     return ExprError();
4522 
4523   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4524     Expr::EvalResult Result;
4525     if (LowerBound->EvaluateAsInt(Result, Context)) {
4526       // OpenMP 4.5, [2.4 Array Sections]
4527       // The array section must be a subset of the original array.
4528       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4529       if (LowerBoundValue.isNegative()) {
4530         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4531             << LowerBound->getSourceRange();
4532         return ExprError();
4533       }
4534     }
4535   }
4536 
4537   if (Length) {
4538     Expr::EvalResult Result;
4539     if (Length->EvaluateAsInt(Result, Context)) {
4540       // OpenMP 4.5, [2.4 Array Sections]
4541       // The length must evaluate to non-negative integers.
4542       llvm::APSInt LengthValue = Result.Val.getInt();
4543       if (LengthValue.isNegative()) {
4544         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4545             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4546             << Length->getSourceRange();
4547         return ExprError();
4548       }
4549     }
4550   } else if (ColonLoc.isValid() &&
4551              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4552                                       !OriginalTy->isVariableArrayType()))) {
4553     // OpenMP 4.5, [2.4 Array Sections]
4554     // When the size of the array dimension is not known, the length must be
4555     // specified explicitly.
4556     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4557         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4558     return ExprError();
4559   }
4560 
4561   if (!Base->getType()->isSpecificPlaceholderType(
4562           BuiltinType::OMPArraySection)) {
4563     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4564     if (Result.isInvalid())
4565       return ExprError();
4566     Base = Result.get();
4567   }
4568   return new (Context)
4569       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4570                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4571 }
4572 
4573 ExprResult
4574 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4575                                       Expr *Idx, SourceLocation RLoc) {
4576   Expr *LHSExp = Base;
4577   Expr *RHSExp = Idx;
4578 
4579   ExprValueKind VK = VK_LValue;
4580   ExprObjectKind OK = OK_Ordinary;
4581 
4582   // Per C++ core issue 1213, the result is an xvalue if either operand is
4583   // a non-lvalue array, and an lvalue otherwise.
4584   if (getLangOpts().CPlusPlus11) {
4585     for (auto *Op : {LHSExp, RHSExp}) {
4586       Op = Op->IgnoreImplicit();
4587       if (Op->getType()->isArrayType() && !Op->isLValue())
4588         VK = VK_XValue;
4589     }
4590   }
4591 
4592   // Perform default conversions.
4593   if (!LHSExp->getType()->getAs<VectorType>()) {
4594     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4595     if (Result.isInvalid())
4596       return ExprError();
4597     LHSExp = Result.get();
4598   }
4599   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4600   if (Result.isInvalid())
4601     return ExprError();
4602   RHSExp = Result.get();
4603 
4604   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4605 
4606   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4607   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4608   // in the subscript position. As a result, we need to derive the array base
4609   // and index from the expression types.
4610   Expr *BaseExpr, *IndexExpr;
4611   QualType ResultType;
4612   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4613     BaseExpr = LHSExp;
4614     IndexExpr = RHSExp;
4615     ResultType = Context.DependentTy;
4616   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4617     BaseExpr = LHSExp;
4618     IndexExpr = RHSExp;
4619     ResultType = PTy->getPointeeType();
4620   } else if (const ObjCObjectPointerType *PTy =
4621                LHSTy->getAs<ObjCObjectPointerType>()) {
4622     BaseExpr = LHSExp;
4623     IndexExpr = RHSExp;
4624 
4625     // Use custom logic if this should be the pseudo-object subscript
4626     // expression.
4627     if (!LangOpts.isSubscriptPointerArithmetic())
4628       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4629                                           nullptr);
4630 
4631     ResultType = PTy->getPointeeType();
4632   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4633      // Handle the uncommon case of "123[Ptr]".
4634     BaseExpr = RHSExp;
4635     IndexExpr = LHSExp;
4636     ResultType = PTy->getPointeeType();
4637   } else if (const ObjCObjectPointerType *PTy =
4638                RHSTy->getAs<ObjCObjectPointerType>()) {
4639      // Handle the uncommon case of "123[Ptr]".
4640     BaseExpr = RHSExp;
4641     IndexExpr = LHSExp;
4642     ResultType = PTy->getPointeeType();
4643     if (!LangOpts.isSubscriptPointerArithmetic()) {
4644       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4645         << ResultType << BaseExpr->getSourceRange();
4646       return ExprError();
4647     }
4648   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4649     BaseExpr = LHSExp;    // vectors: V[123]
4650     IndexExpr = RHSExp;
4651     // We apply C++ DR1213 to vector subscripting too.
4652     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4653       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4654       if (Materialized.isInvalid())
4655         return ExprError();
4656       LHSExp = Materialized.get();
4657     }
4658     VK = LHSExp->getValueKind();
4659     if (VK != VK_RValue)
4660       OK = OK_VectorComponent;
4661 
4662     ResultType = VTy->getElementType();
4663     QualType BaseType = BaseExpr->getType();
4664     Qualifiers BaseQuals = BaseType.getQualifiers();
4665     Qualifiers MemberQuals = ResultType.getQualifiers();
4666     Qualifiers Combined = BaseQuals + MemberQuals;
4667     if (Combined != MemberQuals)
4668       ResultType = Context.getQualifiedType(ResultType, Combined);
4669   } else if (LHSTy->isArrayType()) {
4670     // If we see an array that wasn't promoted by
4671     // DefaultFunctionArrayLvalueConversion, it must be an array that
4672     // wasn't promoted because of the C90 rule that doesn't
4673     // allow promoting non-lvalue arrays.  Warn, then
4674     // force the promotion here.
4675     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4676         << LHSExp->getSourceRange();
4677     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4678                                CK_ArrayToPointerDecay).get();
4679     LHSTy = LHSExp->getType();
4680 
4681     BaseExpr = LHSExp;
4682     IndexExpr = RHSExp;
4683     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4684   } else if (RHSTy->isArrayType()) {
4685     // Same as previous, except for 123[f().a] case
4686     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4687         << RHSExp->getSourceRange();
4688     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4689                                CK_ArrayToPointerDecay).get();
4690     RHSTy = RHSExp->getType();
4691 
4692     BaseExpr = RHSExp;
4693     IndexExpr = LHSExp;
4694     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4695   } else {
4696     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4697        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4698   }
4699   // C99 6.5.2.1p1
4700   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4701     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4702                      << IndexExpr->getSourceRange());
4703 
4704   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4705        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4706          && !IndexExpr->isTypeDependent())
4707     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4708 
4709   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4710   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4711   // type. Note that Functions are not objects, and that (in C99 parlance)
4712   // incomplete types are not object types.
4713   if (ResultType->isFunctionType()) {
4714     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4715         << ResultType << BaseExpr->getSourceRange();
4716     return ExprError();
4717   }
4718 
4719   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4720     // GNU extension: subscripting on pointer to void
4721     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4722       << BaseExpr->getSourceRange();
4723 
4724     // C forbids expressions of unqualified void type from being l-values.
4725     // See IsCForbiddenLValueType.
4726     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4727   } else if (!ResultType->isDependentType() &&
4728       RequireCompleteType(LLoc, ResultType,
4729                           diag::err_subscript_incomplete_type, BaseExpr))
4730     return ExprError();
4731 
4732   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4733          !ResultType.isCForbiddenLValueType());
4734 
4735   return new (Context)
4736       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4737 }
4738 
4739 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4740                                   ParmVarDecl *Param) {
4741   if (Param->hasUnparsedDefaultArg()) {
4742     Diag(CallLoc,
4743          diag::err_use_of_default_argument_to_function_declared_later) <<
4744       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4745     Diag(UnparsedDefaultArgLocs[Param],
4746          diag::note_default_argument_declared_here);
4747     return true;
4748   }
4749 
4750   if (Param->hasUninstantiatedDefaultArg()) {
4751     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4752 
4753     EnterExpressionEvaluationContext EvalContext(
4754         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4755 
4756     // Instantiate the expression.
4757     //
4758     // FIXME: Pass in a correct Pattern argument, otherwise
4759     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4760     //
4761     // template<typename T>
4762     // struct A {
4763     //   static int FooImpl();
4764     //
4765     //   template<typename Tp>
4766     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4767     //   // template argument list [[T], [Tp]], should be [[Tp]].
4768     //   friend A<Tp> Foo(int a);
4769     // };
4770     //
4771     // template<typename T>
4772     // A<T> Foo(int a = A<T>::FooImpl());
4773     MultiLevelTemplateArgumentList MutiLevelArgList
4774       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4775 
4776     InstantiatingTemplate Inst(*this, CallLoc, Param,
4777                                MutiLevelArgList.getInnermost());
4778     if (Inst.isInvalid())
4779       return true;
4780     if (Inst.isAlreadyInstantiating()) {
4781       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4782       Param->setInvalidDecl();
4783       return true;
4784     }
4785 
4786     ExprResult Result;
4787     {
4788       // C++ [dcl.fct.default]p5:
4789       //   The names in the [default argument] expression are bound, and
4790       //   the semantic constraints are checked, at the point where the
4791       //   default argument expression appears.
4792       ContextRAII SavedContext(*this, FD);
4793       LocalInstantiationScope Local(*this);
4794       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4795                                 /*DirectInit*/false);
4796     }
4797     if (Result.isInvalid())
4798       return true;
4799 
4800     // Check the expression as an initializer for the parameter.
4801     InitializedEntity Entity
4802       = InitializedEntity::InitializeParameter(Context, Param);
4803     InitializationKind Kind = InitializationKind::CreateCopy(
4804         Param->getLocation(),
4805         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4806     Expr *ResultE = Result.getAs<Expr>();
4807 
4808     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4809     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4810     if (Result.isInvalid())
4811       return true;
4812 
4813     Result =
4814         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4815                             /*DiscardedValue*/ false);
4816     if (Result.isInvalid())
4817       return true;
4818 
4819     // Remember the instantiated default argument.
4820     Param->setDefaultArg(Result.getAs<Expr>());
4821     if (ASTMutationListener *L = getASTMutationListener()) {
4822       L->DefaultArgumentInstantiated(Param);
4823     }
4824   }
4825 
4826   // If the default argument expression is not set yet, we are building it now.
4827   if (!Param->hasInit()) {
4828     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4829     Param->setInvalidDecl();
4830     return true;
4831   }
4832 
4833   // If the default expression creates temporaries, we need to
4834   // push them to the current stack of expression temporaries so they'll
4835   // be properly destroyed.
4836   // FIXME: We should really be rebuilding the default argument with new
4837   // bound temporaries; see the comment in PR5810.
4838   // We don't need to do that with block decls, though, because
4839   // blocks in default argument expression can never capture anything.
4840   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4841     // Set the "needs cleanups" bit regardless of whether there are
4842     // any explicit objects.
4843     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4844 
4845     // Append all the objects to the cleanup list.  Right now, this
4846     // should always be a no-op, because blocks in default argument
4847     // expressions should never be able to capture anything.
4848     assert(!Init->getNumObjects() &&
4849            "default argument expression has capturing blocks?");
4850   }
4851 
4852   // We already type-checked the argument, so we know it works.
4853   // Just mark all of the declarations in this potentially-evaluated expression
4854   // as being "referenced".
4855   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4856                                    /*SkipLocalVariables=*/true);
4857   return false;
4858 }
4859 
4860 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4861                                         FunctionDecl *FD, ParmVarDecl *Param) {
4862   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4863     return ExprError();
4864   return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
4865 }
4866 
4867 Sema::VariadicCallType
4868 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4869                           Expr *Fn) {
4870   if (Proto && Proto->isVariadic()) {
4871     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4872       return VariadicConstructor;
4873     else if (Fn && Fn->getType()->isBlockPointerType())
4874       return VariadicBlock;
4875     else if (FDecl) {
4876       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4877         if (Method->isInstance())
4878           return VariadicMethod;
4879     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4880       return VariadicMethod;
4881     return VariadicFunction;
4882   }
4883   return VariadicDoesNotApply;
4884 }
4885 
4886 namespace {
4887 class FunctionCallCCC final : public FunctionCallFilterCCC {
4888 public:
4889   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4890                   unsigned NumArgs, MemberExpr *ME)
4891       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4892         FunctionName(FuncName) {}
4893 
4894   bool ValidateCandidate(const TypoCorrection &candidate) override {
4895     if (!candidate.getCorrectionSpecifier() ||
4896         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4897       return false;
4898     }
4899 
4900     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4901   }
4902 
4903   std::unique_ptr<CorrectionCandidateCallback> clone() override {
4904     return llvm::make_unique<FunctionCallCCC>(*this);
4905   }
4906 
4907 private:
4908   const IdentifierInfo *const FunctionName;
4909 };
4910 }
4911 
4912 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4913                                                FunctionDecl *FDecl,
4914                                                ArrayRef<Expr *> Args) {
4915   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4916   DeclarationName FuncName = FDecl->getDeclName();
4917   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4918 
4919   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4920   if (TypoCorrection Corrected = S.CorrectTypo(
4921           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4922           S.getScopeForContext(S.CurContext), nullptr, CCC,
4923           Sema::CTK_ErrorRecovery)) {
4924     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4925       if (Corrected.isOverloaded()) {
4926         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4927         OverloadCandidateSet::iterator Best;
4928         for (NamedDecl *CD : Corrected) {
4929           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4930             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4931                                    OCS);
4932         }
4933         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4934         case OR_Success:
4935           ND = Best->FoundDecl;
4936           Corrected.setCorrectionDecl(ND);
4937           break;
4938         default:
4939           break;
4940         }
4941       }
4942       ND = ND->getUnderlyingDecl();
4943       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4944         return Corrected;
4945     }
4946   }
4947   return TypoCorrection();
4948 }
4949 
4950 /// ConvertArgumentsForCall - Converts the arguments specified in
4951 /// Args/NumArgs to the parameter types of the function FDecl with
4952 /// function prototype Proto. Call is the call expression itself, and
4953 /// Fn is the function expression. For a C++ member function, this
4954 /// routine does not attempt to convert the object argument. Returns
4955 /// true if the call is ill-formed.
4956 bool
4957 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4958                               FunctionDecl *FDecl,
4959                               const FunctionProtoType *Proto,
4960                               ArrayRef<Expr *> Args,
4961                               SourceLocation RParenLoc,
4962                               bool IsExecConfig) {
4963   // Bail out early if calling a builtin with custom typechecking.
4964   if (FDecl)
4965     if (unsigned ID = FDecl->getBuiltinID())
4966       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4967         return false;
4968 
4969   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4970   // assignment, to the types of the corresponding parameter, ...
4971   unsigned NumParams = Proto->getNumParams();
4972   bool Invalid = false;
4973   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4974   unsigned FnKind = Fn->getType()->isBlockPointerType()
4975                        ? 1 /* block */
4976                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4977                                        : 0 /* function */);
4978 
4979   // If too few arguments are available (and we don't have default
4980   // arguments for the remaining parameters), don't make the call.
4981   if (Args.size() < NumParams) {
4982     if (Args.size() < MinArgs) {
4983       TypoCorrection TC;
4984       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4985         unsigned diag_id =
4986             MinArgs == NumParams && !Proto->isVariadic()
4987                 ? diag::err_typecheck_call_too_few_args_suggest
4988                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4989         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4990                                         << static_cast<unsigned>(Args.size())
4991                                         << TC.getCorrectionRange());
4992       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4993         Diag(RParenLoc,
4994              MinArgs == NumParams && !Proto->isVariadic()
4995                  ? diag::err_typecheck_call_too_few_args_one
4996                  : diag::err_typecheck_call_too_few_args_at_least_one)
4997             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4998       else
4999         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5000                             ? diag::err_typecheck_call_too_few_args
5001                             : diag::err_typecheck_call_too_few_args_at_least)
5002             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5003             << Fn->getSourceRange();
5004 
5005       // Emit the location of the prototype.
5006       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5007         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5008 
5009       return true;
5010     }
5011     // We reserve space for the default arguments when we create
5012     // the call expression, before calling ConvertArgumentsForCall.
5013     assert((Call->getNumArgs() == NumParams) &&
5014            "We should have reserved space for the default arguments before!");
5015   }
5016 
5017   // If too many are passed and not variadic, error on the extras and drop
5018   // them.
5019   if (Args.size() > NumParams) {
5020     if (!Proto->isVariadic()) {
5021       TypoCorrection TC;
5022       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5023         unsigned diag_id =
5024             MinArgs == NumParams && !Proto->isVariadic()
5025                 ? diag::err_typecheck_call_too_many_args_suggest
5026                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5027         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5028                                         << static_cast<unsigned>(Args.size())
5029                                         << TC.getCorrectionRange());
5030       } else if (NumParams == 1 && FDecl &&
5031                  FDecl->getParamDecl(0)->getDeclName())
5032         Diag(Args[NumParams]->getBeginLoc(),
5033              MinArgs == NumParams
5034                  ? diag::err_typecheck_call_too_many_args_one
5035                  : diag::err_typecheck_call_too_many_args_at_most_one)
5036             << FnKind << FDecl->getParamDecl(0)
5037             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5038             << SourceRange(Args[NumParams]->getBeginLoc(),
5039                            Args.back()->getEndLoc());
5040       else
5041         Diag(Args[NumParams]->getBeginLoc(),
5042              MinArgs == NumParams
5043                  ? diag::err_typecheck_call_too_many_args
5044                  : diag::err_typecheck_call_too_many_args_at_most)
5045             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5046             << Fn->getSourceRange()
5047             << SourceRange(Args[NumParams]->getBeginLoc(),
5048                            Args.back()->getEndLoc());
5049 
5050       // Emit the location of the prototype.
5051       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5052         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5053 
5054       // This deletes the extra arguments.
5055       Call->shrinkNumArgs(NumParams);
5056       return true;
5057     }
5058   }
5059   SmallVector<Expr *, 8> AllArgs;
5060   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5061 
5062   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5063                                    AllArgs, CallType);
5064   if (Invalid)
5065     return true;
5066   unsigned TotalNumArgs = AllArgs.size();
5067   for (unsigned i = 0; i < TotalNumArgs; ++i)
5068     Call->setArg(i, AllArgs[i]);
5069 
5070   return false;
5071 }
5072 
5073 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5074                                   const FunctionProtoType *Proto,
5075                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5076                                   SmallVectorImpl<Expr *> &AllArgs,
5077                                   VariadicCallType CallType, bool AllowExplicit,
5078                                   bool IsListInitialization) {
5079   unsigned NumParams = Proto->getNumParams();
5080   bool Invalid = false;
5081   size_t ArgIx = 0;
5082   // Continue to check argument types (even if we have too few/many args).
5083   for (unsigned i = FirstParam; i < NumParams; i++) {
5084     QualType ProtoArgType = Proto->getParamType(i);
5085 
5086     Expr *Arg;
5087     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5088     if (ArgIx < Args.size()) {
5089       Arg = Args[ArgIx++];
5090 
5091       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5092                               diag::err_call_incomplete_argument, Arg))
5093         return true;
5094 
5095       // Strip the unbridged-cast placeholder expression off, if applicable.
5096       bool CFAudited = false;
5097       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5098           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5099           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5100         Arg = stripARCUnbridgedCast(Arg);
5101       else if (getLangOpts().ObjCAutoRefCount &&
5102                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5103                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5104         CFAudited = true;
5105 
5106       if (Proto->getExtParameterInfo(i).isNoEscape())
5107         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5108           BE->getBlockDecl()->setDoesNotEscape();
5109 
5110       InitializedEntity Entity =
5111           Param ? InitializedEntity::InitializeParameter(Context, Param,
5112                                                          ProtoArgType)
5113                 : InitializedEntity::InitializeParameter(
5114                       Context, ProtoArgType, Proto->isParamConsumed(i));
5115 
5116       // Remember that parameter belongs to a CF audited API.
5117       if (CFAudited)
5118         Entity.setParameterCFAudited();
5119 
5120       ExprResult ArgE = PerformCopyInitialization(
5121           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5122       if (ArgE.isInvalid())
5123         return true;
5124 
5125       Arg = ArgE.getAs<Expr>();
5126     } else {
5127       assert(Param && "can't use default arguments without a known callee");
5128 
5129       ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5130       if (ArgExpr.isInvalid())
5131         return true;
5132 
5133       Arg = ArgExpr.getAs<Expr>();
5134     }
5135 
5136     // Check for array bounds violations for each argument to the call. This
5137     // check only triggers warnings when the argument isn't a more complex Expr
5138     // with its own checking, such as a BinaryOperator.
5139     CheckArrayAccess(Arg);
5140 
5141     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5142     CheckStaticArrayArgument(CallLoc, Param, Arg);
5143 
5144     AllArgs.push_back(Arg);
5145   }
5146 
5147   // If this is a variadic call, handle args passed through "...".
5148   if (CallType != VariadicDoesNotApply) {
5149     // Assume that extern "C" functions with variadic arguments that
5150     // return __unknown_anytype aren't *really* variadic.
5151     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5152         FDecl->isExternC()) {
5153       for (Expr *A : Args.slice(ArgIx)) {
5154         QualType paramType; // ignored
5155         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5156         Invalid |= arg.isInvalid();
5157         AllArgs.push_back(arg.get());
5158       }
5159 
5160     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5161     } else {
5162       for (Expr *A : Args.slice(ArgIx)) {
5163         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5164         Invalid |= Arg.isInvalid();
5165         AllArgs.push_back(Arg.get());
5166       }
5167     }
5168 
5169     // Check for array bounds violations.
5170     for (Expr *A : Args.slice(ArgIx))
5171       CheckArrayAccess(A);
5172   }
5173   return Invalid;
5174 }
5175 
5176 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5177   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5178   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5179     TL = DTL.getOriginalLoc();
5180   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5181     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5182       << ATL.getLocalSourceRange();
5183 }
5184 
5185 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5186 /// array parameter, check that it is non-null, and that if it is formed by
5187 /// array-to-pointer decay, the underlying array is sufficiently large.
5188 ///
5189 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5190 /// array type derivation, then for each call to the function, the value of the
5191 /// corresponding actual argument shall provide access to the first element of
5192 /// an array with at least as many elements as specified by the size expression.
5193 void
5194 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5195                                ParmVarDecl *Param,
5196                                const Expr *ArgExpr) {
5197   // Static array parameters are not supported in C++.
5198   if (!Param || getLangOpts().CPlusPlus)
5199     return;
5200 
5201   QualType OrigTy = Param->getOriginalType();
5202 
5203   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5204   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5205     return;
5206 
5207   if (ArgExpr->isNullPointerConstant(Context,
5208                                      Expr::NPC_NeverValueDependent)) {
5209     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5210     DiagnoseCalleeStaticArrayParam(*this, Param);
5211     return;
5212   }
5213 
5214   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5215   if (!CAT)
5216     return;
5217 
5218   const ConstantArrayType *ArgCAT =
5219     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5220   if (!ArgCAT)
5221     return;
5222 
5223   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5224                                              ArgCAT->getElementType())) {
5225     if (ArgCAT->getSize().ult(CAT->getSize())) {
5226       Diag(CallLoc, diag::warn_static_array_too_small)
5227           << ArgExpr->getSourceRange()
5228           << (unsigned)ArgCAT->getSize().getZExtValue()
5229           << (unsigned)CAT->getSize().getZExtValue() << 0;
5230       DiagnoseCalleeStaticArrayParam(*this, Param);
5231     }
5232     return;
5233   }
5234 
5235   Optional<CharUnits> ArgSize =
5236       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5237   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5238   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5239     Diag(CallLoc, diag::warn_static_array_too_small)
5240         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5241         << (unsigned)ParmSize->getQuantity() << 1;
5242     DiagnoseCalleeStaticArrayParam(*this, Param);
5243   }
5244 }
5245 
5246 /// Given a function expression of unknown-any type, try to rebuild it
5247 /// to have a function type.
5248 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5249 
5250 /// Is the given type a placeholder that we need to lower out
5251 /// immediately during argument processing?
5252 static bool isPlaceholderToRemoveAsArg(QualType type) {
5253   // Placeholders are never sugared.
5254   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5255   if (!placeholder) return false;
5256 
5257   switch (placeholder->getKind()) {
5258   // Ignore all the non-placeholder types.
5259 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5260   case BuiltinType::Id:
5261 #include "clang/Basic/OpenCLImageTypes.def"
5262 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5263   case BuiltinType::Id:
5264 #include "clang/Basic/OpenCLExtensionTypes.def"
5265 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5266 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5267 #include "clang/AST/BuiltinTypes.def"
5268     return false;
5269 
5270   // We cannot lower out overload sets; they might validly be resolved
5271   // by the call machinery.
5272   case BuiltinType::Overload:
5273     return false;
5274 
5275   // Unbridged casts in ARC can be handled in some call positions and
5276   // should be left in place.
5277   case BuiltinType::ARCUnbridgedCast:
5278     return false;
5279 
5280   // Pseudo-objects should be converted as soon as possible.
5281   case BuiltinType::PseudoObject:
5282     return true;
5283 
5284   // The debugger mode could theoretically but currently does not try
5285   // to resolve unknown-typed arguments based on known parameter types.
5286   case BuiltinType::UnknownAny:
5287     return true;
5288 
5289   // These are always invalid as call arguments and should be reported.
5290   case BuiltinType::BoundMember:
5291   case BuiltinType::BuiltinFn:
5292   case BuiltinType::OMPArraySection:
5293     return true;
5294 
5295   }
5296   llvm_unreachable("bad builtin type kind");
5297 }
5298 
5299 /// Check an argument list for placeholders that we won't try to
5300 /// handle later.
5301 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5302   // Apply this processing to all the arguments at once instead of
5303   // dying at the first failure.
5304   bool hasInvalid = false;
5305   for (size_t i = 0, e = args.size(); i != e; i++) {
5306     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5307       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5308       if (result.isInvalid()) hasInvalid = true;
5309       else args[i] = result.get();
5310     } else if (hasInvalid) {
5311       (void)S.CorrectDelayedTyposInExpr(args[i]);
5312     }
5313   }
5314   return hasInvalid;
5315 }
5316 
5317 /// If a builtin function has a pointer argument with no explicit address
5318 /// space, then it should be able to accept a pointer to any address
5319 /// space as input.  In order to do this, we need to replace the
5320 /// standard builtin declaration with one that uses the same address space
5321 /// as the call.
5322 ///
5323 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5324 ///                  it does not contain any pointer arguments without
5325 ///                  an address space qualifer.  Otherwise the rewritten
5326 ///                  FunctionDecl is returned.
5327 /// TODO: Handle pointer return types.
5328 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5329                                                 const FunctionDecl *FDecl,
5330                                                 MultiExprArg ArgExprs) {
5331 
5332   QualType DeclType = FDecl->getType();
5333   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5334 
5335   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5336       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5337     return nullptr;
5338 
5339   bool NeedsNewDecl = false;
5340   unsigned i = 0;
5341   SmallVector<QualType, 8> OverloadParams;
5342 
5343   for (QualType ParamType : FT->param_types()) {
5344 
5345     // Convert array arguments to pointer to simplify type lookup.
5346     ExprResult ArgRes =
5347         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5348     if (ArgRes.isInvalid())
5349       return nullptr;
5350     Expr *Arg = ArgRes.get();
5351     QualType ArgType = Arg->getType();
5352     if (!ParamType->isPointerType() ||
5353         ParamType.getQualifiers().hasAddressSpace() ||
5354         !ArgType->isPointerType() ||
5355         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5356       OverloadParams.push_back(ParamType);
5357       continue;
5358     }
5359 
5360     QualType PointeeType = ParamType->getPointeeType();
5361     if (PointeeType.getQualifiers().hasAddressSpace())
5362       continue;
5363 
5364     NeedsNewDecl = true;
5365     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5366 
5367     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5368     OverloadParams.push_back(Context.getPointerType(PointeeType));
5369   }
5370 
5371   if (!NeedsNewDecl)
5372     return nullptr;
5373 
5374   FunctionProtoType::ExtProtoInfo EPI;
5375   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5376                                                 OverloadParams, EPI);
5377   DeclContext *Parent = Context.getTranslationUnitDecl();
5378   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5379                                                     FDecl->getLocation(),
5380                                                     FDecl->getLocation(),
5381                                                     FDecl->getIdentifier(),
5382                                                     OverloadTy,
5383                                                     /*TInfo=*/nullptr,
5384                                                     SC_Extern, false,
5385                                                     /*hasPrototype=*/true);
5386   SmallVector<ParmVarDecl*, 16> Params;
5387   FT = cast<FunctionProtoType>(OverloadTy);
5388   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5389     QualType ParamType = FT->getParamType(i);
5390     ParmVarDecl *Parm =
5391         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5392                                 SourceLocation(), nullptr, ParamType,
5393                                 /*TInfo=*/nullptr, SC_None, nullptr);
5394     Parm->setScopeInfo(0, i);
5395     Params.push_back(Parm);
5396   }
5397   OverloadDecl->setParams(Params);
5398   return OverloadDecl;
5399 }
5400 
5401 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5402                                     FunctionDecl *Callee,
5403                                     MultiExprArg ArgExprs) {
5404   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5405   // similar attributes) really don't like it when functions are called with an
5406   // invalid number of args.
5407   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5408                          /*PartialOverloading=*/false) &&
5409       !Callee->isVariadic())
5410     return;
5411   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5412     return;
5413 
5414   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5415     S.Diag(Fn->getBeginLoc(),
5416            isa<CXXMethodDecl>(Callee)
5417                ? diag::err_ovl_no_viable_member_function_in_call
5418                : diag::err_ovl_no_viable_function_in_call)
5419         << Callee << Callee->getSourceRange();
5420     S.Diag(Callee->getLocation(),
5421            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5422         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5423     return;
5424   }
5425 }
5426 
5427 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5428     const UnresolvedMemberExpr *const UME, Sema &S) {
5429 
5430   const auto GetFunctionLevelDCIfCXXClass =
5431       [](Sema &S) -> const CXXRecordDecl * {
5432     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5433     if (!DC || !DC->getParent())
5434       return nullptr;
5435 
5436     // If the call to some member function was made from within a member
5437     // function body 'M' return return 'M's parent.
5438     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5439       return MD->getParent()->getCanonicalDecl();
5440     // else the call was made from within a default member initializer of a
5441     // class, so return the class.
5442     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5443       return RD->getCanonicalDecl();
5444     return nullptr;
5445   };
5446   // If our DeclContext is neither a member function nor a class (in the
5447   // case of a lambda in a default member initializer), we can't have an
5448   // enclosing 'this'.
5449 
5450   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5451   if (!CurParentClass)
5452     return false;
5453 
5454   // The naming class for implicit member functions call is the class in which
5455   // name lookup starts.
5456   const CXXRecordDecl *const NamingClass =
5457       UME->getNamingClass()->getCanonicalDecl();
5458   assert(NamingClass && "Must have naming class even for implicit access");
5459 
5460   // If the unresolved member functions were found in a 'naming class' that is
5461   // related (either the same or derived from) to the class that contains the
5462   // member function that itself contained the implicit member access.
5463 
5464   return CurParentClass == NamingClass ||
5465          CurParentClass->isDerivedFrom(NamingClass);
5466 }
5467 
5468 static void
5469 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5470     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5471 
5472   if (!UME)
5473     return;
5474 
5475   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5476   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5477   // already been captured, or if this is an implicit member function call (if
5478   // it isn't, an attempt to capture 'this' should already have been made).
5479   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5480       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5481     return;
5482 
5483   // Check if the naming class in which the unresolved members were found is
5484   // related (same as or is a base of) to the enclosing class.
5485 
5486   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5487     return;
5488 
5489 
5490   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5491   // If the enclosing function is not dependent, then this lambda is
5492   // capture ready, so if we can capture this, do so.
5493   if (!EnclosingFunctionCtx->isDependentContext()) {
5494     // If the current lambda and all enclosing lambdas can capture 'this' -
5495     // then go ahead and capture 'this' (since our unresolved overload set
5496     // contains at least one non-static member function).
5497     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5498       S.CheckCXXThisCapture(CallLoc);
5499   } else if (S.CurContext->isDependentContext()) {
5500     // ... since this is an implicit member reference, that might potentially
5501     // involve a 'this' capture, mark 'this' for potential capture in
5502     // enclosing lambdas.
5503     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5504       CurLSI->addPotentialThisCapture(CallLoc);
5505   }
5506 }
5507 
5508 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5509                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5510                                Expr *ExecConfig) {
5511   ExprResult Call =
5512       BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5513   if (Call.isInvalid())
5514     return Call;
5515 
5516   // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5517   // language modes.
5518   if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5519     if (ULE->hasExplicitTemplateArgs() &&
5520         ULE->decls_begin() == ULE->decls_end()) {
5521       Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5522                                  ? diag::warn_cxx17_compat_adl_only_template_id
5523                                  : diag::ext_adl_only_template_id)
5524           << ULE->getName();
5525     }
5526   }
5527 
5528   return Call;
5529 }
5530 
5531 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5532 /// This provides the location of the left/right parens and a list of comma
5533 /// locations.
5534 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5535                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5536                                Expr *ExecConfig, bool IsExecConfig) {
5537   // Since this might be a postfix expression, get rid of ParenListExprs.
5538   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5539   if (Result.isInvalid()) return ExprError();
5540   Fn = Result.get();
5541 
5542   if (checkArgsForPlaceholders(*this, ArgExprs))
5543     return ExprError();
5544 
5545   if (getLangOpts().CPlusPlus) {
5546     // If this is a pseudo-destructor expression, build the call immediately.
5547     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5548       if (!ArgExprs.empty()) {
5549         // Pseudo-destructor calls should not have any arguments.
5550         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5551             << FixItHint::CreateRemoval(
5552                    SourceRange(ArgExprs.front()->getBeginLoc(),
5553                                ArgExprs.back()->getEndLoc()));
5554       }
5555 
5556       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5557                               VK_RValue, RParenLoc);
5558     }
5559     if (Fn->getType() == Context.PseudoObjectTy) {
5560       ExprResult result = CheckPlaceholderExpr(Fn);
5561       if (result.isInvalid()) return ExprError();
5562       Fn = result.get();
5563     }
5564 
5565     // Determine whether this is a dependent call inside a C++ template,
5566     // in which case we won't do any semantic analysis now.
5567     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5568       if (ExecConfig) {
5569         return CUDAKernelCallExpr::Create(
5570             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5571             Context.DependentTy, VK_RValue, RParenLoc);
5572       } else {
5573 
5574         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5575             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5576             Fn->getBeginLoc());
5577 
5578         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5579                                 VK_RValue, RParenLoc);
5580       }
5581     }
5582 
5583     // Determine whether this is a call to an object (C++ [over.call.object]).
5584     if (Fn->getType()->isRecordType())
5585       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5586                                           RParenLoc);
5587 
5588     if (Fn->getType() == Context.UnknownAnyTy) {
5589       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5590       if (result.isInvalid()) return ExprError();
5591       Fn = result.get();
5592     }
5593 
5594     if (Fn->getType() == Context.BoundMemberTy) {
5595       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5596                                        RParenLoc);
5597     }
5598   }
5599 
5600   // Check for overloaded calls.  This can happen even in C due to extensions.
5601   if (Fn->getType() == Context.OverloadTy) {
5602     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5603 
5604     // We aren't supposed to apply this logic if there's an '&' involved.
5605     if (!find.HasFormOfMemberPointer) {
5606       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5607         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5608                                 VK_RValue, RParenLoc);
5609       OverloadExpr *ovl = find.Expression;
5610       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5611         return BuildOverloadedCallExpr(
5612             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5613             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5614       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5615                                        RParenLoc);
5616     }
5617   }
5618 
5619   // If we're directly calling a function, get the appropriate declaration.
5620   if (Fn->getType() == Context.UnknownAnyTy) {
5621     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5622     if (result.isInvalid()) return ExprError();
5623     Fn = result.get();
5624   }
5625 
5626   Expr *NakedFn = Fn->IgnoreParens();
5627 
5628   bool CallingNDeclIndirectly = false;
5629   NamedDecl *NDecl = nullptr;
5630   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5631     if (UnOp->getOpcode() == UO_AddrOf) {
5632       CallingNDeclIndirectly = true;
5633       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5634     }
5635   }
5636 
5637   if (isa<DeclRefExpr>(NakedFn)) {
5638     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5639 
5640     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5641     if (FDecl && FDecl->getBuiltinID()) {
5642       // Rewrite the function decl for this builtin by replacing parameters
5643       // with no explicit address space with the address space of the arguments
5644       // in ArgExprs.
5645       if ((FDecl =
5646                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5647         NDecl = FDecl;
5648         Fn = DeclRefExpr::Create(
5649             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5650             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5651       }
5652     }
5653   } else if (isa<MemberExpr>(NakedFn))
5654     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5655 
5656   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5657     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5658                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5659       return ExprError();
5660 
5661     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5662       return ExprError();
5663 
5664     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5665   }
5666 
5667   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5668                                ExecConfig, IsExecConfig);
5669 }
5670 
5671 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5672 ///
5673 /// __builtin_astype( value, dst type )
5674 ///
5675 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5676                                  SourceLocation BuiltinLoc,
5677                                  SourceLocation RParenLoc) {
5678   ExprValueKind VK = VK_RValue;
5679   ExprObjectKind OK = OK_Ordinary;
5680   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5681   QualType SrcTy = E->getType();
5682   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5683     return ExprError(Diag(BuiltinLoc,
5684                           diag::err_invalid_astype_of_different_size)
5685                      << DstTy
5686                      << SrcTy
5687                      << E->getSourceRange());
5688   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5689 }
5690 
5691 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5692 /// provided arguments.
5693 ///
5694 /// __builtin_convertvector( value, dst type )
5695 ///
5696 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5697                                         SourceLocation BuiltinLoc,
5698                                         SourceLocation RParenLoc) {
5699   TypeSourceInfo *TInfo;
5700   GetTypeFromParser(ParsedDestTy, &TInfo);
5701   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5702 }
5703 
5704 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5705 /// i.e. an expression not of \p OverloadTy.  The expression should
5706 /// unary-convert to an expression of function-pointer or
5707 /// block-pointer type.
5708 ///
5709 /// \param NDecl the declaration being called, if available
5710 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5711                                        SourceLocation LParenLoc,
5712                                        ArrayRef<Expr *> Args,
5713                                        SourceLocation RParenLoc, Expr *Config,
5714                                        bool IsExecConfig, ADLCallKind UsesADL) {
5715   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5716   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5717 
5718   // Functions with 'interrupt' attribute cannot be called directly.
5719   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5720     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5721     return ExprError();
5722   }
5723 
5724   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5725   // so there's some risk when calling out to non-interrupt handler functions
5726   // that the callee might not preserve them. This is easy to diagnose here,
5727   // but can be very challenging to debug.
5728   if (auto *Caller = getCurFunctionDecl())
5729     if (Caller->hasAttr<ARMInterruptAttr>()) {
5730       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5731       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5732         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5733     }
5734 
5735   // Promote the function operand.
5736   // We special-case function promotion here because we only allow promoting
5737   // builtin functions to function pointers in the callee of a call.
5738   ExprResult Result;
5739   QualType ResultTy;
5740   if (BuiltinID &&
5741       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5742     // Extract the return type from the (builtin) function pointer type.
5743     // FIXME Several builtins still have setType in
5744     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5745     // Builtins.def to ensure they are correct before removing setType calls.
5746     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5747     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5748     ResultTy = FDecl->getCallResultType();
5749   } else {
5750     Result = CallExprUnaryConversions(Fn);
5751     ResultTy = Context.BoolTy;
5752   }
5753   if (Result.isInvalid())
5754     return ExprError();
5755   Fn = Result.get();
5756 
5757   // Check for a valid function type, but only if it is not a builtin which
5758   // requires custom type checking. These will be handled by
5759   // CheckBuiltinFunctionCall below just after creation of the call expression.
5760   const FunctionType *FuncT = nullptr;
5761   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5762    retry:
5763     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5764       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5765       // have type pointer to function".
5766       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5767       if (!FuncT)
5768         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5769                            << Fn->getType() << Fn->getSourceRange());
5770     } else if (const BlockPointerType *BPT =
5771                  Fn->getType()->getAs<BlockPointerType>()) {
5772       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5773     } else {
5774       // Handle calls to expressions of unknown-any type.
5775       if (Fn->getType() == Context.UnknownAnyTy) {
5776         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5777         if (rewrite.isInvalid()) return ExprError();
5778         Fn = rewrite.get();
5779         goto retry;
5780       }
5781 
5782     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5783       << Fn->getType() << Fn->getSourceRange());
5784     }
5785   }
5786 
5787   // Get the number of parameters in the function prototype, if any.
5788   // We will allocate space for max(Args.size(), NumParams) arguments
5789   // in the call expression.
5790   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5791   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5792 
5793   CallExpr *TheCall;
5794   if (Config) {
5795     assert(UsesADL == ADLCallKind::NotADL &&
5796            "CUDAKernelCallExpr should not use ADL");
5797     TheCall =
5798         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5799                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5800   } else {
5801     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5802                                RParenLoc, NumParams, UsesADL);
5803   }
5804 
5805   if (!getLangOpts().CPlusPlus) {
5806     // Forget about the nulled arguments since typo correction
5807     // do not handle them well.
5808     TheCall->shrinkNumArgs(Args.size());
5809     // C cannot always handle TypoExpr nodes in builtin calls and direct
5810     // function calls as their argument checking don't necessarily handle
5811     // dependent types properly, so make sure any TypoExprs have been
5812     // dealt with.
5813     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5814     if (!Result.isUsable()) return ExprError();
5815     CallExpr *TheOldCall = TheCall;
5816     TheCall = dyn_cast<CallExpr>(Result.get());
5817     bool CorrectedTypos = TheCall != TheOldCall;
5818     if (!TheCall) return Result;
5819     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5820 
5821     // A new call expression node was created if some typos were corrected.
5822     // However it may not have been constructed with enough storage. In this
5823     // case, rebuild the node with enough storage. The waste of space is
5824     // immaterial since this only happens when some typos were corrected.
5825     if (CorrectedTypos && Args.size() < NumParams) {
5826       if (Config)
5827         TheCall = CUDAKernelCallExpr::Create(
5828             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5829             RParenLoc, NumParams);
5830       else
5831         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5832                                    RParenLoc, NumParams, UsesADL);
5833     }
5834     // We can now handle the nulled arguments for the default arguments.
5835     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5836   }
5837 
5838   // Bail out early if calling a builtin with custom type checking.
5839   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5840     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5841 
5842   if (getLangOpts().CUDA) {
5843     if (Config) {
5844       // CUDA: Kernel calls must be to global functions
5845       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5846         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5847             << FDecl << Fn->getSourceRange());
5848 
5849       // CUDA: Kernel function must have 'void' return type
5850       if (!FuncT->getReturnType()->isVoidType())
5851         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5852             << Fn->getType() << Fn->getSourceRange());
5853     } else {
5854       // CUDA: Calls to global functions must be configured
5855       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5856         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5857             << FDecl << Fn->getSourceRange());
5858     }
5859   }
5860 
5861   // Check for a valid return type
5862   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5863                           FDecl))
5864     return ExprError();
5865 
5866   // We know the result type of the call, set it.
5867   TheCall->setType(FuncT->getCallResultType(Context));
5868   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5869 
5870   if (Proto) {
5871     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5872                                 IsExecConfig))
5873       return ExprError();
5874   } else {
5875     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5876 
5877     if (FDecl) {
5878       // Check if we have too few/too many template arguments, based
5879       // on our knowledge of the function definition.
5880       const FunctionDecl *Def = nullptr;
5881       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5882         Proto = Def->getType()->getAs<FunctionProtoType>();
5883        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5884           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5885           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5886       }
5887 
5888       // If the function we're calling isn't a function prototype, but we have
5889       // a function prototype from a prior declaratiom, use that prototype.
5890       if (!FDecl->hasPrototype())
5891         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5892     }
5893 
5894     // Promote the arguments (C99 6.5.2.2p6).
5895     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5896       Expr *Arg = Args[i];
5897 
5898       if (Proto && i < Proto->getNumParams()) {
5899         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5900             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5901         ExprResult ArgE =
5902             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5903         if (ArgE.isInvalid())
5904           return true;
5905 
5906         Arg = ArgE.getAs<Expr>();
5907 
5908       } else {
5909         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5910 
5911         if (ArgE.isInvalid())
5912           return true;
5913 
5914         Arg = ArgE.getAs<Expr>();
5915       }
5916 
5917       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5918                               diag::err_call_incomplete_argument, Arg))
5919         return ExprError();
5920 
5921       TheCall->setArg(i, Arg);
5922     }
5923   }
5924 
5925   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5926     if (!Method->isStatic())
5927       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5928         << Fn->getSourceRange());
5929 
5930   // Check for sentinels
5931   if (NDecl)
5932     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5933 
5934   // Do special checking on direct calls to functions.
5935   if (FDecl) {
5936     if (CheckFunctionCall(FDecl, TheCall, Proto))
5937       return ExprError();
5938 
5939     checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
5940 
5941     if (BuiltinID)
5942       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5943   } else if (NDecl) {
5944     if (CheckPointerCall(NDecl, TheCall, Proto))
5945       return ExprError();
5946   } else {
5947     if (CheckOtherCall(TheCall, Proto))
5948       return ExprError();
5949   }
5950 
5951   return MaybeBindToTemporary(TheCall);
5952 }
5953 
5954 ExprResult
5955 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5956                            SourceLocation RParenLoc, Expr *InitExpr) {
5957   assert(Ty && "ActOnCompoundLiteral(): missing type");
5958   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5959 
5960   TypeSourceInfo *TInfo;
5961   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5962   if (!TInfo)
5963     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5964 
5965   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5966 }
5967 
5968 ExprResult
5969 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5970                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5971   QualType literalType = TInfo->getType();
5972 
5973   if (literalType->isArrayType()) {
5974     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5975           diag::err_illegal_decl_array_incomplete_type,
5976           SourceRange(LParenLoc,
5977                       LiteralExpr->getSourceRange().getEnd())))
5978       return ExprError();
5979     if (literalType->isVariableArrayType())
5980       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5981         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5982   } else if (!literalType->isDependentType() &&
5983              RequireCompleteType(LParenLoc, literalType,
5984                diag::err_typecheck_decl_incomplete_type,
5985                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5986     return ExprError();
5987 
5988   InitializedEntity Entity
5989     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5990   InitializationKind Kind
5991     = InitializationKind::CreateCStyleCast(LParenLoc,
5992                                            SourceRange(LParenLoc, RParenLoc),
5993                                            /*InitList=*/true);
5994   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5995   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5996                                       &literalType);
5997   if (Result.isInvalid())
5998     return ExprError();
5999   LiteralExpr = Result.get();
6000 
6001   bool isFileScope = !CurContext->isFunctionOrMethod();
6002 
6003   // In C, compound literals are l-values for some reason.
6004   // For GCC compatibility, in C++, file-scope array compound literals with
6005   // constant initializers are also l-values, and compound literals are
6006   // otherwise prvalues.
6007   //
6008   // (GCC also treats C++ list-initialized file-scope array prvalues with
6009   // constant initializers as l-values, but that's non-conforming, so we don't
6010   // follow it there.)
6011   //
6012   // FIXME: It would be better to handle the lvalue cases as materializing and
6013   // lifetime-extending a temporary object, but our materialized temporaries
6014   // representation only supports lifetime extension from a variable, not "out
6015   // of thin air".
6016   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6017   // is bound to the result of applying array-to-pointer decay to the compound
6018   // literal.
6019   // FIXME: GCC supports compound literals of reference type, which should
6020   // obviously have a value kind derived from the kind of reference involved.
6021   ExprValueKind VK =
6022       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6023           ? VK_RValue
6024           : VK_LValue;
6025 
6026   if (isFileScope)
6027     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6028       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6029         Expr *Init = ILE->getInit(i);
6030         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6031       }
6032 
6033   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6034                                               VK, LiteralExpr, isFileScope);
6035   if (isFileScope) {
6036     if (!LiteralExpr->isTypeDependent() &&
6037         !LiteralExpr->isValueDependent() &&
6038         !literalType->isDependentType()) // C99 6.5.2.5p3
6039       if (CheckForConstantInitializer(LiteralExpr, literalType))
6040         return ExprError();
6041   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6042              literalType.getAddressSpace() != LangAS::Default) {
6043     // Embedded-C extensions to C99 6.5.2.5:
6044     //   "If the compound literal occurs inside the body of a function, the
6045     //   type name shall not be qualified by an address-space qualifier."
6046     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6047       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6048     return ExprError();
6049   }
6050 
6051   return MaybeBindToTemporary(E);
6052 }
6053 
6054 ExprResult
6055 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6056                     SourceLocation RBraceLoc) {
6057   // Immediately handle non-overload placeholders.  Overloads can be
6058   // resolved contextually, but everything else here can't.
6059   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6060     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6061       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6062 
6063       // Ignore failures; dropping the entire initializer list because
6064       // of one failure would be terrible for indexing/etc.
6065       if (result.isInvalid()) continue;
6066 
6067       InitArgList[I] = result.get();
6068     }
6069   }
6070 
6071   // Semantic analysis for initializers is done by ActOnDeclarator() and
6072   // CheckInitializer() - it requires knowledge of the object being initialized.
6073 
6074   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6075                                                RBraceLoc);
6076   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6077   return E;
6078 }
6079 
6080 /// Do an explicit extend of the given block pointer if we're in ARC.
6081 void Sema::maybeExtendBlockObject(ExprResult &E) {
6082   assert(E.get()->getType()->isBlockPointerType());
6083   assert(E.get()->isRValue());
6084 
6085   // Only do this in an r-value context.
6086   if (!getLangOpts().ObjCAutoRefCount) return;
6087 
6088   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6089                                CK_ARCExtendBlockObject, E.get(),
6090                                /*base path*/ nullptr, VK_RValue);
6091   Cleanup.setExprNeedsCleanups(true);
6092 }
6093 
6094 /// Prepare a conversion of the given expression to an ObjC object
6095 /// pointer type.
6096 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6097   QualType type = E.get()->getType();
6098   if (type->isObjCObjectPointerType()) {
6099     return CK_BitCast;
6100   } else if (type->isBlockPointerType()) {
6101     maybeExtendBlockObject(E);
6102     return CK_BlockPointerToObjCPointerCast;
6103   } else {
6104     assert(type->isPointerType());
6105     return CK_CPointerToObjCPointerCast;
6106   }
6107 }
6108 
6109 /// Prepares for a scalar cast, performing all the necessary stages
6110 /// except the final cast and returning the kind required.
6111 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6112   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6113   // Also, callers should have filtered out the invalid cases with
6114   // pointers.  Everything else should be possible.
6115 
6116   QualType SrcTy = Src.get()->getType();
6117   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6118     return CK_NoOp;
6119 
6120   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6121   case Type::STK_MemberPointer:
6122     llvm_unreachable("member pointer type in C");
6123 
6124   case Type::STK_CPointer:
6125   case Type::STK_BlockPointer:
6126   case Type::STK_ObjCObjectPointer:
6127     switch (DestTy->getScalarTypeKind()) {
6128     case Type::STK_CPointer: {
6129       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6130       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6131       if (SrcAS != DestAS)
6132         return CK_AddressSpaceConversion;
6133       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6134         return CK_NoOp;
6135       return CK_BitCast;
6136     }
6137     case Type::STK_BlockPointer:
6138       return (SrcKind == Type::STK_BlockPointer
6139                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6140     case Type::STK_ObjCObjectPointer:
6141       if (SrcKind == Type::STK_ObjCObjectPointer)
6142         return CK_BitCast;
6143       if (SrcKind == Type::STK_CPointer)
6144         return CK_CPointerToObjCPointerCast;
6145       maybeExtendBlockObject(Src);
6146       return CK_BlockPointerToObjCPointerCast;
6147     case Type::STK_Bool:
6148       return CK_PointerToBoolean;
6149     case Type::STK_Integral:
6150       return CK_PointerToIntegral;
6151     case Type::STK_Floating:
6152     case Type::STK_FloatingComplex:
6153     case Type::STK_IntegralComplex:
6154     case Type::STK_MemberPointer:
6155     case Type::STK_FixedPoint:
6156       llvm_unreachable("illegal cast from pointer");
6157     }
6158     llvm_unreachable("Should have returned before this");
6159 
6160   case Type::STK_FixedPoint:
6161     switch (DestTy->getScalarTypeKind()) {
6162     case Type::STK_FixedPoint:
6163       return CK_FixedPointCast;
6164     case Type::STK_Bool:
6165       return CK_FixedPointToBoolean;
6166     case Type::STK_Integral:
6167       return CK_FixedPointToIntegral;
6168     case Type::STK_Floating:
6169     case Type::STK_IntegralComplex:
6170     case Type::STK_FloatingComplex:
6171       Diag(Src.get()->getExprLoc(),
6172            diag::err_unimplemented_conversion_with_fixed_point_type)
6173           << DestTy;
6174       return CK_IntegralCast;
6175     case Type::STK_CPointer:
6176     case Type::STK_ObjCObjectPointer:
6177     case Type::STK_BlockPointer:
6178     case Type::STK_MemberPointer:
6179       llvm_unreachable("illegal cast to pointer type");
6180     }
6181     llvm_unreachable("Should have returned before this");
6182 
6183   case Type::STK_Bool: // casting from bool is like casting from an integer
6184   case Type::STK_Integral:
6185     switch (DestTy->getScalarTypeKind()) {
6186     case Type::STK_CPointer:
6187     case Type::STK_ObjCObjectPointer:
6188     case Type::STK_BlockPointer:
6189       if (Src.get()->isNullPointerConstant(Context,
6190                                            Expr::NPC_ValueDependentIsNull))
6191         return CK_NullToPointer;
6192       return CK_IntegralToPointer;
6193     case Type::STK_Bool:
6194       return CK_IntegralToBoolean;
6195     case Type::STK_Integral:
6196       return CK_IntegralCast;
6197     case Type::STK_Floating:
6198       return CK_IntegralToFloating;
6199     case Type::STK_IntegralComplex:
6200       Src = ImpCastExprToType(Src.get(),
6201                       DestTy->castAs<ComplexType>()->getElementType(),
6202                       CK_IntegralCast);
6203       return CK_IntegralRealToComplex;
6204     case Type::STK_FloatingComplex:
6205       Src = ImpCastExprToType(Src.get(),
6206                       DestTy->castAs<ComplexType>()->getElementType(),
6207                       CK_IntegralToFloating);
6208       return CK_FloatingRealToComplex;
6209     case Type::STK_MemberPointer:
6210       llvm_unreachable("member pointer type in C");
6211     case Type::STK_FixedPoint:
6212       return CK_IntegralToFixedPoint;
6213     }
6214     llvm_unreachable("Should have returned before this");
6215 
6216   case Type::STK_Floating:
6217     switch (DestTy->getScalarTypeKind()) {
6218     case Type::STK_Floating:
6219       return CK_FloatingCast;
6220     case Type::STK_Bool:
6221       return CK_FloatingToBoolean;
6222     case Type::STK_Integral:
6223       return CK_FloatingToIntegral;
6224     case Type::STK_FloatingComplex:
6225       Src = ImpCastExprToType(Src.get(),
6226                               DestTy->castAs<ComplexType>()->getElementType(),
6227                               CK_FloatingCast);
6228       return CK_FloatingRealToComplex;
6229     case Type::STK_IntegralComplex:
6230       Src = ImpCastExprToType(Src.get(),
6231                               DestTy->castAs<ComplexType>()->getElementType(),
6232                               CK_FloatingToIntegral);
6233       return CK_IntegralRealToComplex;
6234     case Type::STK_CPointer:
6235     case Type::STK_ObjCObjectPointer:
6236     case Type::STK_BlockPointer:
6237       llvm_unreachable("valid float->pointer cast?");
6238     case Type::STK_MemberPointer:
6239       llvm_unreachable("member pointer type in C");
6240     case Type::STK_FixedPoint:
6241       Diag(Src.get()->getExprLoc(),
6242            diag::err_unimplemented_conversion_with_fixed_point_type)
6243           << SrcTy;
6244       return CK_IntegralCast;
6245     }
6246     llvm_unreachable("Should have returned before this");
6247 
6248   case Type::STK_FloatingComplex:
6249     switch (DestTy->getScalarTypeKind()) {
6250     case Type::STK_FloatingComplex:
6251       return CK_FloatingComplexCast;
6252     case Type::STK_IntegralComplex:
6253       return CK_FloatingComplexToIntegralComplex;
6254     case Type::STK_Floating: {
6255       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6256       if (Context.hasSameType(ET, DestTy))
6257         return CK_FloatingComplexToReal;
6258       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6259       return CK_FloatingCast;
6260     }
6261     case Type::STK_Bool:
6262       return CK_FloatingComplexToBoolean;
6263     case Type::STK_Integral:
6264       Src = ImpCastExprToType(Src.get(),
6265                               SrcTy->castAs<ComplexType>()->getElementType(),
6266                               CK_FloatingComplexToReal);
6267       return CK_FloatingToIntegral;
6268     case Type::STK_CPointer:
6269     case Type::STK_ObjCObjectPointer:
6270     case Type::STK_BlockPointer:
6271       llvm_unreachable("valid complex float->pointer cast?");
6272     case Type::STK_MemberPointer:
6273       llvm_unreachable("member pointer type in C");
6274     case Type::STK_FixedPoint:
6275       Diag(Src.get()->getExprLoc(),
6276            diag::err_unimplemented_conversion_with_fixed_point_type)
6277           << SrcTy;
6278       return CK_IntegralCast;
6279     }
6280     llvm_unreachable("Should have returned before this");
6281 
6282   case Type::STK_IntegralComplex:
6283     switch (DestTy->getScalarTypeKind()) {
6284     case Type::STK_FloatingComplex:
6285       return CK_IntegralComplexToFloatingComplex;
6286     case Type::STK_IntegralComplex:
6287       return CK_IntegralComplexCast;
6288     case Type::STK_Integral: {
6289       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6290       if (Context.hasSameType(ET, DestTy))
6291         return CK_IntegralComplexToReal;
6292       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6293       return CK_IntegralCast;
6294     }
6295     case Type::STK_Bool:
6296       return CK_IntegralComplexToBoolean;
6297     case Type::STK_Floating:
6298       Src = ImpCastExprToType(Src.get(),
6299                               SrcTy->castAs<ComplexType>()->getElementType(),
6300                               CK_IntegralComplexToReal);
6301       return CK_IntegralToFloating;
6302     case Type::STK_CPointer:
6303     case Type::STK_ObjCObjectPointer:
6304     case Type::STK_BlockPointer:
6305       llvm_unreachable("valid complex int->pointer cast?");
6306     case Type::STK_MemberPointer:
6307       llvm_unreachable("member pointer type in C");
6308     case Type::STK_FixedPoint:
6309       Diag(Src.get()->getExprLoc(),
6310            diag::err_unimplemented_conversion_with_fixed_point_type)
6311           << SrcTy;
6312       return CK_IntegralCast;
6313     }
6314     llvm_unreachable("Should have returned before this");
6315   }
6316 
6317   llvm_unreachable("Unhandled scalar cast");
6318 }
6319 
6320 static bool breakDownVectorType(QualType type, uint64_t &len,
6321                                 QualType &eltType) {
6322   // Vectors are simple.
6323   if (const VectorType *vecType = type->getAs<VectorType>()) {
6324     len = vecType->getNumElements();
6325     eltType = vecType->getElementType();
6326     assert(eltType->isScalarType());
6327     return true;
6328   }
6329 
6330   // We allow lax conversion to and from non-vector types, but only if
6331   // they're real types (i.e. non-complex, non-pointer scalar types).
6332   if (!type->isRealType()) return false;
6333 
6334   len = 1;
6335   eltType = type;
6336   return true;
6337 }
6338 
6339 /// Are the two types lax-compatible vector types?  That is, given
6340 /// that one of them is a vector, do they have equal storage sizes,
6341 /// where the storage size is the number of elements times the element
6342 /// size?
6343 ///
6344 /// This will also return false if either of the types is neither a
6345 /// vector nor a real type.
6346 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6347   assert(destTy->isVectorType() || srcTy->isVectorType());
6348 
6349   // Disallow lax conversions between scalars and ExtVectors (these
6350   // conversions are allowed for other vector types because common headers
6351   // depend on them).  Most scalar OP ExtVector cases are handled by the
6352   // splat path anyway, which does what we want (convert, not bitcast).
6353   // What this rules out for ExtVectors is crazy things like char4*float.
6354   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6355   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6356 
6357   uint64_t srcLen, destLen;
6358   QualType srcEltTy, destEltTy;
6359   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6360   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6361 
6362   // ASTContext::getTypeSize will return the size rounded up to a
6363   // power of 2, so instead of using that, we need to use the raw
6364   // element size multiplied by the element count.
6365   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6366   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6367 
6368   return (srcLen * srcEltSize == destLen * destEltSize);
6369 }
6370 
6371 /// Is this a legal conversion between two types, one of which is
6372 /// known to be a vector type?
6373 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6374   assert(destTy->isVectorType() || srcTy->isVectorType());
6375 
6376   if (!Context.getLangOpts().LaxVectorConversions)
6377     return false;
6378   return areLaxCompatibleVectorTypes(srcTy, destTy);
6379 }
6380 
6381 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6382                            CastKind &Kind) {
6383   assert(VectorTy->isVectorType() && "Not a vector type!");
6384 
6385   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6386     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6387       return Diag(R.getBegin(),
6388                   Ty->isVectorType() ?
6389                   diag::err_invalid_conversion_between_vectors :
6390                   diag::err_invalid_conversion_between_vector_and_integer)
6391         << VectorTy << Ty << R;
6392   } else
6393     return Diag(R.getBegin(),
6394                 diag::err_invalid_conversion_between_vector_and_scalar)
6395       << VectorTy << Ty << R;
6396 
6397   Kind = CK_BitCast;
6398   return false;
6399 }
6400 
6401 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6402   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6403 
6404   if (DestElemTy == SplattedExpr->getType())
6405     return SplattedExpr;
6406 
6407   assert(DestElemTy->isFloatingType() ||
6408          DestElemTy->isIntegralOrEnumerationType());
6409 
6410   CastKind CK;
6411   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6412     // OpenCL requires that we convert `true` boolean expressions to -1, but
6413     // only when splatting vectors.
6414     if (DestElemTy->isFloatingType()) {
6415       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6416       // in two steps: boolean to signed integral, then to floating.
6417       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6418                                                  CK_BooleanToSignedIntegral);
6419       SplattedExpr = CastExprRes.get();
6420       CK = CK_IntegralToFloating;
6421     } else {
6422       CK = CK_BooleanToSignedIntegral;
6423     }
6424   } else {
6425     ExprResult CastExprRes = SplattedExpr;
6426     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6427     if (CastExprRes.isInvalid())
6428       return ExprError();
6429     SplattedExpr = CastExprRes.get();
6430   }
6431   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6432 }
6433 
6434 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6435                                     Expr *CastExpr, CastKind &Kind) {
6436   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6437 
6438   QualType SrcTy = CastExpr->getType();
6439 
6440   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6441   // an ExtVectorType.
6442   // In OpenCL, casts between vectors of different types are not allowed.
6443   // (See OpenCL 6.2).
6444   if (SrcTy->isVectorType()) {
6445     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6446         (getLangOpts().OpenCL &&
6447          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6448       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6449         << DestTy << SrcTy << R;
6450       return ExprError();
6451     }
6452     Kind = CK_BitCast;
6453     return CastExpr;
6454   }
6455 
6456   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6457   // conversion will take place first from scalar to elt type, and then
6458   // splat from elt type to vector.
6459   if (SrcTy->isPointerType())
6460     return Diag(R.getBegin(),
6461                 diag::err_invalid_conversion_between_vector_and_scalar)
6462       << DestTy << SrcTy << R;
6463 
6464   Kind = CK_VectorSplat;
6465   return prepareVectorSplat(DestTy, CastExpr);
6466 }
6467 
6468 ExprResult
6469 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6470                     Declarator &D, ParsedType &Ty,
6471                     SourceLocation RParenLoc, Expr *CastExpr) {
6472   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6473          "ActOnCastExpr(): missing type or expr");
6474 
6475   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6476   if (D.isInvalidType())
6477     return ExprError();
6478 
6479   if (getLangOpts().CPlusPlus) {
6480     // Check that there are no default arguments (C++ only).
6481     CheckExtraCXXDefaultArguments(D);
6482   } else {
6483     // Make sure any TypoExprs have been dealt with.
6484     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6485     if (!Res.isUsable())
6486       return ExprError();
6487     CastExpr = Res.get();
6488   }
6489 
6490   checkUnusedDeclAttributes(D);
6491 
6492   QualType castType = castTInfo->getType();
6493   Ty = CreateParsedType(castType, castTInfo);
6494 
6495   bool isVectorLiteral = false;
6496 
6497   // Check for an altivec or OpenCL literal,
6498   // i.e. all the elements are integer constants.
6499   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6500   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6501   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6502        && castType->isVectorType() && (PE || PLE)) {
6503     if (PLE && PLE->getNumExprs() == 0) {
6504       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6505       return ExprError();
6506     }
6507     if (PE || PLE->getNumExprs() == 1) {
6508       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6509       if (!E->getType()->isVectorType())
6510         isVectorLiteral = true;
6511     }
6512     else
6513       isVectorLiteral = true;
6514   }
6515 
6516   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6517   // then handle it as such.
6518   if (isVectorLiteral)
6519     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6520 
6521   // If the Expr being casted is a ParenListExpr, handle it specially.
6522   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6523   // sequence of BinOp comma operators.
6524   if (isa<ParenListExpr>(CastExpr)) {
6525     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6526     if (Result.isInvalid()) return ExprError();
6527     CastExpr = Result.get();
6528   }
6529 
6530   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6531       !getSourceManager().isInSystemMacro(LParenLoc))
6532     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6533 
6534   CheckTollFreeBridgeCast(castType, CastExpr);
6535 
6536   CheckObjCBridgeRelatedCast(castType, CastExpr);
6537 
6538   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6539 
6540   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6541 }
6542 
6543 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6544                                     SourceLocation RParenLoc, Expr *E,
6545                                     TypeSourceInfo *TInfo) {
6546   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6547          "Expected paren or paren list expression");
6548 
6549   Expr **exprs;
6550   unsigned numExprs;
6551   Expr *subExpr;
6552   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6553   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6554     LiteralLParenLoc = PE->getLParenLoc();
6555     LiteralRParenLoc = PE->getRParenLoc();
6556     exprs = PE->getExprs();
6557     numExprs = PE->getNumExprs();
6558   } else { // isa<ParenExpr> by assertion at function entrance
6559     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6560     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6561     subExpr = cast<ParenExpr>(E)->getSubExpr();
6562     exprs = &subExpr;
6563     numExprs = 1;
6564   }
6565 
6566   QualType Ty = TInfo->getType();
6567   assert(Ty->isVectorType() && "Expected vector type");
6568 
6569   SmallVector<Expr *, 8> initExprs;
6570   const VectorType *VTy = Ty->getAs<VectorType>();
6571   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6572 
6573   // '(...)' form of vector initialization in AltiVec: the number of
6574   // initializers must be one or must match the size of the vector.
6575   // If a single value is specified in the initializer then it will be
6576   // replicated to all the components of the vector
6577   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6578     // The number of initializers must be one or must match the size of the
6579     // vector. If a single value is specified in the initializer then it will
6580     // be replicated to all the components of the vector
6581     if (numExprs == 1) {
6582       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6583       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6584       if (Literal.isInvalid())
6585         return ExprError();
6586       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6587                                   PrepareScalarCast(Literal, ElemTy));
6588       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6589     }
6590     else if (numExprs < numElems) {
6591       Diag(E->getExprLoc(),
6592            diag::err_incorrect_number_of_vector_initializers);
6593       return ExprError();
6594     }
6595     else
6596       initExprs.append(exprs, exprs + numExprs);
6597   }
6598   else {
6599     // For OpenCL, when the number of initializers is a single value,
6600     // it will be replicated to all components of the vector.
6601     if (getLangOpts().OpenCL &&
6602         VTy->getVectorKind() == VectorType::GenericVector &&
6603         numExprs == 1) {
6604         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6605         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6606         if (Literal.isInvalid())
6607           return ExprError();
6608         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6609                                     PrepareScalarCast(Literal, ElemTy));
6610         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6611     }
6612 
6613     initExprs.append(exprs, exprs + numExprs);
6614   }
6615   // FIXME: This means that pretty-printing the final AST will produce curly
6616   // braces instead of the original commas.
6617   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6618                                                    initExprs, LiteralRParenLoc);
6619   initE->setType(Ty);
6620   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6621 }
6622 
6623 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6624 /// the ParenListExpr into a sequence of comma binary operators.
6625 ExprResult
6626 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6627   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6628   if (!E)
6629     return OrigExpr;
6630 
6631   ExprResult Result(E->getExpr(0));
6632 
6633   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6634     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6635                         E->getExpr(i));
6636 
6637   if (Result.isInvalid()) return ExprError();
6638 
6639   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6640 }
6641 
6642 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6643                                     SourceLocation R,
6644                                     MultiExprArg Val) {
6645   return ParenListExpr::Create(Context, L, Val, R);
6646 }
6647 
6648 /// Emit a specialized diagnostic when one expression is a null pointer
6649 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6650 /// emitted.
6651 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6652                                       SourceLocation QuestionLoc) {
6653   Expr *NullExpr = LHSExpr;
6654   Expr *NonPointerExpr = RHSExpr;
6655   Expr::NullPointerConstantKind NullKind =
6656       NullExpr->isNullPointerConstant(Context,
6657                                       Expr::NPC_ValueDependentIsNotNull);
6658 
6659   if (NullKind == Expr::NPCK_NotNull) {
6660     NullExpr = RHSExpr;
6661     NonPointerExpr = LHSExpr;
6662     NullKind =
6663         NullExpr->isNullPointerConstant(Context,
6664                                         Expr::NPC_ValueDependentIsNotNull);
6665   }
6666 
6667   if (NullKind == Expr::NPCK_NotNull)
6668     return false;
6669 
6670   if (NullKind == Expr::NPCK_ZeroExpression)
6671     return false;
6672 
6673   if (NullKind == Expr::NPCK_ZeroLiteral) {
6674     // In this case, check to make sure that we got here from a "NULL"
6675     // string in the source code.
6676     NullExpr = NullExpr->IgnoreParenImpCasts();
6677     SourceLocation loc = NullExpr->getExprLoc();
6678     if (!findMacroSpelling(loc, "NULL"))
6679       return false;
6680   }
6681 
6682   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6683   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6684       << NonPointerExpr->getType() << DiagType
6685       << NonPointerExpr->getSourceRange();
6686   return true;
6687 }
6688 
6689 /// Return false if the condition expression is valid, true otherwise.
6690 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6691   QualType CondTy = Cond->getType();
6692 
6693   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6694   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6695     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6696       << CondTy << Cond->getSourceRange();
6697     return true;
6698   }
6699 
6700   // C99 6.5.15p2
6701   if (CondTy->isScalarType()) return false;
6702 
6703   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6704     << CondTy << Cond->getSourceRange();
6705   return true;
6706 }
6707 
6708 /// Handle when one or both operands are void type.
6709 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6710                                          ExprResult &RHS) {
6711     Expr *LHSExpr = LHS.get();
6712     Expr *RHSExpr = RHS.get();
6713 
6714     if (!LHSExpr->getType()->isVoidType())
6715       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6716           << RHSExpr->getSourceRange();
6717     if (!RHSExpr->getType()->isVoidType())
6718       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6719           << LHSExpr->getSourceRange();
6720     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6721     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6722     return S.Context.VoidTy;
6723 }
6724 
6725 /// Return false if the NullExpr can be promoted to PointerTy,
6726 /// true otherwise.
6727 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6728                                         QualType PointerTy) {
6729   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6730       !NullExpr.get()->isNullPointerConstant(S.Context,
6731                                             Expr::NPC_ValueDependentIsNull))
6732     return true;
6733 
6734   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6735   return false;
6736 }
6737 
6738 /// Checks compatibility between two pointers and return the resulting
6739 /// type.
6740 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6741                                                      ExprResult &RHS,
6742                                                      SourceLocation Loc) {
6743   QualType LHSTy = LHS.get()->getType();
6744   QualType RHSTy = RHS.get()->getType();
6745 
6746   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6747     // Two identical pointers types are always compatible.
6748     return LHSTy;
6749   }
6750 
6751   QualType lhptee, rhptee;
6752 
6753   // Get the pointee types.
6754   bool IsBlockPointer = false;
6755   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6756     lhptee = LHSBTy->getPointeeType();
6757     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6758     IsBlockPointer = true;
6759   } else {
6760     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6761     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6762   }
6763 
6764   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6765   // differently qualified versions of compatible types, the result type is
6766   // a pointer to an appropriately qualified version of the composite
6767   // type.
6768 
6769   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6770   // clause doesn't make sense for our extensions. E.g. address space 2 should
6771   // be incompatible with address space 3: they may live on different devices or
6772   // anything.
6773   Qualifiers lhQual = lhptee.getQualifiers();
6774   Qualifiers rhQual = rhptee.getQualifiers();
6775 
6776   LangAS ResultAddrSpace = LangAS::Default;
6777   LangAS LAddrSpace = lhQual.getAddressSpace();
6778   LangAS RAddrSpace = rhQual.getAddressSpace();
6779 
6780   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6781   // spaces is disallowed.
6782   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6783     ResultAddrSpace = LAddrSpace;
6784   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6785     ResultAddrSpace = RAddrSpace;
6786   else {
6787     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6788         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6789         << RHS.get()->getSourceRange();
6790     return QualType();
6791   }
6792 
6793   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6794   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6795   lhQual.removeCVRQualifiers();
6796   rhQual.removeCVRQualifiers();
6797 
6798   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6799   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6800   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6801   // qual types are compatible iff
6802   //  * corresponded types are compatible
6803   //  * CVR qualifiers are equal
6804   //  * address spaces are equal
6805   // Thus for conditional operator we merge CVR and address space unqualified
6806   // pointees and if there is a composite type we return a pointer to it with
6807   // merged qualifiers.
6808   LHSCastKind =
6809       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6810   RHSCastKind =
6811       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6812   lhQual.removeAddressSpace();
6813   rhQual.removeAddressSpace();
6814 
6815   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6816   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6817 
6818   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6819 
6820   if (CompositeTy.isNull()) {
6821     // In this situation, we assume void* type. No especially good
6822     // reason, but this is what gcc does, and we do have to pick
6823     // to get a consistent AST.
6824     QualType incompatTy;
6825     incompatTy = S.Context.getPointerType(
6826         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6827     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6828     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6829 
6830     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6831     // for casts between types with incompatible address space qualifiers.
6832     // For the following code the compiler produces casts between global and
6833     // local address spaces of the corresponded innermost pointees:
6834     // local int *global *a;
6835     // global int *global *b;
6836     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6837     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6838         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6839         << RHS.get()->getSourceRange();
6840 
6841     return incompatTy;
6842   }
6843 
6844   // The pointer types are compatible.
6845   // In case of OpenCL ResultTy should have the address space qualifier
6846   // which is a superset of address spaces of both the 2nd and the 3rd
6847   // operands of the conditional operator.
6848   QualType ResultTy = [&, ResultAddrSpace]() {
6849     if (S.getLangOpts().OpenCL) {
6850       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6851       CompositeQuals.setAddressSpace(ResultAddrSpace);
6852       return S.Context
6853           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6854           .withCVRQualifiers(MergedCVRQual);
6855     }
6856     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6857   }();
6858   if (IsBlockPointer)
6859     ResultTy = S.Context.getBlockPointerType(ResultTy);
6860   else
6861     ResultTy = S.Context.getPointerType(ResultTy);
6862 
6863   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6864   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6865   return ResultTy;
6866 }
6867 
6868 /// Return the resulting type when the operands are both block pointers.
6869 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6870                                                           ExprResult &LHS,
6871                                                           ExprResult &RHS,
6872                                                           SourceLocation Loc) {
6873   QualType LHSTy = LHS.get()->getType();
6874   QualType RHSTy = RHS.get()->getType();
6875 
6876   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6877     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6878       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6879       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6880       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6881       return destType;
6882     }
6883     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6884       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6885       << RHS.get()->getSourceRange();
6886     return QualType();
6887   }
6888 
6889   // We have 2 block pointer types.
6890   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6891 }
6892 
6893 /// Return the resulting type when the operands are both pointers.
6894 static QualType
6895 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6896                                             ExprResult &RHS,
6897                                             SourceLocation Loc) {
6898   // get the pointer types
6899   QualType LHSTy = LHS.get()->getType();
6900   QualType RHSTy = RHS.get()->getType();
6901 
6902   // get the "pointed to" types
6903   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6904   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6905 
6906   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6907   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6908     // Figure out necessary qualifiers (C99 6.5.15p6)
6909     QualType destPointee
6910       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6911     QualType destType = S.Context.getPointerType(destPointee);
6912     // Add qualifiers if necessary.
6913     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6914     // Promote to void*.
6915     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6916     return destType;
6917   }
6918   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6919     QualType destPointee
6920       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6921     QualType destType = S.Context.getPointerType(destPointee);
6922     // Add qualifiers if necessary.
6923     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6924     // Promote to void*.
6925     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6926     return destType;
6927   }
6928 
6929   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6930 }
6931 
6932 /// Return false if the first expression is not an integer and the second
6933 /// expression is not a pointer, true otherwise.
6934 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6935                                         Expr* PointerExpr, SourceLocation Loc,
6936                                         bool IsIntFirstExpr) {
6937   if (!PointerExpr->getType()->isPointerType() ||
6938       !Int.get()->getType()->isIntegerType())
6939     return false;
6940 
6941   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6942   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6943 
6944   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6945     << Expr1->getType() << Expr2->getType()
6946     << Expr1->getSourceRange() << Expr2->getSourceRange();
6947   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6948                             CK_IntegralToPointer);
6949   return true;
6950 }
6951 
6952 /// Simple conversion between integer and floating point types.
6953 ///
6954 /// Used when handling the OpenCL conditional operator where the
6955 /// condition is a vector while the other operands are scalar.
6956 ///
6957 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6958 /// types are either integer or floating type. Between the two
6959 /// operands, the type with the higher rank is defined as the "result
6960 /// type". The other operand needs to be promoted to the same type. No
6961 /// other type promotion is allowed. We cannot use
6962 /// UsualArithmeticConversions() for this purpose, since it always
6963 /// promotes promotable types.
6964 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6965                                             ExprResult &RHS,
6966                                             SourceLocation QuestionLoc) {
6967   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6968   if (LHS.isInvalid())
6969     return QualType();
6970   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6971   if (RHS.isInvalid())
6972     return QualType();
6973 
6974   // For conversion purposes, we ignore any qualifiers.
6975   // For example, "const float" and "float" are equivalent.
6976   QualType LHSType =
6977     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6978   QualType RHSType =
6979     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6980 
6981   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6982     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6983       << LHSType << LHS.get()->getSourceRange();
6984     return QualType();
6985   }
6986 
6987   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6988     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6989       << RHSType << RHS.get()->getSourceRange();
6990     return QualType();
6991   }
6992 
6993   // If both types are identical, no conversion is needed.
6994   if (LHSType == RHSType)
6995     return LHSType;
6996 
6997   // Now handle "real" floating types (i.e. float, double, long double).
6998   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6999     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7000                                  /*IsCompAssign = */ false);
7001 
7002   // Finally, we have two differing integer types.
7003   return handleIntegerConversion<doIntegralCast, doIntegralCast>
7004   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7005 }
7006 
7007 /// Convert scalar operands to a vector that matches the
7008 ///        condition in length.
7009 ///
7010 /// Used when handling the OpenCL conditional operator where the
7011 /// condition is a vector while the other operands are scalar.
7012 ///
7013 /// We first compute the "result type" for the scalar operands
7014 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7015 /// into a vector of that type where the length matches the condition
7016 /// vector type. s6.11.6 requires that the element types of the result
7017 /// and the condition must have the same number of bits.
7018 static QualType
7019 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7020                               QualType CondTy, SourceLocation QuestionLoc) {
7021   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7022   if (ResTy.isNull()) return QualType();
7023 
7024   const VectorType *CV = CondTy->getAs<VectorType>();
7025   assert(CV);
7026 
7027   // Determine the vector result type
7028   unsigned NumElements = CV->getNumElements();
7029   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7030 
7031   // Ensure that all types have the same number of bits
7032   if (S.Context.getTypeSize(CV->getElementType())
7033       != S.Context.getTypeSize(ResTy)) {
7034     // Since VectorTy is created internally, it does not pretty print
7035     // with an OpenCL name. Instead, we just print a description.
7036     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7037     SmallString<64> Str;
7038     llvm::raw_svector_ostream OS(Str);
7039     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7040     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7041       << CondTy << OS.str();
7042     return QualType();
7043   }
7044 
7045   // Convert operands to the vector result type
7046   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7047   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7048 
7049   return VectorTy;
7050 }
7051 
7052 /// Return false if this is a valid OpenCL condition vector
7053 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7054                                        SourceLocation QuestionLoc) {
7055   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7056   // integral type.
7057   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7058   assert(CondTy);
7059   QualType EleTy = CondTy->getElementType();
7060   if (EleTy->isIntegerType()) return false;
7061 
7062   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7063     << Cond->getType() << Cond->getSourceRange();
7064   return true;
7065 }
7066 
7067 /// Return false if the vector condition type and the vector
7068 ///        result type are compatible.
7069 ///
7070 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7071 /// number of elements, and their element types have the same number
7072 /// of bits.
7073 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7074                               SourceLocation QuestionLoc) {
7075   const VectorType *CV = CondTy->getAs<VectorType>();
7076   const VectorType *RV = VecResTy->getAs<VectorType>();
7077   assert(CV && RV);
7078 
7079   if (CV->getNumElements() != RV->getNumElements()) {
7080     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7081       << CondTy << VecResTy;
7082     return true;
7083   }
7084 
7085   QualType CVE = CV->getElementType();
7086   QualType RVE = RV->getElementType();
7087 
7088   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7089     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7090       << CondTy << VecResTy;
7091     return true;
7092   }
7093 
7094   return false;
7095 }
7096 
7097 /// Return the resulting type for the conditional operator in
7098 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7099 ///        s6.3.i) when the condition is a vector type.
7100 static QualType
7101 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7102                              ExprResult &LHS, ExprResult &RHS,
7103                              SourceLocation QuestionLoc) {
7104   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7105   if (Cond.isInvalid())
7106     return QualType();
7107   QualType CondTy = Cond.get()->getType();
7108 
7109   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7110     return QualType();
7111 
7112   // If either operand is a vector then find the vector type of the
7113   // result as specified in OpenCL v1.1 s6.3.i.
7114   if (LHS.get()->getType()->isVectorType() ||
7115       RHS.get()->getType()->isVectorType()) {
7116     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7117                                               /*isCompAssign*/false,
7118                                               /*AllowBothBool*/true,
7119                                               /*AllowBoolConversions*/false);
7120     if (VecResTy.isNull()) return QualType();
7121     // The result type must match the condition type as specified in
7122     // OpenCL v1.1 s6.11.6.
7123     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7124       return QualType();
7125     return VecResTy;
7126   }
7127 
7128   // Both operands are scalar.
7129   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7130 }
7131 
7132 /// Return true if the Expr is block type
7133 static bool checkBlockType(Sema &S, const Expr *E) {
7134   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7135     QualType Ty = CE->getCallee()->getType();
7136     if (Ty->isBlockPointerType()) {
7137       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7138       return true;
7139     }
7140   }
7141   return false;
7142 }
7143 
7144 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7145 /// In that case, LHS = cond.
7146 /// C99 6.5.15
7147 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7148                                         ExprResult &RHS, ExprValueKind &VK,
7149                                         ExprObjectKind &OK,
7150                                         SourceLocation QuestionLoc) {
7151 
7152   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7153   if (!LHSResult.isUsable()) return QualType();
7154   LHS = LHSResult;
7155 
7156   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7157   if (!RHSResult.isUsable()) return QualType();
7158   RHS = RHSResult;
7159 
7160   // C++ is sufficiently different to merit its own checker.
7161   if (getLangOpts().CPlusPlus)
7162     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7163 
7164   VK = VK_RValue;
7165   OK = OK_Ordinary;
7166 
7167   // The OpenCL operator with a vector condition is sufficiently
7168   // different to merit its own checker.
7169   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7170     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7171 
7172   // First, check the condition.
7173   Cond = UsualUnaryConversions(Cond.get());
7174   if (Cond.isInvalid())
7175     return QualType();
7176   if (checkCondition(*this, Cond.get(), QuestionLoc))
7177     return QualType();
7178 
7179   // Now check the two expressions.
7180   if (LHS.get()->getType()->isVectorType() ||
7181       RHS.get()->getType()->isVectorType())
7182     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7183                                /*AllowBothBool*/true,
7184                                /*AllowBoolConversions*/false);
7185 
7186   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7187   if (LHS.isInvalid() || RHS.isInvalid())
7188     return QualType();
7189 
7190   QualType LHSTy = LHS.get()->getType();
7191   QualType RHSTy = RHS.get()->getType();
7192 
7193   // Diagnose attempts to convert between __float128 and long double where
7194   // such conversions currently can't be handled.
7195   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7196     Diag(QuestionLoc,
7197          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7198       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7199     return QualType();
7200   }
7201 
7202   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7203   // selection operator (?:).
7204   if (getLangOpts().OpenCL &&
7205       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7206     return QualType();
7207   }
7208 
7209   // If both operands have arithmetic type, do the usual arithmetic conversions
7210   // to find a common type: C99 6.5.15p3,5.
7211   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7212     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7213     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7214 
7215     return ResTy;
7216   }
7217 
7218   // If both operands are the same structure or union type, the result is that
7219   // type.
7220   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7221     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7222       if (LHSRT->getDecl() == RHSRT->getDecl())
7223         // "If both the operands have structure or union type, the result has
7224         // that type."  This implies that CV qualifiers are dropped.
7225         return LHSTy.getUnqualifiedType();
7226     // FIXME: Type of conditional expression must be complete in C mode.
7227   }
7228 
7229   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7230   // The following || allows only one side to be void (a GCC-ism).
7231   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7232     return checkConditionalVoidType(*this, LHS, RHS);
7233   }
7234 
7235   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7236   // the type of the other operand."
7237   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7238   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7239 
7240   // All objective-c pointer type analysis is done here.
7241   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7242                                                         QuestionLoc);
7243   if (LHS.isInvalid() || RHS.isInvalid())
7244     return QualType();
7245   if (!compositeType.isNull())
7246     return compositeType;
7247 
7248 
7249   // Handle block pointer types.
7250   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7251     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7252                                                      QuestionLoc);
7253 
7254   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7255   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7256     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7257                                                        QuestionLoc);
7258 
7259   // GCC compatibility: soften pointer/integer mismatch.  Note that
7260   // null pointers have been filtered out by this point.
7261   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7262       /*isIntFirstExpr=*/true))
7263     return RHSTy;
7264   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7265       /*isIntFirstExpr=*/false))
7266     return LHSTy;
7267 
7268   // Emit a better diagnostic if one of the expressions is a null pointer
7269   // constant and the other is not a pointer type. In this case, the user most
7270   // likely forgot to take the address of the other expression.
7271   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7272     return QualType();
7273 
7274   // Otherwise, the operands are not compatible.
7275   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7276     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7277     << RHS.get()->getSourceRange();
7278   return QualType();
7279 }
7280 
7281 /// FindCompositeObjCPointerType - Helper method to find composite type of
7282 /// two objective-c pointer types of the two input expressions.
7283 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7284                                             SourceLocation QuestionLoc) {
7285   QualType LHSTy = LHS.get()->getType();
7286   QualType RHSTy = RHS.get()->getType();
7287 
7288   // Handle things like Class and struct objc_class*.  Here we case the result
7289   // to the pseudo-builtin, because that will be implicitly cast back to the
7290   // redefinition type if an attempt is made to access its fields.
7291   if (LHSTy->isObjCClassType() &&
7292       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7293     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7294     return LHSTy;
7295   }
7296   if (RHSTy->isObjCClassType() &&
7297       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7298     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7299     return RHSTy;
7300   }
7301   // And the same for struct objc_object* / id
7302   if (LHSTy->isObjCIdType() &&
7303       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7304     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7305     return LHSTy;
7306   }
7307   if (RHSTy->isObjCIdType() &&
7308       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7309     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7310     return RHSTy;
7311   }
7312   // And the same for struct objc_selector* / SEL
7313   if (Context.isObjCSelType(LHSTy) &&
7314       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7315     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7316     return LHSTy;
7317   }
7318   if (Context.isObjCSelType(RHSTy) &&
7319       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7320     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7321     return RHSTy;
7322   }
7323   // Check constraints for Objective-C object pointers types.
7324   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7325 
7326     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7327       // Two identical object pointer types are always compatible.
7328       return LHSTy;
7329     }
7330     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7331     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7332     QualType compositeType = LHSTy;
7333 
7334     // If both operands are interfaces and either operand can be
7335     // assigned to the other, use that type as the composite
7336     // type. This allows
7337     //   xxx ? (A*) a : (B*) b
7338     // where B is a subclass of A.
7339     //
7340     // Additionally, as for assignment, if either type is 'id'
7341     // allow silent coercion. Finally, if the types are
7342     // incompatible then make sure to use 'id' as the composite
7343     // type so the result is acceptable for sending messages to.
7344 
7345     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7346     // It could return the composite type.
7347     if (!(compositeType =
7348           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7349       // Nothing more to do.
7350     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7351       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7352     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7353       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7354     } else if ((LHSTy->isObjCQualifiedIdType() ||
7355                 RHSTy->isObjCQualifiedIdType()) &&
7356                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7357       // Need to handle "id<xx>" explicitly.
7358       // GCC allows qualified id and any Objective-C type to devolve to
7359       // id. Currently localizing to here until clear this should be
7360       // part of ObjCQualifiedIdTypesAreCompatible.
7361       compositeType = Context.getObjCIdType();
7362     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7363       compositeType = Context.getObjCIdType();
7364     } else {
7365       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7366       << LHSTy << RHSTy
7367       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7368       QualType incompatTy = Context.getObjCIdType();
7369       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7370       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7371       return incompatTy;
7372     }
7373     // The object pointer types are compatible.
7374     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7375     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7376     return compositeType;
7377   }
7378   // Check Objective-C object pointer types and 'void *'
7379   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7380     if (getLangOpts().ObjCAutoRefCount) {
7381       // ARC forbids the implicit conversion of object pointers to 'void *',
7382       // so these types are not compatible.
7383       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7384           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7385       LHS = RHS = true;
7386       return QualType();
7387     }
7388     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7389     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7390     QualType destPointee
7391     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7392     QualType destType = Context.getPointerType(destPointee);
7393     // Add qualifiers if necessary.
7394     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7395     // Promote to void*.
7396     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7397     return destType;
7398   }
7399   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7400     if (getLangOpts().ObjCAutoRefCount) {
7401       // ARC forbids the implicit conversion of object pointers to 'void *',
7402       // so these types are not compatible.
7403       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7404           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7405       LHS = RHS = true;
7406       return QualType();
7407     }
7408     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7409     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7410     QualType destPointee
7411     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7412     QualType destType = Context.getPointerType(destPointee);
7413     // Add qualifiers if necessary.
7414     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7415     // Promote to void*.
7416     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7417     return destType;
7418   }
7419   return QualType();
7420 }
7421 
7422 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7423 /// ParenRange in parentheses.
7424 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7425                                const PartialDiagnostic &Note,
7426                                SourceRange ParenRange) {
7427   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7428   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7429       EndLoc.isValid()) {
7430     Self.Diag(Loc, Note)
7431       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7432       << FixItHint::CreateInsertion(EndLoc, ")");
7433   } else {
7434     // We can't display the parentheses, so just show the bare note.
7435     Self.Diag(Loc, Note) << ParenRange;
7436   }
7437 }
7438 
7439 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7440   return BinaryOperator::isAdditiveOp(Opc) ||
7441          BinaryOperator::isMultiplicativeOp(Opc) ||
7442          BinaryOperator::isShiftOp(Opc);
7443 }
7444 
7445 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7446 /// expression, either using a built-in or overloaded operator,
7447 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7448 /// expression.
7449 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7450                                    Expr **RHSExprs) {
7451   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7452   E = E->IgnoreImpCasts();
7453   E = E->IgnoreConversionOperator();
7454   E = E->IgnoreImpCasts();
7455   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7456     E = MTE->GetTemporaryExpr();
7457     E = E->IgnoreImpCasts();
7458   }
7459 
7460   // Built-in binary operator.
7461   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7462     if (IsArithmeticOp(OP->getOpcode())) {
7463       *Opcode = OP->getOpcode();
7464       *RHSExprs = OP->getRHS();
7465       return true;
7466     }
7467   }
7468 
7469   // Overloaded operator.
7470   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7471     if (Call->getNumArgs() != 2)
7472       return false;
7473 
7474     // Make sure this is really a binary operator that is safe to pass into
7475     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7476     OverloadedOperatorKind OO = Call->getOperator();
7477     if (OO < OO_Plus || OO > OO_Arrow ||
7478         OO == OO_PlusPlus || OO == OO_MinusMinus)
7479       return false;
7480 
7481     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7482     if (IsArithmeticOp(OpKind)) {
7483       *Opcode = OpKind;
7484       *RHSExprs = Call->getArg(1);
7485       return true;
7486     }
7487   }
7488 
7489   return false;
7490 }
7491 
7492 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7493 /// or is a logical expression such as (x==y) which has int type, but is
7494 /// commonly interpreted as boolean.
7495 static bool ExprLooksBoolean(Expr *E) {
7496   E = E->IgnoreParenImpCasts();
7497 
7498   if (E->getType()->isBooleanType())
7499     return true;
7500   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7501     return OP->isComparisonOp() || OP->isLogicalOp();
7502   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7503     return OP->getOpcode() == UO_LNot;
7504   if (E->getType()->isPointerType())
7505     return true;
7506   // FIXME: What about overloaded operator calls returning "unspecified boolean
7507   // type"s (commonly pointer-to-members)?
7508 
7509   return false;
7510 }
7511 
7512 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7513 /// and binary operator are mixed in a way that suggests the programmer assumed
7514 /// the conditional operator has higher precedence, for example:
7515 /// "int x = a + someBinaryCondition ? 1 : 2".
7516 static void DiagnoseConditionalPrecedence(Sema &Self,
7517                                           SourceLocation OpLoc,
7518                                           Expr *Condition,
7519                                           Expr *LHSExpr,
7520                                           Expr *RHSExpr) {
7521   BinaryOperatorKind CondOpcode;
7522   Expr *CondRHS;
7523 
7524   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7525     return;
7526   if (!ExprLooksBoolean(CondRHS))
7527     return;
7528 
7529   // The condition is an arithmetic binary expression, with a right-
7530   // hand side that looks boolean, so warn.
7531 
7532   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7533       << Condition->getSourceRange()
7534       << BinaryOperator::getOpcodeStr(CondOpcode);
7535 
7536   SuggestParentheses(
7537       Self, OpLoc,
7538       Self.PDiag(diag::note_precedence_silence)
7539           << BinaryOperator::getOpcodeStr(CondOpcode),
7540       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7541 
7542   SuggestParentheses(Self, OpLoc,
7543                      Self.PDiag(diag::note_precedence_conditional_first),
7544                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7545 }
7546 
7547 /// Compute the nullability of a conditional expression.
7548 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7549                                               QualType LHSTy, QualType RHSTy,
7550                                               ASTContext &Ctx) {
7551   if (!ResTy->isAnyPointerType())
7552     return ResTy;
7553 
7554   auto GetNullability = [&Ctx](QualType Ty) {
7555     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7556     if (Kind)
7557       return *Kind;
7558     return NullabilityKind::Unspecified;
7559   };
7560 
7561   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7562   NullabilityKind MergedKind;
7563 
7564   // Compute nullability of a binary conditional expression.
7565   if (IsBin) {
7566     if (LHSKind == NullabilityKind::NonNull)
7567       MergedKind = NullabilityKind::NonNull;
7568     else
7569       MergedKind = RHSKind;
7570   // Compute nullability of a normal conditional expression.
7571   } else {
7572     if (LHSKind == NullabilityKind::Nullable ||
7573         RHSKind == NullabilityKind::Nullable)
7574       MergedKind = NullabilityKind::Nullable;
7575     else if (LHSKind == NullabilityKind::NonNull)
7576       MergedKind = RHSKind;
7577     else if (RHSKind == NullabilityKind::NonNull)
7578       MergedKind = LHSKind;
7579     else
7580       MergedKind = NullabilityKind::Unspecified;
7581   }
7582 
7583   // Return if ResTy already has the correct nullability.
7584   if (GetNullability(ResTy) == MergedKind)
7585     return ResTy;
7586 
7587   // Strip all nullability from ResTy.
7588   while (ResTy->getNullability(Ctx))
7589     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7590 
7591   // Create a new AttributedType with the new nullability kind.
7592   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7593   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7594 }
7595 
7596 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7597 /// in the case of a the GNU conditional expr extension.
7598 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7599                                     SourceLocation ColonLoc,
7600                                     Expr *CondExpr, Expr *LHSExpr,
7601                                     Expr *RHSExpr) {
7602   if (!getLangOpts().CPlusPlus) {
7603     // C cannot handle TypoExpr nodes in the condition because it
7604     // doesn't handle dependent types properly, so make sure any TypoExprs have
7605     // been dealt with before checking the operands.
7606     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7607     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7608     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7609 
7610     if (!CondResult.isUsable())
7611       return ExprError();
7612 
7613     if (LHSExpr) {
7614       if (!LHSResult.isUsable())
7615         return ExprError();
7616     }
7617 
7618     if (!RHSResult.isUsable())
7619       return ExprError();
7620 
7621     CondExpr = CondResult.get();
7622     LHSExpr = LHSResult.get();
7623     RHSExpr = RHSResult.get();
7624   }
7625 
7626   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7627   // was the condition.
7628   OpaqueValueExpr *opaqueValue = nullptr;
7629   Expr *commonExpr = nullptr;
7630   if (!LHSExpr) {
7631     commonExpr = CondExpr;
7632     // Lower out placeholder types first.  This is important so that we don't
7633     // try to capture a placeholder. This happens in few cases in C++; such
7634     // as Objective-C++'s dictionary subscripting syntax.
7635     if (commonExpr->hasPlaceholderType()) {
7636       ExprResult result = CheckPlaceholderExpr(commonExpr);
7637       if (!result.isUsable()) return ExprError();
7638       commonExpr = result.get();
7639     }
7640     // We usually want to apply unary conversions *before* saving, except
7641     // in the special case of a C++ l-value conditional.
7642     if (!(getLangOpts().CPlusPlus
7643           && !commonExpr->isTypeDependent()
7644           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7645           && commonExpr->isGLValue()
7646           && commonExpr->isOrdinaryOrBitFieldObject()
7647           && RHSExpr->isOrdinaryOrBitFieldObject()
7648           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7649       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7650       if (commonRes.isInvalid())
7651         return ExprError();
7652       commonExpr = commonRes.get();
7653     }
7654 
7655     // If the common expression is a class or array prvalue, materialize it
7656     // so that we can safely refer to it multiple times.
7657     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7658                                    commonExpr->getType()->isArrayType())) {
7659       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7660       if (MatExpr.isInvalid())
7661         return ExprError();
7662       commonExpr = MatExpr.get();
7663     }
7664 
7665     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7666                                                 commonExpr->getType(),
7667                                                 commonExpr->getValueKind(),
7668                                                 commonExpr->getObjectKind(),
7669                                                 commonExpr);
7670     LHSExpr = CondExpr = opaqueValue;
7671   }
7672 
7673   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7674   ExprValueKind VK = VK_RValue;
7675   ExprObjectKind OK = OK_Ordinary;
7676   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7677   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7678                                              VK, OK, QuestionLoc);
7679   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7680       RHS.isInvalid())
7681     return ExprError();
7682 
7683   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7684                                 RHS.get());
7685 
7686   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7687 
7688   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7689                                          Context);
7690 
7691   if (!commonExpr)
7692     return new (Context)
7693         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7694                             RHS.get(), result, VK, OK);
7695 
7696   return new (Context) BinaryConditionalOperator(
7697       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7698       ColonLoc, result, VK, OK);
7699 }
7700 
7701 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7702 // being closely modeled after the C99 spec:-). The odd characteristic of this
7703 // routine is it effectively iqnores the qualifiers on the top level pointee.
7704 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7705 // FIXME: add a couple examples in this comment.
7706 static Sema::AssignConvertType
7707 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7708   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7709   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7710 
7711   // get the "pointed to" type (ignoring qualifiers at the top level)
7712   const Type *lhptee, *rhptee;
7713   Qualifiers lhq, rhq;
7714   std::tie(lhptee, lhq) =
7715       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7716   std::tie(rhptee, rhq) =
7717       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7718 
7719   Sema::AssignConvertType ConvTy = Sema::Compatible;
7720 
7721   // C99 6.5.16.1p1: This following citation is common to constraints
7722   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7723   // qualifiers of the type *pointed to* by the right;
7724 
7725   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7726   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7727       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7728     // Ignore lifetime for further calculation.
7729     lhq.removeObjCLifetime();
7730     rhq.removeObjCLifetime();
7731   }
7732 
7733   if (!lhq.compatiblyIncludes(rhq)) {
7734     // Treat address-space mismatches as fatal.
7735     if (!lhq.isAddressSpaceSupersetOf(rhq))
7736       return Sema::IncompatiblePointerDiscardsQualifiers;
7737 
7738     // It's okay to add or remove GC or lifetime qualifiers when converting to
7739     // and from void*.
7740     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7741                         .compatiblyIncludes(
7742                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7743              && (lhptee->isVoidType() || rhptee->isVoidType()))
7744       ; // keep old
7745 
7746     // Treat lifetime mismatches as fatal.
7747     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7748       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7749 
7750     // For GCC/MS compatibility, other qualifier mismatches are treated
7751     // as still compatible in C.
7752     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7753   }
7754 
7755   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7756   // incomplete type and the other is a pointer to a qualified or unqualified
7757   // version of void...
7758   if (lhptee->isVoidType()) {
7759     if (rhptee->isIncompleteOrObjectType())
7760       return ConvTy;
7761 
7762     // As an extension, we allow cast to/from void* to function pointer.
7763     assert(rhptee->isFunctionType());
7764     return Sema::FunctionVoidPointer;
7765   }
7766 
7767   if (rhptee->isVoidType()) {
7768     if (lhptee->isIncompleteOrObjectType())
7769       return ConvTy;
7770 
7771     // As an extension, we allow cast to/from void* to function pointer.
7772     assert(lhptee->isFunctionType());
7773     return Sema::FunctionVoidPointer;
7774   }
7775 
7776   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7777   // unqualified versions of compatible types, ...
7778   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7779   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7780     // Check if the pointee types are compatible ignoring the sign.
7781     // We explicitly check for char so that we catch "char" vs
7782     // "unsigned char" on systems where "char" is unsigned.
7783     if (lhptee->isCharType())
7784       ltrans = S.Context.UnsignedCharTy;
7785     else if (lhptee->hasSignedIntegerRepresentation())
7786       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7787 
7788     if (rhptee->isCharType())
7789       rtrans = S.Context.UnsignedCharTy;
7790     else if (rhptee->hasSignedIntegerRepresentation())
7791       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7792 
7793     if (ltrans == rtrans) {
7794       // Types are compatible ignoring the sign. Qualifier incompatibility
7795       // takes priority over sign incompatibility because the sign
7796       // warning can be disabled.
7797       if (ConvTy != Sema::Compatible)
7798         return ConvTy;
7799 
7800       return Sema::IncompatiblePointerSign;
7801     }
7802 
7803     // If we are a multi-level pointer, it's possible that our issue is simply
7804     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7805     // the eventual target type is the same and the pointers have the same
7806     // level of indirection, this must be the issue.
7807     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7808       do {
7809         std::tie(lhptee, lhq) =
7810           cast<PointerType>(lhptee)->getPointeeType().split().asPair();
7811         std::tie(rhptee, rhq) =
7812           cast<PointerType>(rhptee)->getPointeeType().split().asPair();
7813 
7814         // Inconsistent address spaces at this point is invalid, even if the
7815         // address spaces would be compatible.
7816         // FIXME: This doesn't catch address space mismatches for pointers of
7817         // different nesting levels, like:
7818         //   __local int *** a;
7819         //   int ** b = a;
7820         // It's not clear how to actually determine when such pointers are
7821         // invalidly incompatible.
7822         if (lhq.getAddressSpace() != rhq.getAddressSpace())
7823           return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
7824 
7825       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7826 
7827       if (lhptee == rhptee)
7828         return Sema::IncompatibleNestedPointerQualifiers;
7829     }
7830 
7831     // General pointer incompatibility takes priority over qualifiers.
7832     return Sema::IncompatiblePointer;
7833   }
7834   if (!S.getLangOpts().CPlusPlus &&
7835       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7836     return Sema::IncompatiblePointer;
7837   return ConvTy;
7838 }
7839 
7840 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7841 /// block pointer types are compatible or whether a block and normal pointer
7842 /// are compatible. It is more restrict than comparing two function pointer
7843 // types.
7844 static Sema::AssignConvertType
7845 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7846                                     QualType RHSType) {
7847   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7848   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7849 
7850   QualType lhptee, rhptee;
7851 
7852   // get the "pointed to" type (ignoring qualifiers at the top level)
7853   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7854   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7855 
7856   // In C++, the types have to match exactly.
7857   if (S.getLangOpts().CPlusPlus)
7858     return Sema::IncompatibleBlockPointer;
7859 
7860   Sema::AssignConvertType ConvTy = Sema::Compatible;
7861 
7862   // For blocks we enforce that qualifiers are identical.
7863   Qualifiers LQuals = lhptee.getLocalQualifiers();
7864   Qualifiers RQuals = rhptee.getLocalQualifiers();
7865   if (S.getLangOpts().OpenCL) {
7866     LQuals.removeAddressSpace();
7867     RQuals.removeAddressSpace();
7868   }
7869   if (LQuals != RQuals)
7870     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7871 
7872   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7873   // assignment.
7874   // The current behavior is similar to C++ lambdas. A block might be
7875   // assigned to a variable iff its return type and parameters are compatible
7876   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7877   // an assignment. Presumably it should behave in way that a function pointer
7878   // assignment does in C, so for each parameter and return type:
7879   //  * CVR and address space of LHS should be a superset of CVR and address
7880   //  space of RHS.
7881   //  * unqualified types should be compatible.
7882   if (S.getLangOpts().OpenCL) {
7883     if (!S.Context.typesAreBlockPointerCompatible(
7884             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7885             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7886       return Sema::IncompatibleBlockPointer;
7887   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7888     return Sema::IncompatibleBlockPointer;
7889 
7890   return ConvTy;
7891 }
7892 
7893 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7894 /// for assignment compatibility.
7895 static Sema::AssignConvertType
7896 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7897                                    QualType RHSType) {
7898   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7899   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7900 
7901   if (LHSType->isObjCBuiltinType()) {
7902     // Class is not compatible with ObjC object pointers.
7903     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7904         !RHSType->isObjCQualifiedClassType())
7905       return Sema::IncompatiblePointer;
7906     return Sema::Compatible;
7907   }
7908   if (RHSType->isObjCBuiltinType()) {
7909     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7910         !LHSType->isObjCQualifiedClassType())
7911       return Sema::IncompatiblePointer;
7912     return Sema::Compatible;
7913   }
7914   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7915   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7916 
7917   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7918       // make an exception for id<P>
7919       !LHSType->isObjCQualifiedIdType())
7920     return Sema::CompatiblePointerDiscardsQualifiers;
7921 
7922   if (S.Context.typesAreCompatible(LHSType, RHSType))
7923     return Sema::Compatible;
7924   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7925     return Sema::IncompatibleObjCQualifiedId;
7926   return Sema::IncompatiblePointer;
7927 }
7928 
7929 Sema::AssignConvertType
7930 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7931                                  QualType LHSType, QualType RHSType) {
7932   // Fake up an opaque expression.  We don't actually care about what
7933   // cast operations are required, so if CheckAssignmentConstraints
7934   // adds casts to this they'll be wasted, but fortunately that doesn't
7935   // usually happen on valid code.
7936   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7937   ExprResult RHSPtr = &RHSExpr;
7938   CastKind K;
7939 
7940   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7941 }
7942 
7943 /// This helper function returns true if QT is a vector type that has element
7944 /// type ElementType.
7945 static bool isVector(QualType QT, QualType ElementType) {
7946   if (const VectorType *VT = QT->getAs<VectorType>())
7947     return VT->getElementType() == ElementType;
7948   return false;
7949 }
7950 
7951 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7952 /// has code to accommodate several GCC extensions when type checking
7953 /// pointers. Here are some objectionable examples that GCC considers warnings:
7954 ///
7955 ///  int a, *pint;
7956 ///  short *pshort;
7957 ///  struct foo *pfoo;
7958 ///
7959 ///  pint = pshort; // warning: assignment from incompatible pointer type
7960 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7961 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7962 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7963 ///
7964 /// As a result, the code for dealing with pointers is more complex than the
7965 /// C99 spec dictates.
7966 ///
7967 /// Sets 'Kind' for any result kind except Incompatible.
7968 Sema::AssignConvertType
7969 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7970                                  CastKind &Kind, bool ConvertRHS) {
7971   QualType RHSType = RHS.get()->getType();
7972   QualType OrigLHSType = LHSType;
7973 
7974   // Get canonical types.  We're not formatting these types, just comparing
7975   // them.
7976   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7977   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7978 
7979   // Common case: no conversion required.
7980   if (LHSType == RHSType) {
7981     Kind = CK_NoOp;
7982     return Compatible;
7983   }
7984 
7985   // If we have an atomic type, try a non-atomic assignment, then just add an
7986   // atomic qualification step.
7987   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7988     Sema::AssignConvertType result =
7989       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7990     if (result != Compatible)
7991       return result;
7992     if (Kind != CK_NoOp && ConvertRHS)
7993       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7994     Kind = CK_NonAtomicToAtomic;
7995     return Compatible;
7996   }
7997 
7998   // If the left-hand side is a reference type, then we are in a
7999   // (rare!) case where we've allowed the use of references in C,
8000   // e.g., as a parameter type in a built-in function. In this case,
8001   // just make sure that the type referenced is compatible with the
8002   // right-hand side type. The caller is responsible for adjusting
8003   // LHSType so that the resulting expression does not have reference
8004   // type.
8005   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8006     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8007       Kind = CK_LValueBitCast;
8008       return Compatible;
8009     }
8010     return Incompatible;
8011   }
8012 
8013   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8014   // to the same ExtVector type.
8015   if (LHSType->isExtVectorType()) {
8016     if (RHSType->isExtVectorType())
8017       return Incompatible;
8018     if (RHSType->isArithmeticType()) {
8019       // CK_VectorSplat does T -> vector T, so first cast to the element type.
8020       if (ConvertRHS)
8021         RHS = prepareVectorSplat(LHSType, RHS.get());
8022       Kind = CK_VectorSplat;
8023       return Compatible;
8024     }
8025   }
8026 
8027   // Conversions to or from vector type.
8028   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8029     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8030       // Allow assignments of an AltiVec vector type to an equivalent GCC
8031       // vector type and vice versa
8032       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8033         Kind = CK_BitCast;
8034         return Compatible;
8035       }
8036 
8037       // If we are allowing lax vector conversions, and LHS and RHS are both
8038       // vectors, the total size only needs to be the same. This is a bitcast;
8039       // no bits are changed but the result type is different.
8040       if (isLaxVectorConversion(RHSType, LHSType)) {
8041         Kind = CK_BitCast;
8042         return IncompatibleVectors;
8043       }
8044     }
8045 
8046     // When the RHS comes from another lax conversion (e.g. binops between
8047     // scalars and vectors) the result is canonicalized as a vector. When the
8048     // LHS is also a vector, the lax is allowed by the condition above. Handle
8049     // the case where LHS is a scalar.
8050     if (LHSType->isScalarType()) {
8051       const VectorType *VecType = RHSType->getAs<VectorType>();
8052       if (VecType && VecType->getNumElements() == 1 &&
8053           isLaxVectorConversion(RHSType, LHSType)) {
8054         ExprResult *VecExpr = &RHS;
8055         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8056         Kind = CK_BitCast;
8057         return Compatible;
8058       }
8059     }
8060 
8061     return Incompatible;
8062   }
8063 
8064   // Diagnose attempts to convert between __float128 and long double where
8065   // such conversions currently can't be handled.
8066   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8067     return Incompatible;
8068 
8069   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8070   // discards the imaginary part.
8071   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8072       !LHSType->getAs<ComplexType>())
8073     return Incompatible;
8074 
8075   // Arithmetic conversions.
8076   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8077       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8078     if (ConvertRHS)
8079       Kind = PrepareScalarCast(RHS, LHSType);
8080     return Compatible;
8081   }
8082 
8083   // Conversions to normal pointers.
8084   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8085     // U* -> T*
8086     if (isa<PointerType>(RHSType)) {
8087       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8088       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8089       if (AddrSpaceL != AddrSpaceR)
8090         Kind = CK_AddressSpaceConversion;
8091       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8092         Kind = CK_NoOp;
8093       else
8094         Kind = CK_BitCast;
8095       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8096     }
8097 
8098     // int -> T*
8099     if (RHSType->isIntegerType()) {
8100       Kind = CK_IntegralToPointer; // FIXME: null?
8101       return IntToPointer;
8102     }
8103 
8104     // C pointers are not compatible with ObjC object pointers,
8105     // with two exceptions:
8106     if (isa<ObjCObjectPointerType>(RHSType)) {
8107       //  - conversions to void*
8108       if (LHSPointer->getPointeeType()->isVoidType()) {
8109         Kind = CK_BitCast;
8110         return Compatible;
8111       }
8112 
8113       //  - conversions from 'Class' to the redefinition type
8114       if (RHSType->isObjCClassType() &&
8115           Context.hasSameType(LHSType,
8116                               Context.getObjCClassRedefinitionType())) {
8117         Kind = CK_BitCast;
8118         return Compatible;
8119       }
8120 
8121       Kind = CK_BitCast;
8122       return IncompatiblePointer;
8123     }
8124 
8125     // U^ -> void*
8126     if (RHSType->getAs<BlockPointerType>()) {
8127       if (LHSPointer->getPointeeType()->isVoidType()) {
8128         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8129         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8130                                 ->getPointeeType()
8131                                 .getAddressSpace();
8132         Kind =
8133             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8134         return Compatible;
8135       }
8136     }
8137 
8138     return Incompatible;
8139   }
8140 
8141   // Conversions to block pointers.
8142   if (isa<BlockPointerType>(LHSType)) {
8143     // U^ -> T^
8144     if (RHSType->isBlockPointerType()) {
8145       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8146                               ->getPointeeType()
8147                               .getAddressSpace();
8148       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8149                               ->getPointeeType()
8150                               .getAddressSpace();
8151       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8152       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8153     }
8154 
8155     // int or null -> T^
8156     if (RHSType->isIntegerType()) {
8157       Kind = CK_IntegralToPointer; // FIXME: null
8158       return IntToBlockPointer;
8159     }
8160 
8161     // id -> T^
8162     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8163       Kind = CK_AnyPointerToBlockPointerCast;
8164       return Compatible;
8165     }
8166 
8167     // void* -> T^
8168     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8169       if (RHSPT->getPointeeType()->isVoidType()) {
8170         Kind = CK_AnyPointerToBlockPointerCast;
8171         return Compatible;
8172       }
8173 
8174     return Incompatible;
8175   }
8176 
8177   // Conversions to Objective-C pointers.
8178   if (isa<ObjCObjectPointerType>(LHSType)) {
8179     // A* -> B*
8180     if (RHSType->isObjCObjectPointerType()) {
8181       Kind = CK_BitCast;
8182       Sema::AssignConvertType result =
8183         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8184       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8185           result == Compatible &&
8186           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8187         result = IncompatibleObjCWeakRef;
8188       return result;
8189     }
8190 
8191     // int or null -> A*
8192     if (RHSType->isIntegerType()) {
8193       Kind = CK_IntegralToPointer; // FIXME: null
8194       return IntToPointer;
8195     }
8196 
8197     // In general, C pointers are not compatible with ObjC object pointers,
8198     // with two exceptions:
8199     if (isa<PointerType>(RHSType)) {
8200       Kind = CK_CPointerToObjCPointerCast;
8201 
8202       //  - conversions from 'void*'
8203       if (RHSType->isVoidPointerType()) {
8204         return Compatible;
8205       }
8206 
8207       //  - conversions to 'Class' from its redefinition type
8208       if (LHSType->isObjCClassType() &&
8209           Context.hasSameType(RHSType,
8210                               Context.getObjCClassRedefinitionType())) {
8211         return Compatible;
8212       }
8213 
8214       return IncompatiblePointer;
8215     }
8216 
8217     // Only under strict condition T^ is compatible with an Objective-C pointer.
8218     if (RHSType->isBlockPointerType() &&
8219         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8220       if (ConvertRHS)
8221         maybeExtendBlockObject(RHS);
8222       Kind = CK_BlockPointerToObjCPointerCast;
8223       return Compatible;
8224     }
8225 
8226     return Incompatible;
8227   }
8228 
8229   // Conversions from pointers that are not covered by the above.
8230   if (isa<PointerType>(RHSType)) {
8231     // T* -> _Bool
8232     if (LHSType == Context.BoolTy) {
8233       Kind = CK_PointerToBoolean;
8234       return Compatible;
8235     }
8236 
8237     // T* -> int
8238     if (LHSType->isIntegerType()) {
8239       Kind = CK_PointerToIntegral;
8240       return PointerToInt;
8241     }
8242 
8243     return Incompatible;
8244   }
8245 
8246   // Conversions from Objective-C pointers that are not covered by the above.
8247   if (isa<ObjCObjectPointerType>(RHSType)) {
8248     // T* -> _Bool
8249     if (LHSType == Context.BoolTy) {
8250       Kind = CK_PointerToBoolean;
8251       return Compatible;
8252     }
8253 
8254     // T* -> int
8255     if (LHSType->isIntegerType()) {
8256       Kind = CK_PointerToIntegral;
8257       return PointerToInt;
8258     }
8259 
8260     return Incompatible;
8261   }
8262 
8263   // struct A -> struct B
8264   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8265     if (Context.typesAreCompatible(LHSType, RHSType)) {
8266       Kind = CK_NoOp;
8267       return Compatible;
8268     }
8269   }
8270 
8271   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8272     Kind = CK_IntToOCLSampler;
8273     return Compatible;
8274   }
8275 
8276   return Incompatible;
8277 }
8278 
8279 /// Constructs a transparent union from an expression that is
8280 /// used to initialize the transparent union.
8281 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8282                                       ExprResult &EResult, QualType UnionType,
8283                                       FieldDecl *Field) {
8284   // Build an initializer list that designates the appropriate member
8285   // of the transparent union.
8286   Expr *E = EResult.get();
8287   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8288                                                    E, SourceLocation());
8289   Initializer->setType(UnionType);
8290   Initializer->setInitializedFieldInUnion(Field);
8291 
8292   // Build a compound literal constructing a value of the transparent
8293   // union type from this initializer list.
8294   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8295   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8296                                         VK_RValue, Initializer, false);
8297 }
8298 
8299 Sema::AssignConvertType
8300 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8301                                                ExprResult &RHS) {
8302   QualType RHSType = RHS.get()->getType();
8303 
8304   // If the ArgType is a Union type, we want to handle a potential
8305   // transparent_union GCC extension.
8306   const RecordType *UT = ArgType->getAsUnionType();
8307   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8308     return Incompatible;
8309 
8310   // The field to initialize within the transparent union.
8311   RecordDecl *UD = UT->getDecl();
8312   FieldDecl *InitField = nullptr;
8313   // It's compatible if the expression matches any of the fields.
8314   for (auto *it : UD->fields()) {
8315     if (it->getType()->isPointerType()) {
8316       // If the transparent union contains a pointer type, we allow:
8317       // 1) void pointer
8318       // 2) null pointer constant
8319       if (RHSType->isPointerType())
8320         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8321           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8322           InitField = it;
8323           break;
8324         }
8325 
8326       if (RHS.get()->isNullPointerConstant(Context,
8327                                            Expr::NPC_ValueDependentIsNull)) {
8328         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8329                                 CK_NullToPointer);
8330         InitField = it;
8331         break;
8332       }
8333     }
8334 
8335     CastKind Kind;
8336     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8337           == Compatible) {
8338       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8339       InitField = it;
8340       break;
8341     }
8342   }
8343 
8344   if (!InitField)
8345     return Incompatible;
8346 
8347   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8348   return Compatible;
8349 }
8350 
8351 Sema::AssignConvertType
8352 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8353                                        bool Diagnose,
8354                                        bool DiagnoseCFAudited,
8355                                        bool ConvertRHS) {
8356   // We need to be able to tell the caller whether we diagnosed a problem, if
8357   // they ask us to issue diagnostics.
8358   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8359 
8360   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8361   // we can't avoid *all* modifications at the moment, so we need some somewhere
8362   // to put the updated value.
8363   ExprResult LocalRHS = CallerRHS;
8364   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8365 
8366   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8367     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8368       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8369           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8370         Diag(RHS.get()->getExprLoc(),
8371              diag::warn_noderef_to_dereferenceable_pointer)
8372             << RHS.get()->getSourceRange();
8373       }
8374     }
8375   }
8376 
8377   if (getLangOpts().CPlusPlus) {
8378     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8379       // C++ 5.17p3: If the left operand is not of class type, the
8380       // expression is implicitly converted (C++ 4) to the
8381       // cv-unqualified type of the left operand.
8382       QualType RHSType = RHS.get()->getType();
8383       if (Diagnose) {
8384         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8385                                         AA_Assigning);
8386       } else {
8387         ImplicitConversionSequence ICS =
8388             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8389                                   /*SuppressUserConversions=*/false,
8390                                   /*AllowExplicit=*/false,
8391                                   /*InOverloadResolution=*/false,
8392                                   /*CStyle=*/false,
8393                                   /*AllowObjCWritebackConversion=*/false);
8394         if (ICS.isFailure())
8395           return Incompatible;
8396         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8397                                         ICS, AA_Assigning);
8398       }
8399       if (RHS.isInvalid())
8400         return Incompatible;
8401       Sema::AssignConvertType result = Compatible;
8402       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8403           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8404         result = IncompatibleObjCWeakRef;
8405       return result;
8406     }
8407 
8408     // FIXME: Currently, we fall through and treat C++ classes like C
8409     // structures.
8410     // FIXME: We also fall through for atomics; not sure what should
8411     // happen there, though.
8412   } else if (RHS.get()->getType() == Context.OverloadTy) {
8413     // As a set of extensions to C, we support overloading on functions. These
8414     // functions need to be resolved here.
8415     DeclAccessPair DAP;
8416     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8417             RHS.get(), LHSType, /*Complain=*/false, DAP))
8418       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8419     else
8420       return Incompatible;
8421   }
8422 
8423   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8424   // a null pointer constant.
8425   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8426        LHSType->isBlockPointerType()) &&
8427       RHS.get()->isNullPointerConstant(Context,
8428                                        Expr::NPC_ValueDependentIsNull)) {
8429     if (Diagnose || ConvertRHS) {
8430       CastKind Kind;
8431       CXXCastPath Path;
8432       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8433                              /*IgnoreBaseAccess=*/false, Diagnose);
8434       if (ConvertRHS)
8435         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8436     }
8437     return Compatible;
8438   }
8439 
8440   // OpenCL queue_t type assignment.
8441   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8442                                  Context, Expr::NPC_ValueDependentIsNull)) {
8443     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8444     return Compatible;
8445   }
8446 
8447   // This check seems unnatural, however it is necessary to ensure the proper
8448   // conversion of functions/arrays. If the conversion were done for all
8449   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8450   // expressions that suppress this implicit conversion (&, sizeof).
8451   //
8452   // Suppress this for references: C++ 8.5.3p5.
8453   if (!LHSType->isReferenceType()) {
8454     // FIXME: We potentially allocate here even if ConvertRHS is false.
8455     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8456     if (RHS.isInvalid())
8457       return Incompatible;
8458   }
8459   CastKind Kind;
8460   Sema::AssignConvertType result =
8461     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8462 
8463   // C99 6.5.16.1p2: The value of the right operand is converted to the
8464   // type of the assignment expression.
8465   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8466   // so that we can use references in built-in functions even in C.
8467   // The getNonReferenceType() call makes sure that the resulting expression
8468   // does not have reference type.
8469   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8470     QualType Ty = LHSType.getNonLValueExprType(Context);
8471     Expr *E = RHS.get();
8472 
8473     // Check for various Objective-C errors. If we are not reporting
8474     // diagnostics and just checking for errors, e.g., during overload
8475     // resolution, return Incompatible to indicate the failure.
8476     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8477         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8478                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8479       if (!Diagnose)
8480         return Incompatible;
8481     }
8482     if (getLangOpts().ObjC &&
8483         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8484                                            E->getType(), E, Diagnose) ||
8485          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8486       if (!Diagnose)
8487         return Incompatible;
8488       // Replace the expression with a corrected version and continue so we
8489       // can find further errors.
8490       RHS = E;
8491       return Compatible;
8492     }
8493 
8494     if (ConvertRHS)
8495       RHS = ImpCastExprToType(E, Ty, Kind);
8496   }
8497 
8498   return result;
8499 }
8500 
8501 namespace {
8502 /// The original operand to an operator, prior to the application of the usual
8503 /// arithmetic conversions and converting the arguments of a builtin operator
8504 /// candidate.
8505 struct OriginalOperand {
8506   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8507     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8508       Op = MTE->GetTemporaryExpr();
8509     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8510       Op = BTE->getSubExpr();
8511     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8512       Orig = ICE->getSubExprAsWritten();
8513       Conversion = ICE->getConversionFunction();
8514     }
8515   }
8516 
8517   QualType getType() const { return Orig->getType(); }
8518 
8519   Expr *Orig;
8520   NamedDecl *Conversion;
8521 };
8522 }
8523 
8524 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8525                                ExprResult &RHS) {
8526   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8527 
8528   Diag(Loc, diag::err_typecheck_invalid_operands)
8529     << OrigLHS.getType() << OrigRHS.getType()
8530     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8531 
8532   // If a user-defined conversion was applied to either of the operands prior
8533   // to applying the built-in operator rules, tell the user about it.
8534   if (OrigLHS.Conversion) {
8535     Diag(OrigLHS.Conversion->getLocation(),
8536          diag::note_typecheck_invalid_operands_converted)
8537       << 0 << LHS.get()->getType();
8538   }
8539   if (OrigRHS.Conversion) {
8540     Diag(OrigRHS.Conversion->getLocation(),
8541          diag::note_typecheck_invalid_operands_converted)
8542       << 1 << RHS.get()->getType();
8543   }
8544 
8545   return QualType();
8546 }
8547 
8548 // Diagnose cases where a scalar was implicitly converted to a vector and
8549 // diagnose the underlying types. Otherwise, diagnose the error
8550 // as invalid vector logical operands for non-C++ cases.
8551 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8552                                             ExprResult &RHS) {
8553   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8554   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8555 
8556   bool LHSNatVec = LHSType->isVectorType();
8557   bool RHSNatVec = RHSType->isVectorType();
8558 
8559   if (!(LHSNatVec && RHSNatVec)) {
8560     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8561     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8562     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8563         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8564         << Vector->getSourceRange();
8565     return QualType();
8566   }
8567 
8568   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8569       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8570       << RHS.get()->getSourceRange();
8571 
8572   return QualType();
8573 }
8574 
8575 /// Try to convert a value of non-vector type to a vector type by converting
8576 /// the type to the element type of the vector and then performing a splat.
8577 /// If the language is OpenCL, we only use conversions that promote scalar
8578 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8579 /// for float->int.
8580 ///
8581 /// OpenCL V2.0 6.2.6.p2:
8582 /// An error shall occur if any scalar operand type has greater rank
8583 /// than the type of the vector element.
8584 ///
8585 /// \param scalar - if non-null, actually perform the conversions
8586 /// \return true if the operation fails (but without diagnosing the failure)
8587 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8588                                      QualType scalarTy,
8589                                      QualType vectorEltTy,
8590                                      QualType vectorTy,
8591                                      unsigned &DiagID) {
8592   // The conversion to apply to the scalar before splatting it,
8593   // if necessary.
8594   CastKind scalarCast = CK_NoOp;
8595 
8596   if (vectorEltTy->isIntegralType(S.Context)) {
8597     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8598         (scalarTy->isIntegerType() &&
8599          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8600       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8601       return true;
8602     }
8603     if (!scalarTy->isIntegralType(S.Context))
8604       return true;
8605     scalarCast = CK_IntegralCast;
8606   } else if (vectorEltTy->isRealFloatingType()) {
8607     if (scalarTy->isRealFloatingType()) {
8608       if (S.getLangOpts().OpenCL &&
8609           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8610         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8611         return true;
8612       }
8613       scalarCast = CK_FloatingCast;
8614     }
8615     else if (scalarTy->isIntegralType(S.Context))
8616       scalarCast = CK_IntegralToFloating;
8617     else
8618       return true;
8619   } else {
8620     return true;
8621   }
8622 
8623   // Adjust scalar if desired.
8624   if (scalar) {
8625     if (scalarCast != CK_NoOp)
8626       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8627     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8628   }
8629   return false;
8630 }
8631 
8632 /// Convert vector E to a vector with the same number of elements but different
8633 /// element type.
8634 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8635   const auto *VecTy = E->getType()->getAs<VectorType>();
8636   assert(VecTy && "Expression E must be a vector");
8637   QualType NewVecTy = S.Context.getVectorType(ElementType,
8638                                               VecTy->getNumElements(),
8639                                               VecTy->getVectorKind());
8640 
8641   // Look through the implicit cast. Return the subexpression if its type is
8642   // NewVecTy.
8643   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8644     if (ICE->getSubExpr()->getType() == NewVecTy)
8645       return ICE->getSubExpr();
8646 
8647   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8648   return S.ImpCastExprToType(E, NewVecTy, Cast);
8649 }
8650 
8651 /// Test if a (constant) integer Int can be casted to another integer type
8652 /// IntTy without losing precision.
8653 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8654                                       QualType OtherIntTy) {
8655   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8656 
8657   // Reject cases where the value of the Int is unknown as that would
8658   // possibly cause truncation, but accept cases where the scalar can be
8659   // demoted without loss of precision.
8660   Expr::EvalResult EVResult;
8661   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8662   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8663   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8664   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8665 
8666   if (CstInt) {
8667     // If the scalar is constant and is of a higher order and has more active
8668     // bits that the vector element type, reject it.
8669     llvm::APSInt Result = EVResult.Val.getInt();
8670     unsigned NumBits = IntSigned
8671                            ? (Result.isNegative() ? Result.getMinSignedBits()
8672                                                   : Result.getActiveBits())
8673                            : Result.getActiveBits();
8674     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8675       return true;
8676 
8677     // If the signedness of the scalar type and the vector element type
8678     // differs and the number of bits is greater than that of the vector
8679     // element reject it.
8680     return (IntSigned != OtherIntSigned &&
8681             NumBits > S.Context.getIntWidth(OtherIntTy));
8682   }
8683 
8684   // Reject cases where the value of the scalar is not constant and it's
8685   // order is greater than that of the vector element type.
8686   return (Order < 0);
8687 }
8688 
8689 /// Test if a (constant) integer Int can be casted to floating point type
8690 /// FloatTy without losing precision.
8691 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8692                                      QualType FloatTy) {
8693   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8694 
8695   // Determine if the integer constant can be expressed as a floating point
8696   // number of the appropriate type.
8697   Expr::EvalResult EVResult;
8698   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8699 
8700   uint64_t Bits = 0;
8701   if (CstInt) {
8702     // Reject constants that would be truncated if they were converted to
8703     // the floating point type. Test by simple to/from conversion.
8704     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8705     //        could be avoided if there was a convertFromAPInt method
8706     //        which could signal back if implicit truncation occurred.
8707     llvm::APSInt Result = EVResult.Val.getInt();
8708     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8709     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8710                            llvm::APFloat::rmTowardZero);
8711     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8712                              !IntTy->hasSignedIntegerRepresentation());
8713     bool Ignored = false;
8714     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8715                            &Ignored);
8716     if (Result != ConvertBack)
8717       return true;
8718   } else {
8719     // Reject types that cannot be fully encoded into the mantissa of
8720     // the float.
8721     Bits = S.Context.getTypeSize(IntTy);
8722     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8723         S.Context.getFloatTypeSemantics(FloatTy));
8724     if (Bits > FloatPrec)
8725       return true;
8726   }
8727 
8728   return false;
8729 }
8730 
8731 /// Attempt to convert and splat Scalar into a vector whose types matches
8732 /// Vector following GCC conversion rules. The rule is that implicit
8733 /// conversion can occur when Scalar can be casted to match Vector's element
8734 /// type without causing truncation of Scalar.
8735 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8736                                         ExprResult *Vector) {
8737   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8738   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8739   const VectorType *VT = VectorTy->getAs<VectorType>();
8740 
8741   assert(!isa<ExtVectorType>(VT) &&
8742          "ExtVectorTypes should not be handled here!");
8743 
8744   QualType VectorEltTy = VT->getElementType();
8745 
8746   // Reject cases where the vector element type or the scalar element type are
8747   // not integral or floating point types.
8748   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8749     return true;
8750 
8751   // The conversion to apply to the scalar before splatting it,
8752   // if necessary.
8753   CastKind ScalarCast = CK_NoOp;
8754 
8755   // Accept cases where the vector elements are integers and the scalar is
8756   // an integer.
8757   // FIXME: Notionally if the scalar was a floating point value with a precise
8758   //        integral representation, we could cast it to an appropriate integer
8759   //        type and then perform the rest of the checks here. GCC will perform
8760   //        this conversion in some cases as determined by the input language.
8761   //        We should accept it on a language independent basis.
8762   if (VectorEltTy->isIntegralType(S.Context) &&
8763       ScalarTy->isIntegralType(S.Context) &&
8764       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8765 
8766     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8767       return true;
8768 
8769     ScalarCast = CK_IntegralCast;
8770   } else if (VectorEltTy->isRealFloatingType()) {
8771     if (ScalarTy->isRealFloatingType()) {
8772 
8773       // Reject cases where the scalar type is not a constant and has a higher
8774       // Order than the vector element type.
8775       llvm::APFloat Result(0.0);
8776       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8777       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8778       if (!CstScalar && Order < 0)
8779         return true;
8780 
8781       // If the scalar cannot be safely casted to the vector element type,
8782       // reject it.
8783       if (CstScalar) {
8784         bool Truncated = false;
8785         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8786                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8787         if (Truncated)
8788           return true;
8789       }
8790 
8791       ScalarCast = CK_FloatingCast;
8792     } else if (ScalarTy->isIntegralType(S.Context)) {
8793       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8794         return true;
8795 
8796       ScalarCast = CK_IntegralToFloating;
8797     } else
8798       return true;
8799   }
8800 
8801   // Adjust scalar if desired.
8802   if (Scalar) {
8803     if (ScalarCast != CK_NoOp)
8804       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8805     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8806   }
8807   return false;
8808 }
8809 
8810 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8811                                    SourceLocation Loc, bool IsCompAssign,
8812                                    bool AllowBothBool,
8813                                    bool AllowBoolConversions) {
8814   if (!IsCompAssign) {
8815     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8816     if (LHS.isInvalid())
8817       return QualType();
8818   }
8819   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8820   if (RHS.isInvalid())
8821     return QualType();
8822 
8823   // For conversion purposes, we ignore any qualifiers.
8824   // For example, "const float" and "float" are equivalent.
8825   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8826   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8827 
8828   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8829   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8830   assert(LHSVecType || RHSVecType);
8831 
8832   // AltiVec-style "vector bool op vector bool" combinations are allowed
8833   // for some operators but not others.
8834   if (!AllowBothBool &&
8835       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8836       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8837     return InvalidOperands(Loc, LHS, RHS);
8838 
8839   // If the vector types are identical, return.
8840   if (Context.hasSameType(LHSType, RHSType))
8841     return LHSType;
8842 
8843   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8844   if (LHSVecType && RHSVecType &&
8845       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8846     if (isa<ExtVectorType>(LHSVecType)) {
8847       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8848       return LHSType;
8849     }
8850 
8851     if (!IsCompAssign)
8852       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8853     return RHSType;
8854   }
8855 
8856   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8857   // can be mixed, with the result being the non-bool type.  The non-bool
8858   // operand must have integer element type.
8859   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8860       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8861       (Context.getTypeSize(LHSVecType->getElementType()) ==
8862        Context.getTypeSize(RHSVecType->getElementType()))) {
8863     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8864         LHSVecType->getElementType()->isIntegerType() &&
8865         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8866       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8867       return LHSType;
8868     }
8869     if (!IsCompAssign &&
8870         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8871         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8872         RHSVecType->getElementType()->isIntegerType()) {
8873       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8874       return RHSType;
8875     }
8876   }
8877 
8878   // If there's a vector type and a scalar, try to convert the scalar to
8879   // the vector element type and splat.
8880   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8881   if (!RHSVecType) {
8882     if (isa<ExtVectorType>(LHSVecType)) {
8883       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8884                                     LHSVecType->getElementType(), LHSType,
8885                                     DiagID))
8886         return LHSType;
8887     } else {
8888       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8889         return LHSType;
8890     }
8891   }
8892   if (!LHSVecType) {
8893     if (isa<ExtVectorType>(RHSVecType)) {
8894       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8895                                     LHSType, RHSVecType->getElementType(),
8896                                     RHSType, DiagID))
8897         return RHSType;
8898     } else {
8899       if (LHS.get()->getValueKind() == VK_LValue ||
8900           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8901         return RHSType;
8902     }
8903   }
8904 
8905   // FIXME: The code below also handles conversion between vectors and
8906   // non-scalars, we should break this down into fine grained specific checks
8907   // and emit proper diagnostics.
8908   QualType VecType = LHSVecType ? LHSType : RHSType;
8909   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8910   QualType OtherType = LHSVecType ? RHSType : LHSType;
8911   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8912   if (isLaxVectorConversion(OtherType, VecType)) {
8913     // If we're allowing lax vector conversions, only the total (data) size
8914     // needs to be the same. For non compound assignment, if one of the types is
8915     // scalar, the result is always the vector type.
8916     if (!IsCompAssign) {
8917       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8918       return VecType;
8919     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8920     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8921     // type. Note that this is already done by non-compound assignments in
8922     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8923     // <1 x T> -> T. The result is also a vector type.
8924     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8925                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8926       ExprResult *RHSExpr = &RHS;
8927       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8928       return VecType;
8929     }
8930   }
8931 
8932   // Okay, the expression is invalid.
8933 
8934   // If there's a non-vector, non-real operand, diagnose that.
8935   if ((!RHSVecType && !RHSType->isRealType()) ||
8936       (!LHSVecType && !LHSType->isRealType())) {
8937     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8938       << LHSType << RHSType
8939       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8940     return QualType();
8941   }
8942 
8943   // OpenCL V1.1 6.2.6.p1:
8944   // If the operands are of more than one vector type, then an error shall
8945   // occur. Implicit conversions between vector types are not permitted, per
8946   // section 6.2.1.
8947   if (getLangOpts().OpenCL &&
8948       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8949       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8950     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8951                                                            << RHSType;
8952     return QualType();
8953   }
8954 
8955 
8956   // If there is a vector type that is not a ExtVector and a scalar, we reach
8957   // this point if scalar could not be converted to the vector's element type
8958   // without truncation.
8959   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8960       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8961     QualType Scalar = LHSVecType ? RHSType : LHSType;
8962     QualType Vector = LHSVecType ? LHSType : RHSType;
8963     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8964     Diag(Loc,
8965          diag::err_typecheck_vector_not_convertable_implict_truncation)
8966         << ScalarOrVector << Scalar << Vector;
8967 
8968     return QualType();
8969   }
8970 
8971   // Otherwise, use the generic diagnostic.
8972   Diag(Loc, DiagID)
8973     << LHSType << RHSType
8974     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8975   return QualType();
8976 }
8977 
8978 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8979 // expression.  These are mainly cases where the null pointer is used as an
8980 // integer instead of a pointer.
8981 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8982                                 SourceLocation Loc, bool IsCompare) {
8983   // The canonical way to check for a GNU null is with isNullPointerConstant,
8984   // but we use a bit of a hack here for speed; this is a relatively
8985   // hot path, and isNullPointerConstant is slow.
8986   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8987   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8988 
8989   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8990 
8991   // Avoid analyzing cases where the result will either be invalid (and
8992   // diagnosed as such) or entirely valid and not something to warn about.
8993   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8994       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8995     return;
8996 
8997   // Comparison operations would not make sense with a null pointer no matter
8998   // what the other expression is.
8999   if (!IsCompare) {
9000     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9001         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9002         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9003     return;
9004   }
9005 
9006   // The rest of the operations only make sense with a null pointer
9007   // if the other expression is a pointer.
9008   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9009       NonNullType->canDecayToPointerType())
9010     return;
9011 
9012   S.Diag(Loc, diag::warn_null_in_comparison_operation)
9013       << LHSNull /* LHS is NULL */ << NonNullType
9014       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9015 }
9016 
9017 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
9018                                           SourceLocation Loc) {
9019   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9020   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9021   if (!LUE || !RUE)
9022     return;
9023   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9024       RUE->getKind() != UETT_SizeOf)
9025     return;
9026 
9027   QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
9028   QualType RHSTy;
9029 
9030   if (RUE->isArgumentType())
9031     RHSTy = RUE->getArgumentType();
9032   else
9033     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9034 
9035   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
9036     return;
9037   if (LHSTy->getPointeeType() != RHSTy)
9038     return;
9039 
9040   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9041 }
9042 
9043 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9044                                                ExprResult &RHS,
9045                                                SourceLocation Loc, bool IsDiv) {
9046   // Check for division/remainder by zero.
9047   Expr::EvalResult RHSValue;
9048   if (!RHS.get()->isValueDependent() &&
9049       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9050       RHSValue.Val.getInt() == 0)
9051     S.DiagRuntimeBehavior(Loc, RHS.get(),
9052                           S.PDiag(diag::warn_remainder_division_by_zero)
9053                             << IsDiv << RHS.get()->getSourceRange());
9054 }
9055 
9056 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9057                                            SourceLocation Loc,
9058                                            bool IsCompAssign, bool IsDiv) {
9059   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9060 
9061   if (LHS.get()->getType()->isVectorType() ||
9062       RHS.get()->getType()->isVectorType())
9063     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9064                                /*AllowBothBool*/getLangOpts().AltiVec,
9065                                /*AllowBoolConversions*/false);
9066 
9067   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9068   if (LHS.isInvalid() || RHS.isInvalid())
9069     return QualType();
9070 
9071 
9072   if (compType.isNull() || !compType->isArithmeticType())
9073     return InvalidOperands(Loc, LHS, RHS);
9074   if (IsDiv) {
9075     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9076     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9077   }
9078   return compType;
9079 }
9080 
9081 QualType Sema::CheckRemainderOperands(
9082   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9083   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9084 
9085   if (LHS.get()->getType()->isVectorType() ||
9086       RHS.get()->getType()->isVectorType()) {
9087     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9088         RHS.get()->getType()->hasIntegerRepresentation())
9089       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9090                                  /*AllowBothBool*/getLangOpts().AltiVec,
9091                                  /*AllowBoolConversions*/false);
9092     return InvalidOperands(Loc, LHS, RHS);
9093   }
9094 
9095   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9096   if (LHS.isInvalid() || RHS.isInvalid())
9097     return QualType();
9098 
9099   if (compType.isNull() || !compType->isIntegerType())
9100     return InvalidOperands(Loc, LHS, RHS);
9101   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9102   return compType;
9103 }
9104 
9105 /// Diagnose invalid arithmetic on two void pointers.
9106 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9107                                                 Expr *LHSExpr, Expr *RHSExpr) {
9108   S.Diag(Loc, S.getLangOpts().CPlusPlus
9109                 ? diag::err_typecheck_pointer_arith_void_type
9110                 : diag::ext_gnu_void_ptr)
9111     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9112                             << RHSExpr->getSourceRange();
9113 }
9114 
9115 /// Diagnose invalid arithmetic on a void pointer.
9116 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9117                                             Expr *Pointer) {
9118   S.Diag(Loc, S.getLangOpts().CPlusPlus
9119                 ? diag::err_typecheck_pointer_arith_void_type
9120                 : diag::ext_gnu_void_ptr)
9121     << 0 /* one pointer */ << Pointer->getSourceRange();
9122 }
9123 
9124 /// Diagnose invalid arithmetic on a null pointer.
9125 ///
9126 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9127 /// idiom, which we recognize as a GNU extension.
9128 ///
9129 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9130                                             Expr *Pointer, bool IsGNUIdiom) {
9131   if (IsGNUIdiom)
9132     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9133       << Pointer->getSourceRange();
9134   else
9135     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9136       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9137 }
9138 
9139 /// Diagnose invalid arithmetic on two function pointers.
9140 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9141                                                     Expr *LHS, Expr *RHS) {
9142   assert(LHS->getType()->isAnyPointerType());
9143   assert(RHS->getType()->isAnyPointerType());
9144   S.Diag(Loc, S.getLangOpts().CPlusPlus
9145                 ? diag::err_typecheck_pointer_arith_function_type
9146                 : diag::ext_gnu_ptr_func_arith)
9147     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9148     // We only show the second type if it differs from the first.
9149     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9150                                                    RHS->getType())
9151     << RHS->getType()->getPointeeType()
9152     << LHS->getSourceRange() << RHS->getSourceRange();
9153 }
9154 
9155 /// Diagnose invalid arithmetic on a function pointer.
9156 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9157                                                 Expr *Pointer) {
9158   assert(Pointer->getType()->isAnyPointerType());
9159   S.Diag(Loc, S.getLangOpts().CPlusPlus
9160                 ? diag::err_typecheck_pointer_arith_function_type
9161                 : diag::ext_gnu_ptr_func_arith)
9162     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9163     << 0 /* one pointer, so only one type */
9164     << Pointer->getSourceRange();
9165 }
9166 
9167 /// Emit error if Operand is incomplete pointer type
9168 ///
9169 /// \returns True if pointer has incomplete type
9170 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9171                                                  Expr *Operand) {
9172   QualType ResType = Operand->getType();
9173   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9174     ResType = ResAtomicType->getValueType();
9175 
9176   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9177   QualType PointeeTy = ResType->getPointeeType();
9178   return S.RequireCompleteType(Loc, PointeeTy,
9179                                diag::err_typecheck_arithmetic_incomplete_type,
9180                                PointeeTy, Operand->getSourceRange());
9181 }
9182 
9183 /// Check the validity of an arithmetic pointer operand.
9184 ///
9185 /// If the operand has pointer type, this code will check for pointer types
9186 /// which are invalid in arithmetic operations. These will be diagnosed
9187 /// appropriately, including whether or not the use is supported as an
9188 /// extension.
9189 ///
9190 /// \returns True when the operand is valid to use (even if as an extension).
9191 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9192                                             Expr *Operand) {
9193   QualType ResType = Operand->getType();
9194   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9195     ResType = ResAtomicType->getValueType();
9196 
9197   if (!ResType->isAnyPointerType()) return true;
9198 
9199   QualType PointeeTy = ResType->getPointeeType();
9200   if (PointeeTy->isVoidType()) {
9201     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9202     return !S.getLangOpts().CPlusPlus;
9203   }
9204   if (PointeeTy->isFunctionType()) {
9205     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9206     return !S.getLangOpts().CPlusPlus;
9207   }
9208 
9209   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9210 
9211   return true;
9212 }
9213 
9214 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9215 /// operands.
9216 ///
9217 /// This routine will diagnose any invalid arithmetic on pointer operands much
9218 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9219 /// for emitting a single diagnostic even for operations where both LHS and RHS
9220 /// are (potentially problematic) pointers.
9221 ///
9222 /// \returns True when the operand is valid to use (even if as an extension).
9223 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9224                                                 Expr *LHSExpr, Expr *RHSExpr) {
9225   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9226   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9227   if (!isLHSPointer && !isRHSPointer) return true;
9228 
9229   QualType LHSPointeeTy, RHSPointeeTy;
9230   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9231   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9232 
9233   // if both are pointers check if operation is valid wrt address spaces
9234   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9235     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9236     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9237     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9238       S.Diag(Loc,
9239              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9240           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9241           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9242       return false;
9243     }
9244   }
9245 
9246   // Check for arithmetic on pointers to incomplete types.
9247   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9248   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9249   if (isLHSVoidPtr || isRHSVoidPtr) {
9250     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9251     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9252     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9253 
9254     return !S.getLangOpts().CPlusPlus;
9255   }
9256 
9257   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9258   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9259   if (isLHSFuncPtr || isRHSFuncPtr) {
9260     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9261     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9262                                                                 RHSExpr);
9263     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9264 
9265     return !S.getLangOpts().CPlusPlus;
9266   }
9267 
9268   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9269     return false;
9270   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9271     return false;
9272 
9273   return true;
9274 }
9275 
9276 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9277 /// literal.
9278 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9279                                   Expr *LHSExpr, Expr *RHSExpr) {
9280   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9281   Expr* IndexExpr = RHSExpr;
9282   if (!StrExpr) {
9283     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9284     IndexExpr = LHSExpr;
9285   }
9286 
9287   bool IsStringPlusInt = StrExpr &&
9288       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9289   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9290     return;
9291 
9292   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9293   Self.Diag(OpLoc, diag::warn_string_plus_int)
9294       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9295 
9296   // Only print a fixit for "str" + int, not for int + "str".
9297   if (IndexExpr == RHSExpr) {
9298     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9299     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9300         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9301         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9302         << FixItHint::CreateInsertion(EndLoc, "]");
9303   } else
9304     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9305 }
9306 
9307 /// Emit a warning when adding a char literal to a string.
9308 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9309                                    Expr *LHSExpr, Expr *RHSExpr) {
9310   const Expr *StringRefExpr = LHSExpr;
9311   const CharacterLiteral *CharExpr =
9312       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9313 
9314   if (!CharExpr) {
9315     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9316     StringRefExpr = RHSExpr;
9317   }
9318 
9319   if (!CharExpr || !StringRefExpr)
9320     return;
9321 
9322   const QualType StringType = StringRefExpr->getType();
9323 
9324   // Return if not a PointerType.
9325   if (!StringType->isAnyPointerType())
9326     return;
9327 
9328   // Return if not a CharacterType.
9329   if (!StringType->getPointeeType()->isAnyCharacterType())
9330     return;
9331 
9332   ASTContext &Ctx = Self.getASTContext();
9333   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9334 
9335   const QualType CharType = CharExpr->getType();
9336   if (!CharType->isAnyCharacterType() &&
9337       CharType->isIntegerType() &&
9338       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9339     Self.Diag(OpLoc, diag::warn_string_plus_char)
9340         << DiagRange << Ctx.CharTy;
9341   } else {
9342     Self.Diag(OpLoc, diag::warn_string_plus_char)
9343         << DiagRange << CharExpr->getType();
9344   }
9345 
9346   // Only print a fixit for str + char, not for char + str.
9347   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9348     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9349     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9350         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9351         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9352         << FixItHint::CreateInsertion(EndLoc, "]");
9353   } else {
9354     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9355   }
9356 }
9357 
9358 /// Emit error when two pointers are incompatible.
9359 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9360                                            Expr *LHSExpr, Expr *RHSExpr) {
9361   assert(LHSExpr->getType()->isAnyPointerType());
9362   assert(RHSExpr->getType()->isAnyPointerType());
9363   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9364     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9365     << RHSExpr->getSourceRange();
9366 }
9367 
9368 // C99 6.5.6
9369 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9370                                      SourceLocation Loc, BinaryOperatorKind Opc,
9371                                      QualType* CompLHSTy) {
9372   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9373 
9374   if (LHS.get()->getType()->isVectorType() ||
9375       RHS.get()->getType()->isVectorType()) {
9376     QualType compType = CheckVectorOperands(
9377         LHS, RHS, Loc, CompLHSTy,
9378         /*AllowBothBool*/getLangOpts().AltiVec,
9379         /*AllowBoolConversions*/getLangOpts().ZVector);
9380     if (CompLHSTy) *CompLHSTy = compType;
9381     return compType;
9382   }
9383 
9384   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9385   if (LHS.isInvalid() || RHS.isInvalid())
9386     return QualType();
9387 
9388   // Diagnose "string literal" '+' int and string '+' "char literal".
9389   if (Opc == BO_Add) {
9390     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9391     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9392   }
9393 
9394   // handle the common case first (both operands are arithmetic).
9395   if (!compType.isNull() && compType->isArithmeticType()) {
9396     if (CompLHSTy) *CompLHSTy = compType;
9397     return compType;
9398   }
9399 
9400   // Type-checking.  Ultimately the pointer's going to be in PExp;
9401   // note that we bias towards the LHS being the pointer.
9402   Expr *PExp = LHS.get(), *IExp = RHS.get();
9403 
9404   bool isObjCPointer;
9405   if (PExp->getType()->isPointerType()) {
9406     isObjCPointer = false;
9407   } else if (PExp->getType()->isObjCObjectPointerType()) {
9408     isObjCPointer = true;
9409   } else {
9410     std::swap(PExp, IExp);
9411     if (PExp->getType()->isPointerType()) {
9412       isObjCPointer = false;
9413     } else if (PExp->getType()->isObjCObjectPointerType()) {
9414       isObjCPointer = true;
9415     } else {
9416       return InvalidOperands(Loc, LHS, RHS);
9417     }
9418   }
9419   assert(PExp->getType()->isAnyPointerType());
9420 
9421   if (!IExp->getType()->isIntegerType())
9422     return InvalidOperands(Loc, LHS, RHS);
9423 
9424   // Adding to a null pointer results in undefined behavior.
9425   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9426           Context, Expr::NPC_ValueDependentIsNotNull)) {
9427     // In C++ adding zero to a null pointer is defined.
9428     Expr::EvalResult KnownVal;
9429     if (!getLangOpts().CPlusPlus ||
9430         (!IExp->isValueDependent() &&
9431          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9432           KnownVal.Val.getInt() != 0))) {
9433       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9434       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9435           Context, BO_Add, PExp, IExp);
9436       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9437     }
9438   }
9439 
9440   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9441     return QualType();
9442 
9443   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9444     return QualType();
9445 
9446   // Check array bounds for pointer arithemtic
9447   CheckArrayAccess(PExp, IExp);
9448 
9449   if (CompLHSTy) {
9450     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9451     if (LHSTy.isNull()) {
9452       LHSTy = LHS.get()->getType();
9453       if (LHSTy->isPromotableIntegerType())
9454         LHSTy = Context.getPromotedIntegerType(LHSTy);
9455     }
9456     *CompLHSTy = LHSTy;
9457   }
9458 
9459   return PExp->getType();
9460 }
9461 
9462 // C99 6.5.6
9463 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9464                                         SourceLocation Loc,
9465                                         QualType* CompLHSTy) {
9466   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9467 
9468   if (LHS.get()->getType()->isVectorType() ||
9469       RHS.get()->getType()->isVectorType()) {
9470     QualType compType = CheckVectorOperands(
9471         LHS, RHS, Loc, CompLHSTy,
9472         /*AllowBothBool*/getLangOpts().AltiVec,
9473         /*AllowBoolConversions*/getLangOpts().ZVector);
9474     if (CompLHSTy) *CompLHSTy = compType;
9475     return compType;
9476   }
9477 
9478   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9479   if (LHS.isInvalid() || RHS.isInvalid())
9480     return QualType();
9481 
9482   // Enforce type constraints: C99 6.5.6p3.
9483 
9484   // Handle the common case first (both operands are arithmetic).
9485   if (!compType.isNull() && compType->isArithmeticType()) {
9486     if (CompLHSTy) *CompLHSTy = compType;
9487     return compType;
9488   }
9489 
9490   // Either ptr - int   or   ptr - ptr.
9491   if (LHS.get()->getType()->isAnyPointerType()) {
9492     QualType lpointee = LHS.get()->getType()->getPointeeType();
9493 
9494     // Diagnose bad cases where we step over interface counts.
9495     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9496         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9497       return QualType();
9498 
9499     // The result type of a pointer-int computation is the pointer type.
9500     if (RHS.get()->getType()->isIntegerType()) {
9501       // Subtracting from a null pointer should produce a warning.
9502       // The last argument to the diagnose call says this doesn't match the
9503       // GNU int-to-pointer idiom.
9504       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9505                                            Expr::NPC_ValueDependentIsNotNull)) {
9506         // In C++ adding zero to a null pointer is defined.
9507         Expr::EvalResult KnownVal;
9508         if (!getLangOpts().CPlusPlus ||
9509             (!RHS.get()->isValueDependent() &&
9510              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9511               KnownVal.Val.getInt() != 0))) {
9512           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9513         }
9514       }
9515 
9516       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9517         return QualType();
9518 
9519       // Check array bounds for pointer arithemtic
9520       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9521                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9522 
9523       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9524       return LHS.get()->getType();
9525     }
9526 
9527     // Handle pointer-pointer subtractions.
9528     if (const PointerType *RHSPTy
9529           = RHS.get()->getType()->getAs<PointerType>()) {
9530       QualType rpointee = RHSPTy->getPointeeType();
9531 
9532       if (getLangOpts().CPlusPlus) {
9533         // Pointee types must be the same: C++ [expr.add]
9534         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9535           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9536         }
9537       } else {
9538         // Pointee types must be compatible C99 6.5.6p3
9539         if (!Context.typesAreCompatible(
9540                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9541                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9542           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9543           return QualType();
9544         }
9545       }
9546 
9547       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9548                                                LHS.get(), RHS.get()))
9549         return QualType();
9550 
9551       // FIXME: Add warnings for nullptr - ptr.
9552 
9553       // The pointee type may have zero size.  As an extension, a structure or
9554       // union may have zero size or an array may have zero length.  In this
9555       // case subtraction does not make sense.
9556       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9557         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9558         if (ElementSize.isZero()) {
9559           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9560             << rpointee.getUnqualifiedType()
9561             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9562         }
9563       }
9564 
9565       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9566       return Context.getPointerDiffType();
9567     }
9568   }
9569 
9570   return InvalidOperands(Loc, LHS, RHS);
9571 }
9572 
9573 static bool isScopedEnumerationType(QualType T) {
9574   if (const EnumType *ET = T->getAs<EnumType>())
9575     return ET->getDecl()->isScoped();
9576   return false;
9577 }
9578 
9579 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9580                                    SourceLocation Loc, BinaryOperatorKind Opc,
9581                                    QualType LHSType) {
9582   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9583   // so skip remaining warnings as we don't want to modify values within Sema.
9584   if (S.getLangOpts().OpenCL)
9585     return;
9586 
9587   // Check right/shifter operand
9588   Expr::EvalResult RHSResult;
9589   if (RHS.get()->isValueDependent() ||
9590       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9591     return;
9592   llvm::APSInt Right = RHSResult.Val.getInt();
9593 
9594   if (Right.isNegative()) {
9595     S.DiagRuntimeBehavior(Loc, RHS.get(),
9596                           S.PDiag(diag::warn_shift_negative)
9597                             << RHS.get()->getSourceRange());
9598     return;
9599   }
9600   llvm::APInt LeftBits(Right.getBitWidth(),
9601                        S.Context.getTypeSize(LHS.get()->getType()));
9602   if (Right.uge(LeftBits)) {
9603     S.DiagRuntimeBehavior(Loc, RHS.get(),
9604                           S.PDiag(diag::warn_shift_gt_typewidth)
9605                             << RHS.get()->getSourceRange());
9606     return;
9607   }
9608   if (Opc != BO_Shl)
9609     return;
9610 
9611   // When left shifting an ICE which is signed, we can check for overflow which
9612   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9613   // integers have defined behavior modulo one more than the maximum value
9614   // representable in the result type, so never warn for those.
9615   Expr::EvalResult LHSResult;
9616   if (LHS.get()->isValueDependent() ||
9617       LHSType->hasUnsignedIntegerRepresentation() ||
9618       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9619     return;
9620   llvm::APSInt Left = LHSResult.Val.getInt();
9621 
9622   // If LHS does not have a signed type and non-negative value
9623   // then, the behavior is undefined. Warn about it.
9624   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9625     S.DiagRuntimeBehavior(Loc, LHS.get(),
9626                           S.PDiag(diag::warn_shift_lhs_negative)
9627                             << LHS.get()->getSourceRange());
9628     return;
9629   }
9630 
9631   llvm::APInt ResultBits =
9632       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9633   if (LeftBits.uge(ResultBits))
9634     return;
9635   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9636   Result = Result.shl(Right);
9637 
9638   // Print the bit representation of the signed integer as an unsigned
9639   // hexadecimal number.
9640   SmallString<40> HexResult;
9641   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9642 
9643   // If we are only missing a sign bit, this is less likely to result in actual
9644   // bugs -- if the result is cast back to an unsigned type, it will have the
9645   // expected value. Thus we place this behind a different warning that can be
9646   // turned off separately if needed.
9647   if (LeftBits == ResultBits - 1) {
9648     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9649         << HexResult << LHSType
9650         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9651     return;
9652   }
9653 
9654   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9655     << HexResult.str() << Result.getMinSignedBits() << LHSType
9656     << Left.getBitWidth() << LHS.get()->getSourceRange()
9657     << RHS.get()->getSourceRange();
9658 }
9659 
9660 /// Return the resulting type when a vector is shifted
9661 ///        by a scalar or vector shift amount.
9662 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9663                                  SourceLocation Loc, bool IsCompAssign) {
9664   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9665   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9666       !LHS.get()->getType()->isVectorType()) {
9667     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9668       << RHS.get()->getType() << LHS.get()->getType()
9669       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9670     return QualType();
9671   }
9672 
9673   if (!IsCompAssign) {
9674     LHS = S.UsualUnaryConversions(LHS.get());
9675     if (LHS.isInvalid()) return QualType();
9676   }
9677 
9678   RHS = S.UsualUnaryConversions(RHS.get());
9679   if (RHS.isInvalid()) return QualType();
9680 
9681   QualType LHSType = LHS.get()->getType();
9682   // Note that LHS might be a scalar because the routine calls not only in
9683   // OpenCL case.
9684   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9685   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9686 
9687   // Note that RHS might not be a vector.
9688   QualType RHSType = RHS.get()->getType();
9689   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9690   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9691 
9692   // The operands need to be integers.
9693   if (!LHSEleType->isIntegerType()) {
9694     S.Diag(Loc, diag::err_typecheck_expect_int)
9695       << LHS.get()->getType() << LHS.get()->getSourceRange();
9696     return QualType();
9697   }
9698 
9699   if (!RHSEleType->isIntegerType()) {
9700     S.Diag(Loc, diag::err_typecheck_expect_int)
9701       << RHS.get()->getType() << RHS.get()->getSourceRange();
9702     return QualType();
9703   }
9704 
9705   if (!LHSVecTy) {
9706     assert(RHSVecTy);
9707     if (IsCompAssign)
9708       return RHSType;
9709     if (LHSEleType != RHSEleType) {
9710       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9711       LHSEleType = RHSEleType;
9712     }
9713     QualType VecTy =
9714         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9715     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9716     LHSType = VecTy;
9717   } else if (RHSVecTy) {
9718     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9719     // are applied component-wise. So if RHS is a vector, then ensure
9720     // that the number of elements is the same as LHS...
9721     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9722       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9723         << LHS.get()->getType() << RHS.get()->getType()
9724         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9725       return QualType();
9726     }
9727     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9728       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9729       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9730       if (LHSBT != RHSBT &&
9731           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9732         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9733             << LHS.get()->getType() << RHS.get()->getType()
9734             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9735       }
9736     }
9737   } else {
9738     // ...else expand RHS to match the number of elements in LHS.
9739     QualType VecTy =
9740       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9741     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9742   }
9743 
9744   return LHSType;
9745 }
9746 
9747 // C99 6.5.7
9748 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9749                                   SourceLocation Loc, BinaryOperatorKind Opc,
9750                                   bool IsCompAssign) {
9751   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9752 
9753   // Vector shifts promote their scalar inputs to vector type.
9754   if (LHS.get()->getType()->isVectorType() ||
9755       RHS.get()->getType()->isVectorType()) {
9756     if (LangOpts.ZVector) {
9757       // The shift operators for the z vector extensions work basically
9758       // like general shifts, except that neither the LHS nor the RHS is
9759       // allowed to be a "vector bool".
9760       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9761         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9762           return InvalidOperands(Loc, LHS, RHS);
9763       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9764         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9765           return InvalidOperands(Loc, LHS, RHS);
9766     }
9767     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9768   }
9769 
9770   // Shifts don't perform usual arithmetic conversions, they just do integer
9771   // promotions on each operand. C99 6.5.7p3
9772 
9773   // For the LHS, do usual unary conversions, but then reset them away
9774   // if this is a compound assignment.
9775   ExprResult OldLHS = LHS;
9776   LHS = UsualUnaryConversions(LHS.get());
9777   if (LHS.isInvalid())
9778     return QualType();
9779   QualType LHSType = LHS.get()->getType();
9780   if (IsCompAssign) LHS = OldLHS;
9781 
9782   // The RHS is simpler.
9783   RHS = UsualUnaryConversions(RHS.get());
9784   if (RHS.isInvalid())
9785     return QualType();
9786   QualType RHSType = RHS.get()->getType();
9787 
9788   // C99 6.5.7p2: Each of the operands shall have integer type.
9789   if (!LHSType->hasIntegerRepresentation() ||
9790       !RHSType->hasIntegerRepresentation())
9791     return InvalidOperands(Loc, LHS, RHS);
9792 
9793   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9794   // hasIntegerRepresentation() above instead of this.
9795   if (isScopedEnumerationType(LHSType) ||
9796       isScopedEnumerationType(RHSType)) {
9797     return InvalidOperands(Loc, LHS, RHS);
9798   }
9799   // Sanity-check shift operands
9800   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9801 
9802   // "The type of the result is that of the promoted left operand."
9803   return LHSType;
9804 }
9805 
9806 /// If two different enums are compared, raise a warning.
9807 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9808                                 Expr *RHS) {
9809   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9810   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9811 
9812   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9813   if (!LHSEnumType)
9814     return;
9815   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9816   if (!RHSEnumType)
9817     return;
9818 
9819   // Ignore anonymous enums.
9820   if (!LHSEnumType->getDecl()->getIdentifier() &&
9821       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9822     return;
9823   if (!RHSEnumType->getDecl()->getIdentifier() &&
9824       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9825     return;
9826 
9827   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9828     return;
9829 
9830   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9831       << LHSStrippedType << RHSStrippedType
9832       << LHS->getSourceRange() << RHS->getSourceRange();
9833 }
9834 
9835 /// Diagnose bad pointer comparisons.
9836 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9837                                               ExprResult &LHS, ExprResult &RHS,
9838                                               bool IsError) {
9839   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9840                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9841     << LHS.get()->getType() << RHS.get()->getType()
9842     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9843 }
9844 
9845 /// Returns false if the pointers are converted to a composite type,
9846 /// true otherwise.
9847 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9848                                            ExprResult &LHS, ExprResult &RHS) {
9849   // C++ [expr.rel]p2:
9850   //   [...] Pointer conversions (4.10) and qualification
9851   //   conversions (4.4) are performed on pointer operands (or on
9852   //   a pointer operand and a null pointer constant) to bring
9853   //   them to their composite pointer type. [...]
9854   //
9855   // C++ [expr.eq]p1 uses the same notion for (in)equality
9856   // comparisons of pointers.
9857 
9858   QualType LHSType = LHS.get()->getType();
9859   QualType RHSType = RHS.get()->getType();
9860   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9861          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9862 
9863   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9864   if (T.isNull()) {
9865     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9866         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9867       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9868     else
9869       S.InvalidOperands(Loc, LHS, RHS);
9870     return true;
9871   }
9872 
9873   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9874   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9875   return false;
9876 }
9877 
9878 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9879                                                     ExprResult &LHS,
9880                                                     ExprResult &RHS,
9881                                                     bool IsError) {
9882   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9883                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9884     << LHS.get()->getType() << RHS.get()->getType()
9885     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9886 }
9887 
9888 static bool isObjCObjectLiteral(ExprResult &E) {
9889   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9890   case Stmt::ObjCArrayLiteralClass:
9891   case Stmt::ObjCDictionaryLiteralClass:
9892   case Stmt::ObjCStringLiteralClass:
9893   case Stmt::ObjCBoxedExprClass:
9894     return true;
9895   default:
9896     // Note that ObjCBoolLiteral is NOT an object literal!
9897     return false;
9898   }
9899 }
9900 
9901 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9902   const ObjCObjectPointerType *Type =
9903     LHS->getType()->getAs<ObjCObjectPointerType>();
9904 
9905   // If this is not actually an Objective-C object, bail out.
9906   if (!Type)
9907     return false;
9908 
9909   // Get the LHS object's interface type.
9910   QualType InterfaceType = Type->getPointeeType();
9911 
9912   // If the RHS isn't an Objective-C object, bail out.
9913   if (!RHS->getType()->isObjCObjectPointerType())
9914     return false;
9915 
9916   // Try to find the -isEqual: method.
9917   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9918   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9919                                                       InterfaceType,
9920                                                       /*instance=*/true);
9921   if (!Method) {
9922     if (Type->isObjCIdType()) {
9923       // For 'id', just check the global pool.
9924       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9925                                                   /*receiverId=*/true);
9926     } else {
9927       // Check protocols.
9928       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9929                                              /*instance=*/true);
9930     }
9931   }
9932 
9933   if (!Method)
9934     return false;
9935 
9936   QualType T = Method->parameters()[0]->getType();
9937   if (!T->isObjCObjectPointerType())
9938     return false;
9939 
9940   QualType R = Method->getReturnType();
9941   if (!R->isScalarType())
9942     return false;
9943 
9944   return true;
9945 }
9946 
9947 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9948   FromE = FromE->IgnoreParenImpCasts();
9949   switch (FromE->getStmtClass()) {
9950     default:
9951       break;
9952     case Stmt::ObjCStringLiteralClass:
9953       // "string literal"
9954       return LK_String;
9955     case Stmt::ObjCArrayLiteralClass:
9956       // "array literal"
9957       return LK_Array;
9958     case Stmt::ObjCDictionaryLiteralClass:
9959       // "dictionary literal"
9960       return LK_Dictionary;
9961     case Stmt::BlockExprClass:
9962       return LK_Block;
9963     case Stmt::ObjCBoxedExprClass: {
9964       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9965       switch (Inner->getStmtClass()) {
9966         case Stmt::IntegerLiteralClass:
9967         case Stmt::FloatingLiteralClass:
9968         case Stmt::CharacterLiteralClass:
9969         case Stmt::ObjCBoolLiteralExprClass:
9970         case Stmt::CXXBoolLiteralExprClass:
9971           // "numeric literal"
9972           return LK_Numeric;
9973         case Stmt::ImplicitCastExprClass: {
9974           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9975           // Boolean literals can be represented by implicit casts.
9976           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9977             return LK_Numeric;
9978           break;
9979         }
9980         default:
9981           break;
9982       }
9983       return LK_Boxed;
9984     }
9985   }
9986   return LK_None;
9987 }
9988 
9989 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9990                                           ExprResult &LHS, ExprResult &RHS,
9991                                           BinaryOperator::Opcode Opc){
9992   Expr *Literal;
9993   Expr *Other;
9994   if (isObjCObjectLiteral(LHS)) {
9995     Literal = LHS.get();
9996     Other = RHS.get();
9997   } else {
9998     Literal = RHS.get();
9999     Other = LHS.get();
10000   }
10001 
10002   // Don't warn on comparisons against nil.
10003   Other = Other->IgnoreParenCasts();
10004   if (Other->isNullPointerConstant(S.getASTContext(),
10005                                    Expr::NPC_ValueDependentIsNotNull))
10006     return;
10007 
10008   // This should be kept in sync with warn_objc_literal_comparison.
10009   // LK_String should always be after the other literals, since it has its own
10010   // warning flag.
10011   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10012   assert(LiteralKind != Sema::LK_Block);
10013   if (LiteralKind == Sema::LK_None) {
10014     llvm_unreachable("Unknown Objective-C object literal kind");
10015   }
10016 
10017   if (LiteralKind == Sema::LK_String)
10018     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10019       << Literal->getSourceRange();
10020   else
10021     S.Diag(Loc, diag::warn_objc_literal_comparison)
10022       << LiteralKind << Literal->getSourceRange();
10023 
10024   if (BinaryOperator::isEqualityOp(Opc) &&
10025       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10026     SourceLocation Start = LHS.get()->getBeginLoc();
10027     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10028     CharSourceRange OpRange =
10029       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10030 
10031     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10032       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10033       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10034       << FixItHint::CreateInsertion(End, "]");
10035   }
10036 }
10037 
10038 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10039 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10040                                            ExprResult &RHS, SourceLocation Loc,
10041                                            BinaryOperatorKind Opc) {
10042   // Check that left hand side is !something.
10043   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10044   if (!UO || UO->getOpcode() != UO_LNot) return;
10045 
10046   // Only check if the right hand side is non-bool arithmetic type.
10047   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10048 
10049   // Make sure that the something in !something is not bool.
10050   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10051   if (SubExpr->isKnownToHaveBooleanValue()) return;
10052 
10053   // Emit warning.
10054   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10055   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10056       << Loc << IsBitwiseOp;
10057 
10058   // First note suggest !(x < y)
10059   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10060   SourceLocation FirstClose = RHS.get()->getEndLoc();
10061   FirstClose = S.getLocForEndOfToken(FirstClose);
10062   if (FirstClose.isInvalid())
10063     FirstOpen = SourceLocation();
10064   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10065       << IsBitwiseOp
10066       << FixItHint::CreateInsertion(FirstOpen, "(")
10067       << FixItHint::CreateInsertion(FirstClose, ")");
10068 
10069   // Second note suggests (!x) < y
10070   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10071   SourceLocation SecondClose = LHS.get()->getEndLoc();
10072   SecondClose = S.getLocForEndOfToken(SecondClose);
10073   if (SecondClose.isInvalid())
10074     SecondOpen = SourceLocation();
10075   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10076       << FixItHint::CreateInsertion(SecondOpen, "(")
10077       << FixItHint::CreateInsertion(SecondClose, ")");
10078 }
10079 
10080 // Get the decl for a simple expression: a reference to a variable,
10081 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10082 static ValueDecl *getCompareDecl(Expr *E) {
10083   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10084     return DR->getDecl();
10085   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10086     if (Ivar->isFreeIvar())
10087       return Ivar->getDecl();
10088   }
10089   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10090     if (Mem->isImplicitAccess())
10091       return Mem->getMemberDecl();
10092   }
10093   return nullptr;
10094 }
10095 
10096 /// Diagnose some forms of syntactically-obvious tautological comparison.
10097 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10098                                            Expr *LHS, Expr *RHS,
10099                                            BinaryOperatorKind Opc) {
10100   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10101   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10102 
10103   QualType LHSType = LHS->getType();
10104   QualType RHSType = RHS->getType();
10105   if (LHSType->hasFloatingRepresentation() ||
10106       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10107       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10108       S.inTemplateInstantiation())
10109     return;
10110 
10111   // Comparisons between two array types are ill-formed for operator<=>, so
10112   // we shouldn't emit any additional warnings about it.
10113   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10114     return;
10115 
10116   // For non-floating point types, check for self-comparisons of the form
10117   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10118   // often indicate logic errors in the program.
10119   //
10120   // NOTE: Don't warn about comparison expressions resulting from macro
10121   // expansion. Also don't warn about comparisons which are only self
10122   // comparisons within a template instantiation. The warnings should catch
10123   // obvious cases in the definition of the template anyways. The idea is to
10124   // warn when the typed comparison operator will always evaluate to the same
10125   // result.
10126   ValueDecl *DL = getCompareDecl(LHSStripped);
10127   ValueDecl *DR = getCompareDecl(RHSStripped);
10128   if (DL && DR && declaresSameEntity(DL, DR)) {
10129     StringRef Result;
10130     switch (Opc) {
10131     case BO_EQ: case BO_LE: case BO_GE:
10132       Result = "true";
10133       break;
10134     case BO_NE: case BO_LT: case BO_GT:
10135       Result = "false";
10136       break;
10137     case BO_Cmp:
10138       Result = "'std::strong_ordering::equal'";
10139       break;
10140     default:
10141       break;
10142     }
10143     S.DiagRuntimeBehavior(Loc, nullptr,
10144                           S.PDiag(diag::warn_comparison_always)
10145                               << 0 /*self-comparison*/ << !Result.empty()
10146                               << Result);
10147   } else if (DL && DR &&
10148              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10149              !DL->isWeak() && !DR->isWeak()) {
10150     // What is it always going to evaluate to?
10151     StringRef Result;
10152     switch(Opc) {
10153     case BO_EQ: // e.g. array1 == array2
10154       Result = "false";
10155       break;
10156     case BO_NE: // e.g. array1 != array2
10157       Result = "true";
10158       break;
10159     default: // e.g. array1 <= array2
10160       // The best we can say is 'a constant'
10161       break;
10162     }
10163     S.DiagRuntimeBehavior(Loc, nullptr,
10164                           S.PDiag(diag::warn_comparison_always)
10165                               << 1 /*array comparison*/
10166                               << !Result.empty() << Result);
10167   }
10168 
10169   if (isa<CastExpr>(LHSStripped))
10170     LHSStripped = LHSStripped->IgnoreParenCasts();
10171   if (isa<CastExpr>(RHSStripped))
10172     RHSStripped = RHSStripped->IgnoreParenCasts();
10173 
10174   // Warn about comparisons against a string constant (unless the other
10175   // operand is null); the user probably wants strcmp.
10176   Expr *LiteralString = nullptr;
10177   Expr *LiteralStringStripped = nullptr;
10178   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10179       !RHSStripped->isNullPointerConstant(S.Context,
10180                                           Expr::NPC_ValueDependentIsNull)) {
10181     LiteralString = LHS;
10182     LiteralStringStripped = LHSStripped;
10183   } else if ((isa<StringLiteral>(RHSStripped) ||
10184               isa<ObjCEncodeExpr>(RHSStripped)) &&
10185              !LHSStripped->isNullPointerConstant(S.Context,
10186                                           Expr::NPC_ValueDependentIsNull)) {
10187     LiteralString = RHS;
10188     LiteralStringStripped = RHSStripped;
10189   }
10190 
10191   if (LiteralString) {
10192     S.DiagRuntimeBehavior(Loc, nullptr,
10193                           S.PDiag(diag::warn_stringcompare)
10194                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10195                               << LiteralString->getSourceRange());
10196   }
10197 }
10198 
10199 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10200   switch (CK) {
10201   default: {
10202 #ifndef NDEBUG
10203     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10204                  << "\n";
10205 #endif
10206     llvm_unreachable("unhandled cast kind");
10207   }
10208   case CK_UserDefinedConversion:
10209     return ICK_Identity;
10210   case CK_LValueToRValue:
10211     return ICK_Lvalue_To_Rvalue;
10212   case CK_ArrayToPointerDecay:
10213     return ICK_Array_To_Pointer;
10214   case CK_FunctionToPointerDecay:
10215     return ICK_Function_To_Pointer;
10216   case CK_IntegralCast:
10217     return ICK_Integral_Conversion;
10218   case CK_FloatingCast:
10219     return ICK_Floating_Conversion;
10220   case CK_IntegralToFloating:
10221   case CK_FloatingToIntegral:
10222     return ICK_Floating_Integral;
10223   case CK_IntegralComplexCast:
10224   case CK_FloatingComplexCast:
10225   case CK_FloatingComplexToIntegralComplex:
10226   case CK_IntegralComplexToFloatingComplex:
10227     return ICK_Complex_Conversion;
10228   case CK_FloatingComplexToReal:
10229   case CK_FloatingRealToComplex:
10230   case CK_IntegralComplexToReal:
10231   case CK_IntegralRealToComplex:
10232     return ICK_Complex_Real;
10233   }
10234 }
10235 
10236 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10237                                              QualType FromType,
10238                                              SourceLocation Loc) {
10239   // Check for a narrowing implicit conversion.
10240   StandardConversionSequence SCS;
10241   SCS.setAsIdentityConversion();
10242   SCS.setToType(0, FromType);
10243   SCS.setToType(1, ToType);
10244   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10245     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10246 
10247   APValue PreNarrowingValue;
10248   QualType PreNarrowingType;
10249   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10250                                PreNarrowingType,
10251                                /*IgnoreFloatToIntegralConversion*/ true)) {
10252   case NK_Dependent_Narrowing:
10253     // Implicit conversion to a narrower type, but the expression is
10254     // value-dependent so we can't tell whether it's actually narrowing.
10255   case NK_Not_Narrowing:
10256     return false;
10257 
10258   case NK_Constant_Narrowing:
10259     // Implicit conversion to a narrower type, and the value is not a constant
10260     // expression.
10261     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10262         << /*Constant*/ 1
10263         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10264     return true;
10265 
10266   case NK_Variable_Narrowing:
10267     // Implicit conversion to a narrower type, and the value is not a constant
10268     // expression.
10269   case NK_Type_Narrowing:
10270     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10271         << /*Constant*/ 0 << FromType << ToType;
10272     // TODO: It's not a constant expression, but what if the user intended it
10273     // to be? Can we produce notes to help them figure out why it isn't?
10274     return true;
10275   }
10276   llvm_unreachable("unhandled case in switch");
10277 }
10278 
10279 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10280                                                          ExprResult &LHS,
10281                                                          ExprResult &RHS,
10282                                                          SourceLocation Loc) {
10283   using CCT = ComparisonCategoryType;
10284 
10285   QualType LHSType = LHS.get()->getType();
10286   QualType RHSType = RHS.get()->getType();
10287   // Dig out the original argument type and expression before implicit casts
10288   // were applied. These are the types/expressions we need to check the
10289   // [expr.spaceship] requirements against.
10290   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10291   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10292   QualType LHSStrippedType = LHSStripped.get()->getType();
10293   QualType RHSStrippedType = RHSStripped.get()->getType();
10294 
10295   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10296   // other is not, the program is ill-formed.
10297   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10298     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10299     return QualType();
10300   }
10301 
10302   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10303                     RHSStrippedType->isEnumeralType();
10304   if (NumEnumArgs == 1) {
10305     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10306     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10307     if (OtherTy->hasFloatingRepresentation()) {
10308       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10309       return QualType();
10310     }
10311   }
10312   if (NumEnumArgs == 2) {
10313     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10314     // type E, the operator yields the result of converting the operands
10315     // to the underlying type of E and applying <=> to the converted operands.
10316     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10317       S.InvalidOperands(Loc, LHS, RHS);
10318       return QualType();
10319     }
10320     QualType IntType =
10321         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10322     assert(IntType->isArithmeticType());
10323 
10324     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10325     // promote the boolean type, and all other promotable integer types, to
10326     // avoid this.
10327     if (IntType->isPromotableIntegerType())
10328       IntType = S.Context.getPromotedIntegerType(IntType);
10329 
10330     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10331     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10332     LHSType = RHSType = IntType;
10333   }
10334 
10335   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10336   // usual arithmetic conversions are applied to the operands.
10337   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10338   if (LHS.isInvalid() || RHS.isInvalid())
10339     return QualType();
10340   if (Type.isNull())
10341     return S.InvalidOperands(Loc, LHS, RHS);
10342   assert(Type->isArithmeticType() || Type->isEnumeralType());
10343 
10344   bool HasNarrowing = checkThreeWayNarrowingConversion(
10345       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10346   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10347                                                    RHS.get()->getBeginLoc());
10348   if (HasNarrowing)
10349     return QualType();
10350 
10351   assert(!Type.isNull() && "composite type for <=> has not been set");
10352 
10353   auto TypeKind = [&]() {
10354     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10355       if (CT->getElementType()->hasFloatingRepresentation())
10356         return CCT::WeakEquality;
10357       return CCT::StrongEquality;
10358     }
10359     if (Type->isIntegralOrEnumerationType())
10360       return CCT::StrongOrdering;
10361     if (Type->hasFloatingRepresentation())
10362       return CCT::PartialOrdering;
10363     llvm_unreachable("other types are unimplemented");
10364   }();
10365 
10366   return S.CheckComparisonCategoryType(TypeKind, Loc);
10367 }
10368 
10369 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10370                                                  ExprResult &RHS,
10371                                                  SourceLocation Loc,
10372                                                  BinaryOperatorKind Opc) {
10373   if (Opc == BO_Cmp)
10374     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10375 
10376   // C99 6.5.8p3 / C99 6.5.9p4
10377   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10378   if (LHS.isInvalid() || RHS.isInvalid())
10379     return QualType();
10380   if (Type.isNull())
10381     return S.InvalidOperands(Loc, LHS, RHS);
10382   assert(Type->isArithmeticType() || Type->isEnumeralType());
10383 
10384   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10385 
10386   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10387     return S.InvalidOperands(Loc, LHS, RHS);
10388 
10389   // Check for comparisons of floating point operands using != and ==.
10390   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10391     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10392 
10393   // The result of comparisons is 'bool' in C++, 'int' in C.
10394   return S.Context.getLogicalOperationType();
10395 }
10396 
10397 // C99 6.5.8, C++ [expr.rel]
10398 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10399                                     SourceLocation Loc,
10400                                     BinaryOperatorKind Opc) {
10401   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10402   bool IsThreeWay = Opc == BO_Cmp;
10403   auto IsAnyPointerType = [](ExprResult E) {
10404     QualType Ty = E.get()->getType();
10405     return Ty->isPointerType() || Ty->isMemberPointerType();
10406   };
10407 
10408   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10409   // type, array-to-pointer, ..., conversions are performed on both operands to
10410   // bring them to their composite type.
10411   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10412   // any type-related checks.
10413   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10414     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10415     if (LHS.isInvalid())
10416       return QualType();
10417     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10418     if (RHS.isInvalid())
10419       return QualType();
10420   } else {
10421     LHS = DefaultLvalueConversion(LHS.get());
10422     if (LHS.isInvalid())
10423       return QualType();
10424     RHS = DefaultLvalueConversion(RHS.get());
10425     if (RHS.isInvalid())
10426       return QualType();
10427   }
10428 
10429   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10430 
10431   // Handle vector comparisons separately.
10432   if (LHS.get()->getType()->isVectorType() ||
10433       RHS.get()->getType()->isVectorType())
10434     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10435 
10436   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10437   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10438 
10439   QualType LHSType = LHS.get()->getType();
10440   QualType RHSType = RHS.get()->getType();
10441   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10442       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10443     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10444 
10445   const Expr::NullPointerConstantKind LHSNullKind =
10446       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10447   const Expr::NullPointerConstantKind RHSNullKind =
10448       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10449   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10450   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10451 
10452   auto computeResultTy = [&]() {
10453     if (Opc != BO_Cmp)
10454       return Context.getLogicalOperationType();
10455     assert(getLangOpts().CPlusPlus);
10456     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10457 
10458     QualType CompositeTy = LHS.get()->getType();
10459     assert(!CompositeTy->isReferenceType());
10460 
10461     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10462       return CheckComparisonCategoryType(Kind, Loc);
10463     };
10464 
10465     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10466     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10467     // result is of type std::strong_equality
10468     if (CompositeTy->isFunctionPointerType() ||
10469         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10470       // FIXME: consider making the function pointer case produce
10471       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10472       // and direction polls
10473       return buildResultTy(ComparisonCategoryType::StrongEquality);
10474 
10475     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10476     // pointer type, p <=> q is of type std::strong_ordering.
10477     if (CompositeTy->isPointerType()) {
10478       // P0946R0: Comparisons between a null pointer constant and an object
10479       // pointer result in std::strong_equality
10480       if (LHSIsNull != RHSIsNull)
10481         return buildResultTy(ComparisonCategoryType::StrongEquality);
10482       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10483     }
10484     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10485     // TODO: Extend support for operator<=> to ObjC types.
10486     return InvalidOperands(Loc, LHS, RHS);
10487   };
10488 
10489 
10490   if (!IsRelational && LHSIsNull != RHSIsNull) {
10491     bool IsEquality = Opc == BO_EQ;
10492     if (RHSIsNull)
10493       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10494                                    RHS.get()->getSourceRange());
10495     else
10496       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10497                                    LHS.get()->getSourceRange());
10498   }
10499 
10500   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10501       (RHSType->isIntegerType() && !RHSIsNull)) {
10502     // Skip normal pointer conversion checks in this case; we have better
10503     // diagnostics for this below.
10504   } else if (getLangOpts().CPlusPlus) {
10505     // Equality comparison of a function pointer to a void pointer is invalid,
10506     // but we allow it as an extension.
10507     // FIXME: If we really want to allow this, should it be part of composite
10508     // pointer type computation so it works in conditionals too?
10509     if (!IsRelational &&
10510         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10511          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10512       // This is a gcc extension compatibility comparison.
10513       // In a SFINAE context, we treat this as a hard error to maintain
10514       // conformance with the C++ standard.
10515       diagnoseFunctionPointerToVoidComparison(
10516           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10517 
10518       if (isSFINAEContext())
10519         return QualType();
10520 
10521       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10522       return computeResultTy();
10523     }
10524 
10525     // C++ [expr.eq]p2:
10526     //   If at least one operand is a pointer [...] bring them to their
10527     //   composite pointer type.
10528     // C++ [expr.spaceship]p6
10529     //  If at least one of the operands is of pointer type, [...] bring them
10530     //  to their composite pointer type.
10531     // C++ [expr.rel]p2:
10532     //   If both operands are pointers, [...] bring them to their composite
10533     //   pointer type.
10534     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10535             (IsRelational ? 2 : 1) &&
10536         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10537                                          RHSType->isObjCObjectPointerType()))) {
10538       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10539         return QualType();
10540       return computeResultTy();
10541     }
10542   } else if (LHSType->isPointerType() &&
10543              RHSType->isPointerType()) { // C99 6.5.8p2
10544     // All of the following pointer-related warnings are GCC extensions, except
10545     // when handling null pointer constants.
10546     QualType LCanPointeeTy =
10547       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10548     QualType RCanPointeeTy =
10549       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10550 
10551     // C99 6.5.9p2 and C99 6.5.8p2
10552     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10553                                    RCanPointeeTy.getUnqualifiedType())) {
10554       // Valid unless a relational comparison of function pointers
10555       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10556         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10557           << LHSType << RHSType << LHS.get()->getSourceRange()
10558           << RHS.get()->getSourceRange();
10559       }
10560     } else if (!IsRelational &&
10561                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10562       // Valid unless comparison between non-null pointer and function pointer
10563       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10564           && !LHSIsNull && !RHSIsNull)
10565         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10566                                                 /*isError*/false);
10567     } else {
10568       // Invalid
10569       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10570     }
10571     if (LCanPointeeTy != RCanPointeeTy) {
10572       // Treat NULL constant as a special case in OpenCL.
10573       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10574         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10575         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10576           Diag(Loc,
10577                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10578               << LHSType << RHSType << 0 /* comparison */
10579               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10580         }
10581       }
10582       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10583       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10584       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10585                                                : CK_BitCast;
10586       if (LHSIsNull && !RHSIsNull)
10587         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10588       else
10589         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10590     }
10591     return computeResultTy();
10592   }
10593 
10594   if (getLangOpts().CPlusPlus) {
10595     // C++ [expr.eq]p4:
10596     //   Two operands of type std::nullptr_t or one operand of type
10597     //   std::nullptr_t and the other a null pointer constant compare equal.
10598     if (!IsRelational && LHSIsNull && RHSIsNull) {
10599       if (LHSType->isNullPtrType()) {
10600         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10601         return computeResultTy();
10602       }
10603       if (RHSType->isNullPtrType()) {
10604         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10605         return computeResultTy();
10606       }
10607     }
10608 
10609     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10610     // These aren't covered by the composite pointer type rules.
10611     if (!IsRelational && RHSType->isNullPtrType() &&
10612         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10613       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10614       return computeResultTy();
10615     }
10616     if (!IsRelational && LHSType->isNullPtrType() &&
10617         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10618       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10619       return computeResultTy();
10620     }
10621 
10622     if (IsRelational &&
10623         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10624          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10625       // HACK: Relational comparison of nullptr_t against a pointer type is
10626       // invalid per DR583, but we allow it within std::less<> and friends,
10627       // since otherwise common uses of it break.
10628       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10629       // friends to have std::nullptr_t overload candidates.
10630       DeclContext *DC = CurContext;
10631       if (isa<FunctionDecl>(DC))
10632         DC = DC->getParent();
10633       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10634         if (CTSD->isInStdNamespace() &&
10635             llvm::StringSwitch<bool>(CTSD->getName())
10636                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10637                 .Default(false)) {
10638           if (RHSType->isNullPtrType())
10639             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10640           else
10641             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10642           return computeResultTy();
10643         }
10644       }
10645     }
10646 
10647     // C++ [expr.eq]p2:
10648     //   If at least one operand is a pointer to member, [...] bring them to
10649     //   their composite pointer type.
10650     if (!IsRelational &&
10651         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10652       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10653         return QualType();
10654       else
10655         return computeResultTy();
10656     }
10657   }
10658 
10659   // Handle block pointer types.
10660   if (!IsRelational && LHSType->isBlockPointerType() &&
10661       RHSType->isBlockPointerType()) {
10662     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10663     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10664 
10665     if (!LHSIsNull && !RHSIsNull &&
10666         !Context.typesAreCompatible(lpointee, rpointee)) {
10667       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10668         << LHSType << RHSType << LHS.get()->getSourceRange()
10669         << RHS.get()->getSourceRange();
10670     }
10671     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10672     return computeResultTy();
10673   }
10674 
10675   // Allow block pointers to be compared with null pointer constants.
10676   if (!IsRelational
10677       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10678           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10679     if (!LHSIsNull && !RHSIsNull) {
10680       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10681              ->getPointeeType()->isVoidType())
10682             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10683                 ->getPointeeType()->isVoidType())))
10684         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10685           << LHSType << RHSType << LHS.get()->getSourceRange()
10686           << RHS.get()->getSourceRange();
10687     }
10688     if (LHSIsNull && !RHSIsNull)
10689       LHS = ImpCastExprToType(LHS.get(), RHSType,
10690                               RHSType->isPointerType() ? CK_BitCast
10691                                 : CK_AnyPointerToBlockPointerCast);
10692     else
10693       RHS = ImpCastExprToType(RHS.get(), LHSType,
10694                               LHSType->isPointerType() ? CK_BitCast
10695                                 : CK_AnyPointerToBlockPointerCast);
10696     return computeResultTy();
10697   }
10698 
10699   if (LHSType->isObjCObjectPointerType() ||
10700       RHSType->isObjCObjectPointerType()) {
10701     const PointerType *LPT = LHSType->getAs<PointerType>();
10702     const PointerType *RPT = RHSType->getAs<PointerType>();
10703     if (LPT || RPT) {
10704       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10705       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10706 
10707       if (!LPtrToVoid && !RPtrToVoid &&
10708           !Context.typesAreCompatible(LHSType, RHSType)) {
10709         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10710                                           /*isError*/false);
10711       }
10712       if (LHSIsNull && !RHSIsNull) {
10713         Expr *E = LHS.get();
10714         if (getLangOpts().ObjCAutoRefCount)
10715           CheckObjCConversion(SourceRange(), RHSType, E,
10716                               CCK_ImplicitConversion);
10717         LHS = ImpCastExprToType(E, RHSType,
10718                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10719       }
10720       else {
10721         Expr *E = RHS.get();
10722         if (getLangOpts().ObjCAutoRefCount)
10723           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10724                               /*Diagnose=*/true,
10725                               /*DiagnoseCFAudited=*/false, Opc);
10726         RHS = ImpCastExprToType(E, LHSType,
10727                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10728       }
10729       return computeResultTy();
10730     }
10731     if (LHSType->isObjCObjectPointerType() &&
10732         RHSType->isObjCObjectPointerType()) {
10733       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10734         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10735                                           /*isError*/false);
10736       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10737         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10738 
10739       if (LHSIsNull && !RHSIsNull)
10740         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10741       else
10742         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10743       return computeResultTy();
10744     }
10745 
10746     if (!IsRelational && LHSType->isBlockPointerType() &&
10747         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10748       LHS = ImpCastExprToType(LHS.get(), RHSType,
10749                               CK_BlockPointerToObjCPointerCast);
10750       return computeResultTy();
10751     } else if (!IsRelational &&
10752                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10753                RHSType->isBlockPointerType()) {
10754       RHS = ImpCastExprToType(RHS.get(), LHSType,
10755                               CK_BlockPointerToObjCPointerCast);
10756       return computeResultTy();
10757     }
10758   }
10759   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10760       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10761     unsigned DiagID = 0;
10762     bool isError = false;
10763     if (LangOpts.DebuggerSupport) {
10764       // Under a debugger, allow the comparison of pointers to integers,
10765       // since users tend to want to compare addresses.
10766     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10767                (RHSIsNull && RHSType->isIntegerType())) {
10768       if (IsRelational) {
10769         isError = getLangOpts().CPlusPlus;
10770         DiagID =
10771           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10772                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10773       }
10774     } else if (getLangOpts().CPlusPlus) {
10775       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10776       isError = true;
10777     } else if (IsRelational)
10778       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10779     else
10780       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10781 
10782     if (DiagID) {
10783       Diag(Loc, DiagID)
10784         << LHSType << RHSType << LHS.get()->getSourceRange()
10785         << RHS.get()->getSourceRange();
10786       if (isError)
10787         return QualType();
10788     }
10789 
10790     if (LHSType->isIntegerType())
10791       LHS = ImpCastExprToType(LHS.get(), RHSType,
10792                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10793     else
10794       RHS = ImpCastExprToType(RHS.get(), LHSType,
10795                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10796     return computeResultTy();
10797   }
10798 
10799   // Handle block pointers.
10800   if (!IsRelational && RHSIsNull
10801       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10802     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10803     return computeResultTy();
10804   }
10805   if (!IsRelational && LHSIsNull
10806       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10807     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10808     return computeResultTy();
10809   }
10810 
10811   if (getLangOpts().OpenCLVersion >= 200) {
10812     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10813       return computeResultTy();
10814     }
10815 
10816     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10817       return computeResultTy();
10818     }
10819 
10820     if (LHSIsNull && RHSType->isQueueT()) {
10821       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10822       return computeResultTy();
10823     }
10824 
10825     if (LHSType->isQueueT() && RHSIsNull) {
10826       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10827       return computeResultTy();
10828     }
10829   }
10830 
10831   return InvalidOperands(Loc, LHS, RHS);
10832 }
10833 
10834 // Return a signed ext_vector_type that is of identical size and number of
10835 // elements. For floating point vectors, return an integer type of identical
10836 // size and number of elements. In the non ext_vector_type case, search from
10837 // the largest type to the smallest type to avoid cases where long long == long,
10838 // where long gets picked over long long.
10839 QualType Sema::GetSignedVectorType(QualType V) {
10840   const VectorType *VTy = V->getAs<VectorType>();
10841   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10842 
10843   if (isa<ExtVectorType>(VTy)) {
10844     if (TypeSize == Context.getTypeSize(Context.CharTy))
10845       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10846     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10847       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10848     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10849       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10850     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10851       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10852     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10853            "Unhandled vector element size in vector compare");
10854     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10855   }
10856 
10857   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10858     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10859                                  VectorType::GenericVector);
10860   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10861     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10862                                  VectorType::GenericVector);
10863   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10864     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10865                                  VectorType::GenericVector);
10866   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10867     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10868                                  VectorType::GenericVector);
10869   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10870          "Unhandled vector element size in vector compare");
10871   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10872                                VectorType::GenericVector);
10873 }
10874 
10875 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10876 /// operates on extended vector types.  Instead of producing an IntTy result,
10877 /// like a scalar comparison, a vector comparison produces a vector of integer
10878 /// types.
10879 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10880                                           SourceLocation Loc,
10881                                           BinaryOperatorKind Opc) {
10882   // Check to make sure we're operating on vectors of the same type and width,
10883   // Allowing one side to be a scalar of element type.
10884   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10885                               /*AllowBothBool*/true,
10886                               /*AllowBoolConversions*/getLangOpts().ZVector);
10887   if (vType.isNull())
10888     return vType;
10889 
10890   QualType LHSType = LHS.get()->getType();
10891 
10892   // If AltiVec, the comparison results in a numeric type, i.e.
10893   // bool for C++, int for C
10894   if (getLangOpts().AltiVec &&
10895       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10896     return Context.getLogicalOperationType();
10897 
10898   // For non-floating point types, check for self-comparisons of the form
10899   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10900   // often indicate logic errors in the program.
10901   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10902 
10903   // Check for comparisons of floating point operands using != and ==.
10904   if (BinaryOperator::isEqualityOp(Opc) &&
10905       LHSType->hasFloatingRepresentation()) {
10906     assert(RHS.get()->getType()->hasFloatingRepresentation());
10907     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10908   }
10909 
10910   // Return a signed type for the vector.
10911   return GetSignedVectorType(vType);
10912 }
10913 
10914 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10915                                           SourceLocation Loc) {
10916   // Ensure that either both operands are of the same vector type, or
10917   // one operand is of a vector type and the other is of its element type.
10918   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10919                                        /*AllowBothBool*/true,
10920                                        /*AllowBoolConversions*/false);
10921   if (vType.isNull())
10922     return InvalidOperands(Loc, LHS, RHS);
10923   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10924       vType->hasFloatingRepresentation())
10925     return InvalidOperands(Loc, LHS, RHS);
10926   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10927   //        usage of the logical operators && and || with vectors in C. This
10928   //        check could be notionally dropped.
10929   if (!getLangOpts().CPlusPlus &&
10930       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10931     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10932 
10933   return GetSignedVectorType(LHS.get()->getType());
10934 }
10935 
10936 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10937                                            SourceLocation Loc,
10938                                            BinaryOperatorKind Opc) {
10939   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10940 
10941   bool IsCompAssign =
10942       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10943 
10944   if (LHS.get()->getType()->isVectorType() ||
10945       RHS.get()->getType()->isVectorType()) {
10946     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10947         RHS.get()->getType()->hasIntegerRepresentation())
10948       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10949                         /*AllowBothBool*/true,
10950                         /*AllowBoolConversions*/getLangOpts().ZVector);
10951     return InvalidOperands(Loc, LHS, RHS);
10952   }
10953 
10954   if (Opc == BO_And)
10955     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10956 
10957   ExprResult LHSResult = LHS, RHSResult = RHS;
10958   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10959                                                  IsCompAssign);
10960   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10961     return QualType();
10962   LHS = LHSResult.get();
10963   RHS = RHSResult.get();
10964 
10965   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10966     return compType;
10967   return InvalidOperands(Loc, LHS, RHS);
10968 }
10969 
10970 // C99 6.5.[13,14]
10971 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10972                                            SourceLocation Loc,
10973                                            BinaryOperatorKind Opc) {
10974   // Check vector operands differently.
10975   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10976     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10977 
10978   // Diagnose cases where the user write a logical and/or but probably meant a
10979   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10980   // is a constant.
10981   if (LHS.get()->getType()->isIntegerType() &&
10982       !LHS.get()->getType()->isBooleanType() &&
10983       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10984       // Don't warn in macros or template instantiations.
10985       !Loc.isMacroID() && !inTemplateInstantiation()) {
10986     // If the RHS can be constant folded, and if it constant folds to something
10987     // that isn't 0 or 1 (which indicate a potential logical operation that
10988     // happened to fold to true/false) then warn.
10989     // Parens on the RHS are ignored.
10990     Expr::EvalResult EVResult;
10991     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10992       llvm::APSInt Result = EVResult.Val.getInt();
10993       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10994            !RHS.get()->getExprLoc().isMacroID()) ||
10995           (Result != 0 && Result != 1)) {
10996         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10997           << RHS.get()->getSourceRange()
10998           << (Opc == BO_LAnd ? "&&" : "||");
10999         // Suggest replacing the logical operator with the bitwise version
11000         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11001             << (Opc == BO_LAnd ? "&" : "|")
11002             << FixItHint::CreateReplacement(SourceRange(
11003                                                  Loc, getLocForEndOfToken(Loc)),
11004                                             Opc == BO_LAnd ? "&" : "|");
11005         if (Opc == BO_LAnd)
11006           // Suggest replacing "Foo() && kNonZero" with "Foo()"
11007           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11008               << FixItHint::CreateRemoval(
11009                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11010                                  RHS.get()->getEndLoc()));
11011       }
11012     }
11013   }
11014 
11015   if (!Context.getLangOpts().CPlusPlus) {
11016     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11017     // not operate on the built-in scalar and vector float types.
11018     if (Context.getLangOpts().OpenCL &&
11019         Context.getLangOpts().OpenCLVersion < 120) {
11020       if (LHS.get()->getType()->isFloatingType() ||
11021           RHS.get()->getType()->isFloatingType())
11022         return InvalidOperands(Loc, LHS, RHS);
11023     }
11024 
11025     LHS = UsualUnaryConversions(LHS.get());
11026     if (LHS.isInvalid())
11027       return QualType();
11028 
11029     RHS = UsualUnaryConversions(RHS.get());
11030     if (RHS.isInvalid())
11031       return QualType();
11032 
11033     if (!LHS.get()->getType()->isScalarType() ||
11034         !RHS.get()->getType()->isScalarType())
11035       return InvalidOperands(Loc, LHS, RHS);
11036 
11037     return Context.IntTy;
11038   }
11039 
11040   // The following is safe because we only use this method for
11041   // non-overloadable operands.
11042 
11043   // C++ [expr.log.and]p1
11044   // C++ [expr.log.or]p1
11045   // The operands are both contextually converted to type bool.
11046   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11047   if (LHSRes.isInvalid())
11048     return InvalidOperands(Loc, LHS, RHS);
11049   LHS = LHSRes;
11050 
11051   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11052   if (RHSRes.isInvalid())
11053     return InvalidOperands(Loc, LHS, RHS);
11054   RHS = RHSRes;
11055 
11056   // C++ [expr.log.and]p2
11057   // C++ [expr.log.or]p2
11058   // The result is a bool.
11059   return Context.BoolTy;
11060 }
11061 
11062 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11063   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11064   if (!ME) return false;
11065   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11066   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11067       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11068   if (!Base) return false;
11069   return Base->getMethodDecl() != nullptr;
11070 }
11071 
11072 /// Is the given expression (which must be 'const') a reference to a
11073 /// variable which was originally non-const, but which has become
11074 /// 'const' due to being captured within a block?
11075 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11076 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11077   assert(E->isLValue() && E->getType().isConstQualified());
11078   E = E->IgnoreParens();
11079 
11080   // Must be a reference to a declaration from an enclosing scope.
11081   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11082   if (!DRE) return NCCK_None;
11083   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11084 
11085   // The declaration must be a variable which is not declared 'const'.
11086   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11087   if (!var) return NCCK_None;
11088   if (var->getType().isConstQualified()) return NCCK_None;
11089   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11090 
11091   // Decide whether the first capture was for a block or a lambda.
11092   DeclContext *DC = S.CurContext, *Prev = nullptr;
11093   // Decide whether the first capture was for a block or a lambda.
11094   while (DC) {
11095     // For init-capture, it is possible that the variable belongs to the
11096     // template pattern of the current context.
11097     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11098       if (var->isInitCapture() &&
11099           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11100         break;
11101     if (DC == var->getDeclContext())
11102       break;
11103     Prev = DC;
11104     DC = DC->getParent();
11105   }
11106   // Unless we have an init-capture, we've gone one step too far.
11107   if (!var->isInitCapture())
11108     DC = Prev;
11109   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11110 }
11111 
11112 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11113   Ty = Ty.getNonReferenceType();
11114   if (IsDereference && Ty->isPointerType())
11115     Ty = Ty->getPointeeType();
11116   return !Ty.isConstQualified();
11117 }
11118 
11119 // Update err_typecheck_assign_const and note_typecheck_assign_const
11120 // when this enum is changed.
11121 enum {
11122   ConstFunction,
11123   ConstVariable,
11124   ConstMember,
11125   ConstMethod,
11126   NestedConstMember,
11127   ConstUnknown,  // Keep as last element
11128 };
11129 
11130 /// Emit the "read-only variable not assignable" error and print notes to give
11131 /// more information about why the variable is not assignable, such as pointing
11132 /// to the declaration of a const variable, showing that a method is const, or
11133 /// that the function is returning a const reference.
11134 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11135                                     SourceLocation Loc) {
11136   SourceRange ExprRange = E->getSourceRange();
11137 
11138   // Only emit one error on the first const found.  All other consts will emit
11139   // a note to the error.
11140   bool DiagnosticEmitted = false;
11141 
11142   // Track if the current expression is the result of a dereference, and if the
11143   // next checked expression is the result of a dereference.
11144   bool IsDereference = false;
11145   bool NextIsDereference = false;
11146 
11147   // Loop to process MemberExpr chains.
11148   while (true) {
11149     IsDereference = NextIsDereference;
11150 
11151     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11152     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11153       NextIsDereference = ME->isArrow();
11154       const ValueDecl *VD = ME->getMemberDecl();
11155       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11156         // Mutable fields can be modified even if the class is const.
11157         if (Field->isMutable()) {
11158           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11159           break;
11160         }
11161 
11162         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11163           if (!DiagnosticEmitted) {
11164             S.Diag(Loc, diag::err_typecheck_assign_const)
11165                 << ExprRange << ConstMember << false /*static*/ << Field
11166                 << Field->getType();
11167             DiagnosticEmitted = true;
11168           }
11169           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11170               << ConstMember << false /*static*/ << Field << Field->getType()
11171               << Field->getSourceRange();
11172         }
11173         E = ME->getBase();
11174         continue;
11175       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11176         if (VDecl->getType().isConstQualified()) {
11177           if (!DiagnosticEmitted) {
11178             S.Diag(Loc, diag::err_typecheck_assign_const)
11179                 << ExprRange << ConstMember << true /*static*/ << VDecl
11180                 << VDecl->getType();
11181             DiagnosticEmitted = true;
11182           }
11183           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11184               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11185               << VDecl->getSourceRange();
11186         }
11187         // Static fields do not inherit constness from parents.
11188         break;
11189       }
11190       break; // End MemberExpr
11191     } else if (const ArraySubscriptExpr *ASE =
11192                    dyn_cast<ArraySubscriptExpr>(E)) {
11193       E = ASE->getBase()->IgnoreParenImpCasts();
11194       continue;
11195     } else if (const ExtVectorElementExpr *EVE =
11196                    dyn_cast<ExtVectorElementExpr>(E)) {
11197       E = EVE->getBase()->IgnoreParenImpCasts();
11198       continue;
11199     }
11200     break;
11201   }
11202 
11203   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11204     // Function calls
11205     const FunctionDecl *FD = CE->getDirectCallee();
11206     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11207       if (!DiagnosticEmitted) {
11208         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11209                                                       << ConstFunction << FD;
11210         DiagnosticEmitted = true;
11211       }
11212       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11213              diag::note_typecheck_assign_const)
11214           << ConstFunction << FD << FD->getReturnType()
11215           << FD->getReturnTypeSourceRange();
11216     }
11217   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11218     // Point to variable declaration.
11219     if (const ValueDecl *VD = DRE->getDecl()) {
11220       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11221         if (!DiagnosticEmitted) {
11222           S.Diag(Loc, diag::err_typecheck_assign_const)
11223               << ExprRange << ConstVariable << VD << VD->getType();
11224           DiagnosticEmitted = true;
11225         }
11226         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11227             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11228       }
11229     }
11230   } else if (isa<CXXThisExpr>(E)) {
11231     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11232       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11233         if (MD->isConst()) {
11234           if (!DiagnosticEmitted) {
11235             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11236                                                           << ConstMethod << MD;
11237             DiagnosticEmitted = true;
11238           }
11239           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11240               << ConstMethod << MD << MD->getSourceRange();
11241         }
11242       }
11243     }
11244   }
11245 
11246   if (DiagnosticEmitted)
11247     return;
11248 
11249   // Can't determine a more specific message, so display the generic error.
11250   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11251 }
11252 
11253 enum OriginalExprKind {
11254   OEK_Variable,
11255   OEK_Member,
11256   OEK_LValue
11257 };
11258 
11259 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11260                                          const RecordType *Ty,
11261                                          SourceLocation Loc, SourceRange Range,
11262                                          OriginalExprKind OEK,
11263                                          bool &DiagnosticEmitted) {
11264   std::vector<const RecordType *> RecordTypeList;
11265   RecordTypeList.push_back(Ty);
11266   unsigned NextToCheckIndex = 0;
11267   // We walk the record hierarchy breadth-first to ensure that we print
11268   // diagnostics in field nesting order.
11269   while (RecordTypeList.size() > NextToCheckIndex) {
11270     bool IsNested = NextToCheckIndex > 0;
11271     for (const FieldDecl *Field :
11272          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11273       // First, check every field for constness.
11274       QualType FieldTy = Field->getType();
11275       if (FieldTy.isConstQualified()) {
11276         if (!DiagnosticEmitted) {
11277           S.Diag(Loc, diag::err_typecheck_assign_const)
11278               << Range << NestedConstMember << OEK << VD
11279               << IsNested << Field;
11280           DiagnosticEmitted = true;
11281         }
11282         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11283             << NestedConstMember << IsNested << Field
11284             << FieldTy << Field->getSourceRange();
11285       }
11286 
11287       // Then we append it to the list to check next in order.
11288       FieldTy = FieldTy.getCanonicalType();
11289       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11290         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11291           RecordTypeList.push_back(FieldRecTy);
11292       }
11293     }
11294     ++NextToCheckIndex;
11295   }
11296 }
11297 
11298 /// Emit an error for the case where a record we are trying to assign to has a
11299 /// const-qualified field somewhere in its hierarchy.
11300 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11301                                          SourceLocation Loc) {
11302   QualType Ty = E->getType();
11303   assert(Ty->isRecordType() && "lvalue was not record?");
11304   SourceRange Range = E->getSourceRange();
11305   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11306   bool DiagEmitted = false;
11307 
11308   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11309     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11310             Range, OEK_Member, DiagEmitted);
11311   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11312     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11313             Range, OEK_Variable, DiagEmitted);
11314   else
11315     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11316             Range, OEK_LValue, DiagEmitted);
11317   if (!DiagEmitted)
11318     DiagnoseConstAssignment(S, E, Loc);
11319 }
11320 
11321 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11322 /// emit an error and return true.  If so, return false.
11323 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11324   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11325 
11326   S.CheckShadowingDeclModification(E, Loc);
11327 
11328   SourceLocation OrigLoc = Loc;
11329   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11330                                                               &Loc);
11331   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11332     IsLV = Expr::MLV_InvalidMessageExpression;
11333   if (IsLV == Expr::MLV_Valid)
11334     return false;
11335 
11336   unsigned DiagID = 0;
11337   bool NeedType = false;
11338   switch (IsLV) { // C99 6.5.16p2
11339   case Expr::MLV_ConstQualified:
11340     // Use a specialized diagnostic when we're assigning to an object
11341     // from an enclosing function or block.
11342     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11343       if (NCCK == NCCK_Block)
11344         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11345       else
11346         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11347       break;
11348     }
11349 
11350     // In ARC, use some specialized diagnostics for occasions where we
11351     // infer 'const'.  These are always pseudo-strong variables.
11352     if (S.getLangOpts().ObjCAutoRefCount) {
11353       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11354       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11355         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11356 
11357         // Use the normal diagnostic if it's pseudo-__strong but the
11358         // user actually wrote 'const'.
11359         if (var->isARCPseudoStrong() &&
11360             (!var->getTypeSourceInfo() ||
11361              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11362           // There are three pseudo-strong cases:
11363           //  - self
11364           ObjCMethodDecl *method = S.getCurMethodDecl();
11365           if (method && var == method->getSelfDecl()) {
11366             DiagID = method->isClassMethod()
11367               ? diag::err_typecheck_arc_assign_self_class_method
11368               : diag::err_typecheck_arc_assign_self;
11369 
11370           //  - Objective-C externally_retained attribute.
11371           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11372                      isa<ParmVarDecl>(var)) {
11373             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11374 
11375           //  - fast enumeration variables
11376           } else {
11377             DiagID = diag::err_typecheck_arr_assign_enumeration;
11378           }
11379 
11380           SourceRange Assign;
11381           if (Loc != OrigLoc)
11382             Assign = SourceRange(OrigLoc, OrigLoc);
11383           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11384           // We need to preserve the AST regardless, so migration tool
11385           // can do its job.
11386           return false;
11387         }
11388       }
11389     }
11390 
11391     // If none of the special cases above are triggered, then this is a
11392     // simple const assignment.
11393     if (DiagID == 0) {
11394       DiagnoseConstAssignment(S, E, Loc);
11395       return true;
11396     }
11397 
11398     break;
11399   case Expr::MLV_ConstAddrSpace:
11400     DiagnoseConstAssignment(S, E, Loc);
11401     return true;
11402   case Expr::MLV_ConstQualifiedField:
11403     DiagnoseRecursiveConstFields(S, E, Loc);
11404     return true;
11405   case Expr::MLV_ArrayType:
11406   case Expr::MLV_ArrayTemporary:
11407     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11408     NeedType = true;
11409     break;
11410   case Expr::MLV_NotObjectType:
11411     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11412     NeedType = true;
11413     break;
11414   case Expr::MLV_LValueCast:
11415     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11416     break;
11417   case Expr::MLV_Valid:
11418     llvm_unreachable("did not take early return for MLV_Valid");
11419   case Expr::MLV_InvalidExpression:
11420   case Expr::MLV_MemberFunction:
11421   case Expr::MLV_ClassTemporary:
11422     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11423     break;
11424   case Expr::MLV_IncompleteType:
11425   case Expr::MLV_IncompleteVoidType:
11426     return S.RequireCompleteType(Loc, E->getType(),
11427              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11428   case Expr::MLV_DuplicateVectorComponents:
11429     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11430     break;
11431   case Expr::MLV_NoSetterProperty:
11432     llvm_unreachable("readonly properties should be processed differently");
11433   case Expr::MLV_InvalidMessageExpression:
11434     DiagID = diag::err_readonly_message_assignment;
11435     break;
11436   case Expr::MLV_SubObjCPropertySetting:
11437     DiagID = diag::err_no_subobject_property_setting;
11438     break;
11439   }
11440 
11441   SourceRange Assign;
11442   if (Loc != OrigLoc)
11443     Assign = SourceRange(OrigLoc, OrigLoc);
11444   if (NeedType)
11445     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11446   else
11447     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11448   return true;
11449 }
11450 
11451 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11452                                          SourceLocation Loc,
11453                                          Sema &Sema) {
11454   if (Sema.inTemplateInstantiation())
11455     return;
11456   if (Sema.isUnevaluatedContext())
11457     return;
11458   if (Loc.isInvalid() || Loc.isMacroID())
11459     return;
11460   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11461     return;
11462 
11463   // C / C++ fields
11464   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11465   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11466   if (ML && MR) {
11467     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11468       return;
11469     const ValueDecl *LHSDecl =
11470         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11471     const ValueDecl *RHSDecl =
11472         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11473     if (LHSDecl != RHSDecl)
11474       return;
11475     if (LHSDecl->getType().isVolatileQualified())
11476       return;
11477     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11478       if (RefTy->getPointeeType().isVolatileQualified())
11479         return;
11480 
11481     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11482   }
11483 
11484   // Objective-C instance variables
11485   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11486   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11487   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11488     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11489     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11490     if (RL && RR && RL->getDecl() == RR->getDecl())
11491       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11492   }
11493 }
11494 
11495 // C99 6.5.16.1
11496 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11497                                        SourceLocation Loc,
11498                                        QualType CompoundType) {
11499   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11500 
11501   // Verify that LHS is a modifiable lvalue, and emit error if not.
11502   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11503     return QualType();
11504 
11505   QualType LHSType = LHSExpr->getType();
11506   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11507                                              CompoundType;
11508   // OpenCL v1.2 s6.1.1.1 p2:
11509   // The half data type can only be used to declare a pointer to a buffer that
11510   // contains half values
11511   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11512     LHSType->isHalfType()) {
11513     Diag(Loc, diag::err_opencl_half_load_store) << 1
11514         << LHSType.getUnqualifiedType();
11515     return QualType();
11516   }
11517 
11518   AssignConvertType ConvTy;
11519   if (CompoundType.isNull()) {
11520     Expr *RHSCheck = RHS.get();
11521 
11522     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11523 
11524     QualType LHSTy(LHSType);
11525     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11526     if (RHS.isInvalid())
11527       return QualType();
11528     // Special case of NSObject attributes on c-style pointer types.
11529     if (ConvTy == IncompatiblePointer &&
11530         ((Context.isObjCNSObjectType(LHSType) &&
11531           RHSType->isObjCObjectPointerType()) ||
11532          (Context.isObjCNSObjectType(RHSType) &&
11533           LHSType->isObjCObjectPointerType())))
11534       ConvTy = Compatible;
11535 
11536     if (ConvTy == Compatible &&
11537         LHSType->isObjCObjectType())
11538         Diag(Loc, diag::err_objc_object_assignment)
11539           << LHSType;
11540 
11541     // If the RHS is a unary plus or minus, check to see if they = and + are
11542     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11543     // instead of "x += 4".
11544     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11545       RHSCheck = ICE->getSubExpr();
11546     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11547       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11548           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11549           // Only if the two operators are exactly adjacent.
11550           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11551           // And there is a space or other character before the subexpr of the
11552           // unary +/-.  We don't want to warn on "x=-1".
11553           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11554           UO->getSubExpr()->getBeginLoc().isFileID()) {
11555         Diag(Loc, diag::warn_not_compound_assign)
11556           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11557           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11558       }
11559     }
11560 
11561     if (ConvTy == Compatible) {
11562       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11563         // Warn about retain cycles where a block captures the LHS, but
11564         // not if the LHS is a simple variable into which the block is
11565         // being stored...unless that variable can be captured by reference!
11566         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11567         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11568         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11569           checkRetainCycles(LHSExpr, RHS.get());
11570       }
11571 
11572       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11573           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11574         // It is safe to assign a weak reference into a strong variable.
11575         // Although this code can still have problems:
11576         //   id x = self.weakProp;
11577         //   id y = self.weakProp;
11578         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11579         // paths through the function. This should be revisited if
11580         // -Wrepeated-use-of-weak is made flow-sensitive.
11581         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11582         // variable, which will be valid for the current autorelease scope.
11583         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11584                              RHS.get()->getBeginLoc()))
11585           getCurFunction()->markSafeWeakUse(RHS.get());
11586 
11587       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11588         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11589       }
11590     }
11591   } else {
11592     // Compound assignment "x += y"
11593     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11594   }
11595 
11596   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11597                                RHS.get(), AA_Assigning))
11598     return QualType();
11599 
11600   CheckForNullPointerDereference(*this, LHSExpr);
11601 
11602   // C99 6.5.16p3: The type of an assignment expression is the type of the
11603   // left operand unless the left operand has qualified type, in which case
11604   // it is the unqualified version of the type of the left operand.
11605   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11606   // is converted to the type of the assignment expression (above).
11607   // C++ 5.17p1: the type of the assignment expression is that of its left
11608   // operand.
11609   return (getLangOpts().CPlusPlus
11610           ? LHSType : LHSType.getUnqualifiedType());
11611 }
11612 
11613 // Only ignore explicit casts to void.
11614 static bool IgnoreCommaOperand(const Expr *E) {
11615   E = E->IgnoreParens();
11616 
11617   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11618     if (CE->getCastKind() == CK_ToVoid) {
11619       return true;
11620     }
11621 
11622     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11623     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11624         CE->getSubExpr()->getType()->isDependentType()) {
11625       return true;
11626     }
11627   }
11628 
11629   return false;
11630 }
11631 
11632 // Look for instances where it is likely the comma operator is confused with
11633 // another operator.  There is a whitelist of acceptable expressions for the
11634 // left hand side of the comma operator, otherwise emit a warning.
11635 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11636   // No warnings in macros
11637   if (Loc.isMacroID())
11638     return;
11639 
11640   // Don't warn in template instantiations.
11641   if (inTemplateInstantiation())
11642     return;
11643 
11644   // Scope isn't fine-grained enough to whitelist the specific cases, so
11645   // instead, skip more than needed, then call back into here with the
11646   // CommaVisitor in SemaStmt.cpp.
11647   // The whitelisted locations are the initialization and increment portions
11648   // of a for loop.  The additional checks are on the condition of
11649   // if statements, do/while loops, and for loops.
11650   // Differences in scope flags for C89 mode requires the extra logic.
11651   const unsigned ForIncrementFlags =
11652       getLangOpts().C99 || getLangOpts().CPlusPlus
11653           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11654           : Scope::ContinueScope | Scope::BreakScope;
11655   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11656   const unsigned ScopeFlags = getCurScope()->getFlags();
11657   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11658       (ScopeFlags & ForInitFlags) == ForInitFlags)
11659     return;
11660 
11661   // If there are multiple comma operators used together, get the RHS of the
11662   // of the comma operator as the LHS.
11663   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11664     if (BO->getOpcode() != BO_Comma)
11665       break;
11666     LHS = BO->getRHS();
11667   }
11668 
11669   // Only allow some expressions on LHS to not warn.
11670   if (IgnoreCommaOperand(LHS))
11671     return;
11672 
11673   Diag(Loc, diag::warn_comma_operator);
11674   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11675       << LHS->getSourceRange()
11676       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11677                                     LangOpts.CPlusPlus ? "static_cast<void>("
11678                                                        : "(void)(")
11679       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11680                                     ")");
11681 }
11682 
11683 // C99 6.5.17
11684 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11685                                    SourceLocation Loc) {
11686   LHS = S.CheckPlaceholderExpr(LHS.get());
11687   RHS = S.CheckPlaceholderExpr(RHS.get());
11688   if (LHS.isInvalid() || RHS.isInvalid())
11689     return QualType();
11690 
11691   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11692   // operands, but not unary promotions.
11693   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11694 
11695   // So we treat the LHS as a ignored value, and in C++ we allow the
11696   // containing site to determine what should be done with the RHS.
11697   LHS = S.IgnoredValueConversions(LHS.get());
11698   if (LHS.isInvalid())
11699     return QualType();
11700 
11701   S.DiagnoseUnusedExprResult(LHS.get());
11702 
11703   if (!S.getLangOpts().CPlusPlus) {
11704     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11705     if (RHS.isInvalid())
11706       return QualType();
11707     if (!RHS.get()->getType()->isVoidType())
11708       S.RequireCompleteType(Loc, RHS.get()->getType(),
11709                             diag::err_incomplete_type);
11710   }
11711 
11712   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11713     S.DiagnoseCommaOperator(LHS.get(), Loc);
11714 
11715   return RHS.get()->getType();
11716 }
11717 
11718 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11719 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11720 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11721                                                ExprValueKind &VK,
11722                                                ExprObjectKind &OK,
11723                                                SourceLocation OpLoc,
11724                                                bool IsInc, bool IsPrefix) {
11725   if (Op->isTypeDependent())
11726     return S.Context.DependentTy;
11727 
11728   QualType ResType = Op->getType();
11729   // Atomic types can be used for increment / decrement where the non-atomic
11730   // versions can, so ignore the _Atomic() specifier for the purpose of
11731   // checking.
11732   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11733     ResType = ResAtomicType->getValueType();
11734 
11735   assert(!ResType.isNull() && "no type for increment/decrement expression");
11736 
11737   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11738     // Decrement of bool is not allowed.
11739     if (!IsInc) {
11740       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11741       return QualType();
11742     }
11743     // Increment of bool sets it to true, but is deprecated.
11744     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11745                                               : diag::warn_increment_bool)
11746       << Op->getSourceRange();
11747   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11748     // Error on enum increments and decrements in C++ mode
11749     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11750     return QualType();
11751   } else if (ResType->isRealType()) {
11752     // OK!
11753   } else if (ResType->isPointerType()) {
11754     // C99 6.5.2.4p2, 6.5.6p2
11755     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11756       return QualType();
11757   } else if (ResType->isObjCObjectPointerType()) {
11758     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11759     // Otherwise, we just need a complete type.
11760     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11761         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11762       return QualType();
11763   } else if (ResType->isAnyComplexType()) {
11764     // C99 does not support ++/-- on complex types, we allow as an extension.
11765     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11766       << ResType << Op->getSourceRange();
11767   } else if (ResType->isPlaceholderType()) {
11768     ExprResult PR = S.CheckPlaceholderExpr(Op);
11769     if (PR.isInvalid()) return QualType();
11770     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11771                                           IsInc, IsPrefix);
11772   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11773     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11774   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11775              (ResType->getAs<VectorType>()->getVectorKind() !=
11776               VectorType::AltiVecBool)) {
11777     // The z vector extensions allow ++ and -- for non-bool vectors.
11778   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11779             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11780     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11781   } else {
11782     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11783       << ResType << int(IsInc) << Op->getSourceRange();
11784     return QualType();
11785   }
11786   // At this point, we know we have a real, complex or pointer type.
11787   // Now make sure the operand is a modifiable lvalue.
11788   if (CheckForModifiableLvalue(Op, OpLoc, S))
11789     return QualType();
11790   // In C++, a prefix increment is the same type as the operand. Otherwise
11791   // (in C or with postfix), the increment is the unqualified type of the
11792   // operand.
11793   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11794     VK = VK_LValue;
11795     OK = Op->getObjectKind();
11796     return ResType;
11797   } else {
11798     VK = VK_RValue;
11799     return ResType.getUnqualifiedType();
11800   }
11801 }
11802 
11803 
11804 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11805 /// This routine allows us to typecheck complex/recursive expressions
11806 /// where the declaration is needed for type checking. We only need to
11807 /// handle cases when the expression references a function designator
11808 /// or is an lvalue. Here are some examples:
11809 ///  - &(x) => x
11810 ///  - &*****f => f for f a function designator.
11811 ///  - &s.xx => s
11812 ///  - &s.zz[1].yy -> s, if zz is an array
11813 ///  - *(x + 1) -> x, if x is an array
11814 ///  - &"123"[2] -> 0
11815 ///  - & __real__ x -> x
11816 static ValueDecl *getPrimaryDecl(Expr *E) {
11817   switch (E->getStmtClass()) {
11818   case Stmt::DeclRefExprClass:
11819     return cast<DeclRefExpr>(E)->getDecl();
11820   case Stmt::MemberExprClass:
11821     // If this is an arrow operator, the address is an offset from
11822     // the base's value, so the object the base refers to is
11823     // irrelevant.
11824     if (cast<MemberExpr>(E)->isArrow())
11825       return nullptr;
11826     // Otherwise, the expression refers to a part of the base
11827     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11828   case Stmt::ArraySubscriptExprClass: {
11829     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11830     // promotion of register arrays earlier.
11831     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11832     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11833       if (ICE->getSubExpr()->getType()->isArrayType())
11834         return getPrimaryDecl(ICE->getSubExpr());
11835     }
11836     return nullptr;
11837   }
11838   case Stmt::UnaryOperatorClass: {
11839     UnaryOperator *UO = cast<UnaryOperator>(E);
11840 
11841     switch(UO->getOpcode()) {
11842     case UO_Real:
11843     case UO_Imag:
11844     case UO_Extension:
11845       return getPrimaryDecl(UO->getSubExpr());
11846     default:
11847       return nullptr;
11848     }
11849   }
11850   case Stmt::ParenExprClass:
11851     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11852   case Stmt::ImplicitCastExprClass:
11853     // If the result of an implicit cast is an l-value, we care about
11854     // the sub-expression; otherwise, the result here doesn't matter.
11855     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11856   default:
11857     return nullptr;
11858   }
11859 }
11860 
11861 namespace {
11862   enum {
11863     AO_Bit_Field = 0,
11864     AO_Vector_Element = 1,
11865     AO_Property_Expansion = 2,
11866     AO_Register_Variable = 3,
11867     AO_No_Error = 4
11868   };
11869 }
11870 /// Diagnose invalid operand for address of operations.
11871 ///
11872 /// \param Type The type of operand which cannot have its address taken.
11873 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11874                                          Expr *E, unsigned Type) {
11875   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11876 }
11877 
11878 /// CheckAddressOfOperand - The operand of & must be either a function
11879 /// designator or an lvalue designating an object. If it is an lvalue, the
11880 /// object cannot be declared with storage class register or be a bit field.
11881 /// Note: The usual conversions are *not* applied to the operand of the &
11882 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11883 /// In C++, the operand might be an overloaded function name, in which case
11884 /// we allow the '&' but retain the overloaded-function type.
11885 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11886   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11887     if (PTy->getKind() == BuiltinType::Overload) {
11888       Expr *E = OrigOp.get()->IgnoreParens();
11889       if (!isa<OverloadExpr>(E)) {
11890         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11891         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11892           << OrigOp.get()->getSourceRange();
11893         return QualType();
11894       }
11895 
11896       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11897       if (isa<UnresolvedMemberExpr>(Ovl))
11898         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11899           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11900             << OrigOp.get()->getSourceRange();
11901           return QualType();
11902         }
11903 
11904       return Context.OverloadTy;
11905     }
11906 
11907     if (PTy->getKind() == BuiltinType::UnknownAny)
11908       return Context.UnknownAnyTy;
11909 
11910     if (PTy->getKind() == BuiltinType::BoundMember) {
11911       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11912         << OrigOp.get()->getSourceRange();
11913       return QualType();
11914     }
11915 
11916     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11917     if (OrigOp.isInvalid()) return QualType();
11918   }
11919 
11920   if (OrigOp.get()->isTypeDependent())
11921     return Context.DependentTy;
11922 
11923   assert(!OrigOp.get()->getType()->isPlaceholderType());
11924 
11925   // Make sure to ignore parentheses in subsequent checks
11926   Expr *op = OrigOp.get()->IgnoreParens();
11927 
11928   // In OpenCL captures for blocks called as lambda functions
11929   // are located in the private address space. Blocks used in
11930   // enqueue_kernel can be located in a different address space
11931   // depending on a vendor implementation. Thus preventing
11932   // taking an address of the capture to avoid invalid AS casts.
11933   if (LangOpts.OpenCL) {
11934     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11935     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11936       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11937       return QualType();
11938     }
11939   }
11940 
11941   if (getLangOpts().C99) {
11942     // Implement C99-only parts of addressof rules.
11943     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11944       if (uOp->getOpcode() == UO_Deref)
11945         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11946         // (assuming the deref expression is valid).
11947         return uOp->getSubExpr()->getType();
11948     }
11949     // Technically, there should be a check for array subscript
11950     // expressions here, but the result of one is always an lvalue anyway.
11951   }
11952   ValueDecl *dcl = getPrimaryDecl(op);
11953 
11954   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11955     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11956                                            op->getBeginLoc()))
11957       return QualType();
11958 
11959   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11960   unsigned AddressOfError = AO_No_Error;
11961 
11962   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11963     bool sfinae = (bool)isSFINAEContext();
11964     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11965                                   : diag::ext_typecheck_addrof_temporary)
11966       << op->getType() << op->getSourceRange();
11967     if (sfinae)
11968       return QualType();
11969     // Materialize the temporary as an lvalue so that we can take its address.
11970     OrigOp = op =
11971         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11972   } else if (isa<ObjCSelectorExpr>(op)) {
11973     return Context.getPointerType(op->getType());
11974   } else if (lval == Expr::LV_MemberFunction) {
11975     // If it's an instance method, make a member pointer.
11976     // The expression must have exactly the form &A::foo.
11977 
11978     // If the underlying expression isn't a decl ref, give up.
11979     if (!isa<DeclRefExpr>(op)) {
11980       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11981         << OrigOp.get()->getSourceRange();
11982       return QualType();
11983     }
11984     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11985     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11986 
11987     // The id-expression was parenthesized.
11988     if (OrigOp.get() != DRE) {
11989       Diag(OpLoc, diag::err_parens_pointer_member_function)
11990         << OrigOp.get()->getSourceRange();
11991 
11992     // The method was named without a qualifier.
11993     } else if (!DRE->getQualifier()) {
11994       if (MD->getParent()->getName().empty())
11995         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11996           << op->getSourceRange();
11997       else {
11998         SmallString<32> Str;
11999         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12000         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12001           << op->getSourceRange()
12002           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12003       }
12004     }
12005 
12006     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12007     if (isa<CXXDestructorDecl>(MD))
12008       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12009 
12010     QualType MPTy = Context.getMemberPointerType(
12011         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12012     // Under the MS ABI, lock down the inheritance model now.
12013     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12014       (void)isCompleteType(OpLoc, MPTy);
12015     return MPTy;
12016   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12017     // C99 6.5.3.2p1
12018     // The operand must be either an l-value or a function designator
12019     if (!op->getType()->isFunctionType()) {
12020       // Use a special diagnostic for loads from property references.
12021       if (isa<PseudoObjectExpr>(op)) {
12022         AddressOfError = AO_Property_Expansion;
12023       } else {
12024         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12025           << op->getType() << op->getSourceRange();
12026         return QualType();
12027       }
12028     }
12029   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12030     // The operand cannot be a bit-field
12031     AddressOfError = AO_Bit_Field;
12032   } else if (op->getObjectKind() == OK_VectorComponent) {
12033     // The operand cannot be an element of a vector
12034     AddressOfError = AO_Vector_Element;
12035   } else if (dcl) { // C99 6.5.3.2p1
12036     // We have an lvalue with a decl. Make sure the decl is not declared
12037     // with the register storage-class specifier.
12038     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12039       // in C++ it is not error to take address of a register
12040       // variable (c++03 7.1.1P3)
12041       if (vd->getStorageClass() == SC_Register &&
12042           !getLangOpts().CPlusPlus) {
12043         AddressOfError = AO_Register_Variable;
12044       }
12045     } else if (isa<MSPropertyDecl>(dcl)) {
12046       AddressOfError = AO_Property_Expansion;
12047     } else if (isa<FunctionTemplateDecl>(dcl)) {
12048       return Context.OverloadTy;
12049     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12050       // Okay: we can take the address of a field.
12051       // Could be a pointer to member, though, if there is an explicit
12052       // scope qualifier for the class.
12053       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12054         DeclContext *Ctx = dcl->getDeclContext();
12055         if (Ctx && Ctx->isRecord()) {
12056           if (dcl->getType()->isReferenceType()) {
12057             Diag(OpLoc,
12058                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12059               << dcl->getDeclName() << dcl->getType();
12060             return QualType();
12061           }
12062 
12063           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12064             Ctx = Ctx->getParent();
12065 
12066           QualType MPTy = Context.getMemberPointerType(
12067               op->getType(),
12068               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12069           // Under the MS ABI, lock down the inheritance model now.
12070           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12071             (void)isCompleteType(OpLoc, MPTy);
12072           return MPTy;
12073         }
12074       }
12075     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12076                !isa<BindingDecl>(dcl))
12077       llvm_unreachable("Unknown/unexpected decl type");
12078   }
12079 
12080   if (AddressOfError != AO_No_Error) {
12081     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12082     return QualType();
12083   }
12084 
12085   if (lval == Expr::LV_IncompleteVoidType) {
12086     // Taking the address of a void variable is technically illegal, but we
12087     // allow it in cases which are otherwise valid.
12088     // Example: "extern void x; void* y = &x;".
12089     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12090   }
12091 
12092   // If the operand has type "type", the result has type "pointer to type".
12093   if (op->getType()->isObjCObjectType())
12094     return Context.getObjCObjectPointerType(op->getType());
12095 
12096   CheckAddressOfPackedMember(op);
12097 
12098   return Context.getPointerType(op->getType());
12099 }
12100 
12101 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12102   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12103   if (!DRE)
12104     return;
12105   const Decl *D = DRE->getDecl();
12106   if (!D)
12107     return;
12108   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12109   if (!Param)
12110     return;
12111   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12112     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12113       return;
12114   if (FunctionScopeInfo *FD = S.getCurFunction())
12115     if (!FD->ModifiedNonNullParams.count(Param))
12116       FD->ModifiedNonNullParams.insert(Param);
12117 }
12118 
12119 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12120 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12121                                         SourceLocation OpLoc) {
12122   if (Op->isTypeDependent())
12123     return S.Context.DependentTy;
12124 
12125   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12126   if (ConvResult.isInvalid())
12127     return QualType();
12128   Op = ConvResult.get();
12129   QualType OpTy = Op->getType();
12130   QualType Result;
12131 
12132   if (isa<CXXReinterpretCastExpr>(Op)) {
12133     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12134     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12135                                      Op->getSourceRange());
12136   }
12137 
12138   if (const PointerType *PT = OpTy->getAs<PointerType>())
12139   {
12140     Result = PT->getPointeeType();
12141   }
12142   else if (const ObjCObjectPointerType *OPT =
12143              OpTy->getAs<ObjCObjectPointerType>())
12144     Result = OPT->getPointeeType();
12145   else {
12146     ExprResult PR = S.CheckPlaceholderExpr(Op);
12147     if (PR.isInvalid()) return QualType();
12148     if (PR.get() != Op)
12149       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12150   }
12151 
12152   if (Result.isNull()) {
12153     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12154       << OpTy << Op->getSourceRange();
12155     return QualType();
12156   }
12157 
12158   // Note that per both C89 and C99, indirection is always legal, even if Result
12159   // is an incomplete type or void.  It would be possible to warn about
12160   // dereferencing a void pointer, but it's completely well-defined, and such a
12161   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12162   // for pointers to 'void' but is fine for any other pointer type:
12163   //
12164   // C++ [expr.unary.op]p1:
12165   //   [...] the expression to which [the unary * operator] is applied shall
12166   //   be a pointer to an object type, or a pointer to a function type
12167   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12168     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12169       << OpTy << Op->getSourceRange();
12170 
12171   // Dereferences are usually l-values...
12172   VK = VK_LValue;
12173 
12174   // ...except that certain expressions are never l-values in C.
12175   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12176     VK = VK_RValue;
12177 
12178   return Result;
12179 }
12180 
12181 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12182   BinaryOperatorKind Opc;
12183   switch (Kind) {
12184   default: llvm_unreachable("Unknown binop!");
12185   case tok::periodstar:           Opc = BO_PtrMemD; break;
12186   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12187   case tok::star:                 Opc = BO_Mul; break;
12188   case tok::slash:                Opc = BO_Div; break;
12189   case tok::percent:              Opc = BO_Rem; break;
12190   case tok::plus:                 Opc = BO_Add; break;
12191   case tok::minus:                Opc = BO_Sub; break;
12192   case tok::lessless:             Opc = BO_Shl; break;
12193   case tok::greatergreater:       Opc = BO_Shr; break;
12194   case tok::lessequal:            Opc = BO_LE; break;
12195   case tok::less:                 Opc = BO_LT; break;
12196   case tok::greaterequal:         Opc = BO_GE; break;
12197   case tok::greater:              Opc = BO_GT; break;
12198   case tok::exclaimequal:         Opc = BO_NE; break;
12199   case tok::equalequal:           Opc = BO_EQ; break;
12200   case tok::spaceship:            Opc = BO_Cmp; break;
12201   case tok::amp:                  Opc = BO_And; break;
12202   case tok::caret:                Opc = BO_Xor; break;
12203   case tok::pipe:                 Opc = BO_Or; break;
12204   case tok::ampamp:               Opc = BO_LAnd; break;
12205   case tok::pipepipe:             Opc = BO_LOr; break;
12206   case tok::equal:                Opc = BO_Assign; break;
12207   case tok::starequal:            Opc = BO_MulAssign; break;
12208   case tok::slashequal:           Opc = BO_DivAssign; break;
12209   case tok::percentequal:         Opc = BO_RemAssign; break;
12210   case tok::plusequal:            Opc = BO_AddAssign; break;
12211   case tok::minusequal:           Opc = BO_SubAssign; break;
12212   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12213   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12214   case tok::ampequal:             Opc = BO_AndAssign; break;
12215   case tok::caretequal:           Opc = BO_XorAssign; break;
12216   case tok::pipeequal:            Opc = BO_OrAssign; break;
12217   case tok::comma:                Opc = BO_Comma; break;
12218   }
12219   return Opc;
12220 }
12221 
12222 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12223   tok::TokenKind Kind) {
12224   UnaryOperatorKind Opc;
12225   switch (Kind) {
12226   default: llvm_unreachable("Unknown unary op!");
12227   case tok::plusplus:     Opc = UO_PreInc; break;
12228   case tok::minusminus:   Opc = UO_PreDec; break;
12229   case tok::amp:          Opc = UO_AddrOf; break;
12230   case tok::star:         Opc = UO_Deref; break;
12231   case tok::plus:         Opc = UO_Plus; break;
12232   case tok::minus:        Opc = UO_Minus; break;
12233   case tok::tilde:        Opc = UO_Not; break;
12234   case tok::exclaim:      Opc = UO_LNot; break;
12235   case tok::kw___real:    Opc = UO_Real; break;
12236   case tok::kw___imag:    Opc = UO_Imag; break;
12237   case tok::kw___extension__: Opc = UO_Extension; break;
12238   }
12239   return Opc;
12240 }
12241 
12242 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12243 /// This warning suppressed in the event of macro expansions.
12244 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12245                                    SourceLocation OpLoc, bool IsBuiltin) {
12246   if (S.inTemplateInstantiation())
12247     return;
12248   if (S.isUnevaluatedContext())
12249     return;
12250   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12251     return;
12252   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12253   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12254   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12255   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12256   if (!LHSDeclRef || !RHSDeclRef ||
12257       LHSDeclRef->getLocation().isMacroID() ||
12258       RHSDeclRef->getLocation().isMacroID())
12259     return;
12260   const ValueDecl *LHSDecl =
12261     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12262   const ValueDecl *RHSDecl =
12263     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12264   if (LHSDecl != RHSDecl)
12265     return;
12266   if (LHSDecl->getType().isVolatileQualified())
12267     return;
12268   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12269     if (RefTy->getPointeeType().isVolatileQualified())
12270       return;
12271 
12272   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12273                           : diag::warn_self_assignment_overloaded)
12274       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12275       << RHSExpr->getSourceRange();
12276 }
12277 
12278 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12279 /// is usually indicative of introspection within the Objective-C pointer.
12280 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12281                                           SourceLocation OpLoc) {
12282   if (!S.getLangOpts().ObjC)
12283     return;
12284 
12285   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12286   const Expr *LHS = L.get();
12287   const Expr *RHS = R.get();
12288 
12289   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12290     ObjCPointerExpr = LHS;
12291     OtherExpr = RHS;
12292   }
12293   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12294     ObjCPointerExpr = RHS;
12295     OtherExpr = LHS;
12296   }
12297 
12298   // This warning is deliberately made very specific to reduce false
12299   // positives with logic that uses '&' for hashing.  This logic mainly
12300   // looks for code trying to introspect into tagged pointers, which
12301   // code should generally never do.
12302   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12303     unsigned Diag = diag::warn_objc_pointer_masking;
12304     // Determine if we are introspecting the result of performSelectorXXX.
12305     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12306     // Special case messages to -performSelector and friends, which
12307     // can return non-pointer values boxed in a pointer value.
12308     // Some clients may wish to silence warnings in this subcase.
12309     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12310       Selector S = ME->getSelector();
12311       StringRef SelArg0 = S.getNameForSlot(0);
12312       if (SelArg0.startswith("performSelector"))
12313         Diag = diag::warn_objc_pointer_masking_performSelector;
12314     }
12315 
12316     S.Diag(OpLoc, Diag)
12317       << ObjCPointerExpr->getSourceRange();
12318   }
12319 }
12320 
12321 static NamedDecl *getDeclFromExpr(Expr *E) {
12322   if (!E)
12323     return nullptr;
12324   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12325     return DRE->getDecl();
12326   if (auto *ME = dyn_cast<MemberExpr>(E))
12327     return ME->getMemberDecl();
12328   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12329     return IRE->getDecl();
12330   return nullptr;
12331 }
12332 
12333 // This helper function promotes a binary operator's operands (which are of a
12334 // half vector type) to a vector of floats and then truncates the result to
12335 // a vector of either half or short.
12336 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12337                                       BinaryOperatorKind Opc, QualType ResultTy,
12338                                       ExprValueKind VK, ExprObjectKind OK,
12339                                       bool IsCompAssign, SourceLocation OpLoc,
12340                                       FPOptions FPFeatures) {
12341   auto &Context = S.getASTContext();
12342   assert((isVector(ResultTy, Context.HalfTy) ||
12343           isVector(ResultTy, Context.ShortTy)) &&
12344          "Result must be a vector of half or short");
12345   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12346          isVector(RHS.get()->getType(), Context.HalfTy) &&
12347          "both operands expected to be a half vector");
12348 
12349   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12350   QualType BinOpResTy = RHS.get()->getType();
12351 
12352   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12353   // change BinOpResTy to a vector of ints.
12354   if (isVector(ResultTy, Context.ShortTy))
12355     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12356 
12357   if (IsCompAssign)
12358     return new (Context) CompoundAssignOperator(
12359         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12360         OpLoc, FPFeatures);
12361 
12362   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12363   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12364                                           VK, OK, OpLoc, FPFeatures);
12365   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12366 }
12367 
12368 static std::pair<ExprResult, ExprResult>
12369 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12370                            Expr *RHSExpr) {
12371   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12372   if (!S.getLangOpts().CPlusPlus) {
12373     // C cannot handle TypoExpr nodes on either side of a binop because it
12374     // doesn't handle dependent types properly, so make sure any TypoExprs have
12375     // been dealt with before checking the operands.
12376     LHS = S.CorrectDelayedTyposInExpr(LHS);
12377     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12378       if (Opc != BO_Assign)
12379         return ExprResult(E);
12380       // Avoid correcting the RHS to the same Expr as the LHS.
12381       Decl *D = getDeclFromExpr(E);
12382       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12383     });
12384   }
12385   return std::make_pair(LHS, RHS);
12386 }
12387 
12388 /// Returns true if conversion between vectors of halfs and vectors of floats
12389 /// is needed.
12390 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12391                                      QualType SrcType) {
12392   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12393          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12394          isVector(SrcType, Ctx.HalfTy);
12395 }
12396 
12397 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12398 /// operator @p Opc at location @c TokLoc. This routine only supports
12399 /// built-in operations; ActOnBinOp handles overloaded operators.
12400 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12401                                     BinaryOperatorKind Opc,
12402                                     Expr *LHSExpr, Expr *RHSExpr) {
12403   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12404     // The syntax only allows initializer lists on the RHS of assignment,
12405     // so we don't need to worry about accepting invalid code for
12406     // non-assignment operators.
12407     // C++11 5.17p9:
12408     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12409     //   of x = {} is x = T().
12410     InitializationKind Kind = InitializationKind::CreateDirectList(
12411         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12412     InitializedEntity Entity =
12413         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12414     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12415     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12416     if (Init.isInvalid())
12417       return Init;
12418     RHSExpr = Init.get();
12419   }
12420 
12421   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12422   QualType ResultTy;     // Result type of the binary operator.
12423   // The following two variables are used for compound assignment operators
12424   QualType CompLHSTy;    // Type of LHS after promotions for computation
12425   QualType CompResultTy; // Type of computation result
12426   ExprValueKind VK = VK_RValue;
12427   ExprObjectKind OK = OK_Ordinary;
12428   bool ConvertHalfVec = false;
12429 
12430   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12431   if (!LHS.isUsable() || !RHS.isUsable())
12432     return ExprError();
12433 
12434   if (getLangOpts().OpenCL) {
12435     QualType LHSTy = LHSExpr->getType();
12436     QualType RHSTy = RHSExpr->getType();
12437     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12438     // the ATOMIC_VAR_INIT macro.
12439     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12440       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12441       if (BO_Assign == Opc)
12442         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12443       else
12444         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12445       return ExprError();
12446     }
12447 
12448     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12449     // only with a builtin functions and therefore should be disallowed here.
12450     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12451         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12452         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12453         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12454       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12455       return ExprError();
12456     }
12457   }
12458 
12459   // Diagnose operations on the unsupported types for OpenMP device compilation.
12460   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12461     if (Opc != BO_Assign && Opc != BO_Comma) {
12462       checkOpenMPDeviceExpr(LHSExpr);
12463       checkOpenMPDeviceExpr(RHSExpr);
12464     }
12465   }
12466 
12467   switch (Opc) {
12468   case BO_Assign:
12469     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12470     if (getLangOpts().CPlusPlus &&
12471         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12472       VK = LHS.get()->getValueKind();
12473       OK = LHS.get()->getObjectKind();
12474     }
12475     if (!ResultTy.isNull()) {
12476       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12477       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12478 
12479       // Avoid copying a block to the heap if the block is assigned to a local
12480       // auto variable that is declared in the same scope as the block. This
12481       // optimization is unsafe if the local variable is declared in an outer
12482       // scope. For example:
12483       //
12484       // BlockTy b;
12485       // {
12486       //   b = ^{...};
12487       // }
12488       // // It is unsafe to invoke the block here if it wasn't copied to the
12489       // // heap.
12490       // b();
12491 
12492       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12493         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12494           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12495             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12496               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12497     }
12498     RecordModifiableNonNullParam(*this, LHS.get());
12499     break;
12500   case BO_PtrMemD:
12501   case BO_PtrMemI:
12502     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12503                                             Opc == BO_PtrMemI);
12504     break;
12505   case BO_Mul:
12506   case BO_Div:
12507     ConvertHalfVec = true;
12508     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12509                                            Opc == BO_Div);
12510     break;
12511   case BO_Rem:
12512     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12513     break;
12514   case BO_Add:
12515     ConvertHalfVec = true;
12516     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12517     break;
12518   case BO_Sub:
12519     ConvertHalfVec = true;
12520     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12521     break;
12522   case BO_Shl:
12523   case BO_Shr:
12524     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12525     break;
12526   case BO_LE:
12527   case BO_LT:
12528   case BO_GE:
12529   case BO_GT:
12530     ConvertHalfVec = true;
12531     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12532     break;
12533   case BO_EQ:
12534   case BO_NE:
12535     ConvertHalfVec = true;
12536     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12537     break;
12538   case BO_Cmp:
12539     ConvertHalfVec = true;
12540     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12541     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12542     break;
12543   case BO_And:
12544     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12545     LLVM_FALLTHROUGH;
12546   case BO_Xor:
12547   case BO_Or:
12548     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12549     break;
12550   case BO_LAnd:
12551   case BO_LOr:
12552     ConvertHalfVec = true;
12553     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12554     break;
12555   case BO_MulAssign:
12556   case BO_DivAssign:
12557     ConvertHalfVec = true;
12558     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12559                                                Opc == BO_DivAssign);
12560     CompLHSTy = CompResultTy;
12561     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12562       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12563     break;
12564   case BO_RemAssign:
12565     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12566     CompLHSTy = CompResultTy;
12567     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12568       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12569     break;
12570   case BO_AddAssign:
12571     ConvertHalfVec = true;
12572     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12573     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12574       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12575     break;
12576   case BO_SubAssign:
12577     ConvertHalfVec = true;
12578     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12579     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12580       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12581     break;
12582   case BO_ShlAssign:
12583   case BO_ShrAssign:
12584     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12585     CompLHSTy = CompResultTy;
12586     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12587       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12588     break;
12589   case BO_AndAssign:
12590   case BO_OrAssign: // fallthrough
12591     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12592     LLVM_FALLTHROUGH;
12593   case BO_XorAssign:
12594     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12595     CompLHSTy = CompResultTy;
12596     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12597       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12598     break;
12599   case BO_Comma:
12600     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12601     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12602       VK = RHS.get()->getValueKind();
12603       OK = RHS.get()->getObjectKind();
12604     }
12605     break;
12606   }
12607   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12608     return ExprError();
12609 
12610   // Some of the binary operations require promoting operands of half vector to
12611   // float vectors and truncating the result back to half vector. For now, we do
12612   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12613   // arm64).
12614   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12615          isVector(LHS.get()->getType(), Context.HalfTy) &&
12616          "both sides are half vectors or neither sides are");
12617   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12618                                             LHS.get()->getType());
12619 
12620   // Check for array bounds violations for both sides of the BinaryOperator
12621   CheckArrayAccess(LHS.get());
12622   CheckArrayAccess(RHS.get());
12623 
12624   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12625     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12626                                                  &Context.Idents.get("object_setClass"),
12627                                                  SourceLocation(), LookupOrdinaryName);
12628     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12629       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12630       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12631           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12632                                         "object_setClass(")
12633           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12634                                           ",")
12635           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12636     }
12637     else
12638       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12639   }
12640   else if (const ObjCIvarRefExpr *OIRE =
12641            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12642     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12643 
12644   // Opc is not a compound assignment if CompResultTy is null.
12645   if (CompResultTy.isNull()) {
12646     if (ConvertHalfVec)
12647       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12648                                  OpLoc, FPFeatures);
12649     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12650                                         OK, OpLoc, FPFeatures);
12651   }
12652 
12653   // Handle compound assignments.
12654   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12655       OK_ObjCProperty) {
12656     VK = VK_LValue;
12657     OK = LHS.get()->getObjectKind();
12658   }
12659 
12660   if (ConvertHalfVec)
12661     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12662                                OpLoc, FPFeatures);
12663 
12664   return new (Context) CompoundAssignOperator(
12665       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12666       OpLoc, FPFeatures);
12667 }
12668 
12669 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12670 /// operators are mixed in a way that suggests that the programmer forgot that
12671 /// comparison operators have higher precedence. The most typical example of
12672 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12673 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12674                                       SourceLocation OpLoc, Expr *LHSExpr,
12675                                       Expr *RHSExpr) {
12676   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12677   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12678 
12679   // Check that one of the sides is a comparison operator and the other isn't.
12680   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12681   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12682   if (isLeftComp == isRightComp)
12683     return;
12684 
12685   // Bitwise operations are sometimes used as eager logical ops.
12686   // Don't diagnose this.
12687   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12688   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12689   if (isLeftBitwise || isRightBitwise)
12690     return;
12691 
12692   SourceRange DiagRange = isLeftComp
12693                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12694                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12695   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12696   SourceRange ParensRange =
12697       isLeftComp
12698           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12699           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12700 
12701   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12702     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12703   SuggestParentheses(Self, OpLoc,
12704     Self.PDiag(diag::note_precedence_silence) << OpStr,
12705     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12706   SuggestParentheses(Self, OpLoc,
12707     Self.PDiag(diag::note_precedence_bitwise_first)
12708       << BinaryOperator::getOpcodeStr(Opc),
12709     ParensRange);
12710 }
12711 
12712 /// It accepts a '&&' expr that is inside a '||' one.
12713 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12714 /// in parentheses.
12715 static void
12716 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12717                                        BinaryOperator *Bop) {
12718   assert(Bop->getOpcode() == BO_LAnd);
12719   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12720       << Bop->getSourceRange() << OpLoc;
12721   SuggestParentheses(Self, Bop->getOperatorLoc(),
12722     Self.PDiag(diag::note_precedence_silence)
12723       << Bop->getOpcodeStr(),
12724     Bop->getSourceRange());
12725 }
12726 
12727 /// Returns true if the given expression can be evaluated as a constant
12728 /// 'true'.
12729 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12730   bool Res;
12731   return !E->isValueDependent() &&
12732          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12733 }
12734 
12735 /// Returns true if the given expression can be evaluated as a constant
12736 /// 'false'.
12737 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12738   bool Res;
12739   return !E->isValueDependent() &&
12740          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12741 }
12742 
12743 /// Look for '&&' in the left hand of a '||' expr.
12744 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12745                                              Expr *LHSExpr, Expr *RHSExpr) {
12746   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12747     if (Bop->getOpcode() == BO_LAnd) {
12748       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12749       if (EvaluatesAsFalse(S, RHSExpr))
12750         return;
12751       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12752       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12753         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12754     } else if (Bop->getOpcode() == BO_LOr) {
12755       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12756         // If it's "a || b && 1 || c" we didn't warn earlier for
12757         // "a || b && 1", but warn now.
12758         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12759           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12760       }
12761     }
12762   }
12763 }
12764 
12765 /// Look for '&&' in the right hand of a '||' expr.
12766 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12767                                              Expr *LHSExpr, Expr *RHSExpr) {
12768   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12769     if (Bop->getOpcode() == BO_LAnd) {
12770       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12771       if (EvaluatesAsFalse(S, LHSExpr))
12772         return;
12773       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12774       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12775         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12776     }
12777   }
12778 }
12779 
12780 /// Look for bitwise op in the left or right hand of a bitwise op with
12781 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12782 /// the '&' expression in parentheses.
12783 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12784                                          SourceLocation OpLoc, Expr *SubExpr) {
12785   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12786     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12787       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12788         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12789         << Bop->getSourceRange() << OpLoc;
12790       SuggestParentheses(S, Bop->getOperatorLoc(),
12791         S.PDiag(diag::note_precedence_silence)
12792           << Bop->getOpcodeStr(),
12793         Bop->getSourceRange());
12794     }
12795   }
12796 }
12797 
12798 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12799                                     Expr *SubExpr, StringRef Shift) {
12800   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12801     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12802       StringRef Op = Bop->getOpcodeStr();
12803       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12804           << Bop->getSourceRange() << OpLoc << Shift << Op;
12805       SuggestParentheses(S, Bop->getOperatorLoc(),
12806           S.PDiag(diag::note_precedence_silence) << Op,
12807           Bop->getSourceRange());
12808     }
12809   }
12810 }
12811 
12812 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12813                                  Expr *LHSExpr, Expr *RHSExpr) {
12814   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12815   if (!OCE)
12816     return;
12817 
12818   FunctionDecl *FD = OCE->getDirectCallee();
12819   if (!FD || !FD->isOverloadedOperator())
12820     return;
12821 
12822   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12823   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12824     return;
12825 
12826   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12827       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12828       << (Kind == OO_LessLess);
12829   SuggestParentheses(S, OCE->getOperatorLoc(),
12830                      S.PDiag(diag::note_precedence_silence)
12831                          << (Kind == OO_LessLess ? "<<" : ">>"),
12832                      OCE->getSourceRange());
12833   SuggestParentheses(
12834       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12835       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12836 }
12837 
12838 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12839 /// precedence.
12840 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12841                                     SourceLocation OpLoc, Expr *LHSExpr,
12842                                     Expr *RHSExpr){
12843   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12844   if (BinaryOperator::isBitwiseOp(Opc))
12845     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12846 
12847   // Diagnose "arg1 & arg2 | arg3"
12848   if ((Opc == BO_Or || Opc == BO_Xor) &&
12849       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12850     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12851     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12852   }
12853 
12854   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12855   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12856   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12857     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12858     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12859   }
12860 
12861   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12862       || Opc == BO_Shr) {
12863     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12864     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12865     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12866   }
12867 
12868   // Warn on overloaded shift operators and comparisons, such as:
12869   // cout << 5 == 4;
12870   if (BinaryOperator::isComparisonOp(Opc))
12871     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12872 }
12873 
12874 // Binary Operators.  'Tok' is the token for the operator.
12875 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12876                             tok::TokenKind Kind,
12877                             Expr *LHSExpr, Expr *RHSExpr) {
12878   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12879   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12880   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12881 
12882   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12883   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12884 
12885   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12886 }
12887 
12888 /// Build an overloaded binary operator expression in the given scope.
12889 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12890                                        BinaryOperatorKind Opc,
12891                                        Expr *LHS, Expr *RHS) {
12892   switch (Opc) {
12893   case BO_Assign:
12894   case BO_DivAssign:
12895   case BO_RemAssign:
12896   case BO_SubAssign:
12897   case BO_AndAssign:
12898   case BO_OrAssign:
12899   case BO_XorAssign:
12900     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12901     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12902     break;
12903   default:
12904     break;
12905   }
12906 
12907   // Find all of the overloaded operators visible from this
12908   // point. We perform both an operator-name lookup from the local
12909   // scope and an argument-dependent lookup based on the types of
12910   // the arguments.
12911   UnresolvedSet<16> Functions;
12912   OverloadedOperatorKind OverOp
12913     = BinaryOperator::getOverloadedOperator(Opc);
12914   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12915     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12916                                    RHS->getType(), Functions);
12917 
12918   // Build the (potentially-overloaded, potentially-dependent)
12919   // binary operation.
12920   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12921 }
12922 
12923 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12924                             BinaryOperatorKind Opc,
12925                             Expr *LHSExpr, Expr *RHSExpr) {
12926   ExprResult LHS, RHS;
12927   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12928   if (!LHS.isUsable() || !RHS.isUsable())
12929     return ExprError();
12930   LHSExpr = LHS.get();
12931   RHSExpr = RHS.get();
12932 
12933   // We want to end up calling one of checkPseudoObjectAssignment
12934   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12935   // both expressions are overloadable or either is type-dependent),
12936   // or CreateBuiltinBinOp (in any other case).  We also want to get
12937   // any placeholder types out of the way.
12938 
12939   // Handle pseudo-objects in the LHS.
12940   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12941     // Assignments with a pseudo-object l-value need special analysis.
12942     if (pty->getKind() == BuiltinType::PseudoObject &&
12943         BinaryOperator::isAssignmentOp(Opc))
12944       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12945 
12946     // Don't resolve overloads if the other type is overloadable.
12947     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12948       // We can't actually test that if we still have a placeholder,
12949       // though.  Fortunately, none of the exceptions we see in that
12950       // code below are valid when the LHS is an overload set.  Note
12951       // that an overload set can be dependently-typed, but it never
12952       // instantiates to having an overloadable type.
12953       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12954       if (resolvedRHS.isInvalid()) return ExprError();
12955       RHSExpr = resolvedRHS.get();
12956 
12957       if (RHSExpr->isTypeDependent() ||
12958           RHSExpr->getType()->isOverloadableType())
12959         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12960     }
12961 
12962     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12963     // template, diagnose the missing 'template' keyword instead of diagnosing
12964     // an invalid use of a bound member function.
12965     //
12966     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12967     // to C++1z [over.over]/1.4, but we already checked for that case above.
12968     if (Opc == BO_LT && inTemplateInstantiation() &&
12969         (pty->getKind() == BuiltinType::BoundMember ||
12970          pty->getKind() == BuiltinType::Overload)) {
12971       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12972       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12973           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12974             return isa<FunctionTemplateDecl>(ND);
12975           })) {
12976         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12977                                 : OE->getNameLoc(),
12978              diag::err_template_kw_missing)
12979           << OE->getName().getAsString() << "";
12980         return ExprError();
12981       }
12982     }
12983 
12984     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12985     if (LHS.isInvalid()) return ExprError();
12986     LHSExpr = LHS.get();
12987   }
12988 
12989   // Handle pseudo-objects in the RHS.
12990   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12991     // An overload in the RHS can potentially be resolved by the type
12992     // being assigned to.
12993     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12994       if (getLangOpts().CPlusPlus &&
12995           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12996            LHSExpr->getType()->isOverloadableType()))
12997         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12998 
12999       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13000     }
13001 
13002     // Don't resolve overloads if the other type is overloadable.
13003     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13004         LHSExpr->getType()->isOverloadableType())
13005       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13006 
13007     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13008     if (!resolvedRHS.isUsable()) return ExprError();
13009     RHSExpr = resolvedRHS.get();
13010   }
13011 
13012   if (getLangOpts().CPlusPlus) {
13013     // If either expression is type-dependent, always build an
13014     // overloaded op.
13015     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13016       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13017 
13018     // Otherwise, build an overloaded op if either expression has an
13019     // overloadable type.
13020     if (LHSExpr->getType()->isOverloadableType() ||
13021         RHSExpr->getType()->isOverloadableType())
13022       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13023   }
13024 
13025   // Build a built-in binary operation.
13026   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13027 }
13028 
13029 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13030   if (T.isNull() || T->isDependentType())
13031     return false;
13032 
13033   if (!T->isPromotableIntegerType())
13034     return true;
13035 
13036   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13037 }
13038 
13039 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13040                                       UnaryOperatorKind Opc,
13041                                       Expr *InputExpr) {
13042   ExprResult Input = InputExpr;
13043   ExprValueKind VK = VK_RValue;
13044   ExprObjectKind OK = OK_Ordinary;
13045   QualType resultType;
13046   bool CanOverflow = false;
13047 
13048   bool ConvertHalfVec = false;
13049   if (getLangOpts().OpenCL) {
13050     QualType Ty = InputExpr->getType();
13051     // The only legal unary operation for atomics is '&'.
13052     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13053     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13054     // only with a builtin functions and therefore should be disallowed here.
13055         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13056         || Ty->isBlockPointerType())) {
13057       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13058                        << InputExpr->getType()
13059                        << Input.get()->getSourceRange());
13060     }
13061   }
13062   // Diagnose operations on the unsupported types for OpenMP device compilation.
13063   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13064     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13065         UnaryOperator::isArithmeticOp(Opc))
13066       checkOpenMPDeviceExpr(InputExpr);
13067   }
13068 
13069   switch (Opc) {
13070   case UO_PreInc:
13071   case UO_PreDec:
13072   case UO_PostInc:
13073   case UO_PostDec:
13074     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13075                                                 OpLoc,
13076                                                 Opc == UO_PreInc ||
13077                                                 Opc == UO_PostInc,
13078                                                 Opc == UO_PreInc ||
13079                                                 Opc == UO_PreDec);
13080     CanOverflow = isOverflowingIntegerType(Context, resultType);
13081     break;
13082   case UO_AddrOf:
13083     resultType = CheckAddressOfOperand(Input, OpLoc);
13084     CheckAddressOfNoDeref(InputExpr);
13085     RecordModifiableNonNullParam(*this, InputExpr);
13086     break;
13087   case UO_Deref: {
13088     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13089     if (Input.isInvalid()) return ExprError();
13090     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13091     break;
13092   }
13093   case UO_Plus:
13094   case UO_Minus:
13095     CanOverflow = Opc == UO_Minus &&
13096                   isOverflowingIntegerType(Context, Input.get()->getType());
13097     Input = UsualUnaryConversions(Input.get());
13098     if (Input.isInvalid()) return ExprError();
13099     // Unary plus and minus require promoting an operand of half vector to a
13100     // float vector and truncating the result back to a half vector. For now, we
13101     // do this only when HalfArgsAndReturns is set (that is, when the target is
13102     // arm or arm64).
13103     ConvertHalfVec =
13104         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13105 
13106     // If the operand is a half vector, promote it to a float vector.
13107     if (ConvertHalfVec)
13108       Input = convertVector(Input.get(), Context.FloatTy, *this);
13109     resultType = Input.get()->getType();
13110     if (resultType->isDependentType())
13111       break;
13112     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13113       break;
13114     else if (resultType->isVectorType() &&
13115              // The z vector extensions don't allow + or - with bool vectors.
13116              (!Context.getLangOpts().ZVector ||
13117               resultType->getAs<VectorType>()->getVectorKind() !=
13118               VectorType::AltiVecBool))
13119       break;
13120     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13121              Opc == UO_Plus &&
13122              resultType->isPointerType())
13123       break;
13124 
13125     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13126       << resultType << Input.get()->getSourceRange());
13127 
13128   case UO_Not: // bitwise complement
13129     Input = UsualUnaryConversions(Input.get());
13130     if (Input.isInvalid())
13131       return ExprError();
13132     resultType = Input.get()->getType();
13133 
13134     if (resultType->isDependentType())
13135       break;
13136     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13137     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13138       // C99 does not support '~' for complex conjugation.
13139       Diag(OpLoc, diag::ext_integer_complement_complex)
13140           << resultType << Input.get()->getSourceRange();
13141     else if (resultType->hasIntegerRepresentation())
13142       break;
13143     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13144       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13145       // on vector float types.
13146       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13147       if (!T->isIntegerType())
13148         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13149                           << resultType << Input.get()->getSourceRange());
13150     } else {
13151       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13152                        << resultType << Input.get()->getSourceRange());
13153     }
13154     break;
13155 
13156   case UO_LNot: // logical negation
13157     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13158     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13159     if (Input.isInvalid()) return ExprError();
13160     resultType = Input.get()->getType();
13161 
13162     // Though we still have to promote half FP to float...
13163     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13164       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13165       resultType = Context.FloatTy;
13166     }
13167 
13168     if (resultType->isDependentType())
13169       break;
13170     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13171       // C99 6.5.3.3p1: ok, fallthrough;
13172       if (Context.getLangOpts().CPlusPlus) {
13173         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13174         // operand contextually converted to bool.
13175         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13176                                   ScalarTypeToBooleanCastKind(resultType));
13177       } else if (Context.getLangOpts().OpenCL &&
13178                  Context.getLangOpts().OpenCLVersion < 120) {
13179         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13180         // operate on scalar float types.
13181         if (!resultType->isIntegerType() && !resultType->isPointerType())
13182           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13183                            << resultType << Input.get()->getSourceRange());
13184       }
13185     } else if (resultType->isExtVectorType()) {
13186       if (Context.getLangOpts().OpenCL &&
13187           Context.getLangOpts().OpenCLVersion < 120) {
13188         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13189         // operate on vector float types.
13190         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13191         if (!T->isIntegerType())
13192           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13193                            << resultType << Input.get()->getSourceRange());
13194       }
13195       // Vector logical not returns the signed variant of the operand type.
13196       resultType = GetSignedVectorType(resultType);
13197       break;
13198     } else {
13199       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13200       //        type in C++. We should allow that here too.
13201       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13202         << resultType << Input.get()->getSourceRange());
13203     }
13204 
13205     // LNot always has type int. C99 6.5.3.3p5.
13206     // In C++, it's bool. C++ 5.3.1p8
13207     resultType = Context.getLogicalOperationType();
13208     break;
13209   case UO_Real:
13210   case UO_Imag:
13211     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13212     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13213     // complex l-values to ordinary l-values and all other values to r-values.
13214     if (Input.isInvalid()) return ExprError();
13215     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13216       if (Input.get()->getValueKind() != VK_RValue &&
13217           Input.get()->getObjectKind() == OK_Ordinary)
13218         VK = Input.get()->getValueKind();
13219     } else if (!getLangOpts().CPlusPlus) {
13220       // In C, a volatile scalar is read by __imag. In C++, it is not.
13221       Input = DefaultLvalueConversion(Input.get());
13222     }
13223     break;
13224   case UO_Extension:
13225     resultType = Input.get()->getType();
13226     VK = Input.get()->getValueKind();
13227     OK = Input.get()->getObjectKind();
13228     break;
13229   case UO_Coawait:
13230     // It's unnecessary to represent the pass-through operator co_await in the
13231     // AST; just return the input expression instead.
13232     assert(!Input.get()->getType()->isDependentType() &&
13233                    "the co_await expression must be non-dependant before "
13234                    "building operator co_await");
13235     return Input;
13236   }
13237   if (resultType.isNull() || Input.isInvalid())
13238     return ExprError();
13239 
13240   // Check for array bounds violations in the operand of the UnaryOperator,
13241   // except for the '*' and '&' operators that have to be handled specially
13242   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13243   // that are explicitly defined as valid by the standard).
13244   if (Opc != UO_AddrOf && Opc != UO_Deref)
13245     CheckArrayAccess(Input.get());
13246 
13247   auto *UO = new (Context)
13248       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13249 
13250   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13251       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13252     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13253 
13254   // Convert the result back to a half vector.
13255   if (ConvertHalfVec)
13256     return convertVector(UO, Context.HalfTy, *this);
13257   return UO;
13258 }
13259 
13260 /// Determine whether the given expression is a qualified member
13261 /// access expression, of a form that could be turned into a pointer to member
13262 /// with the address-of operator.
13263 bool Sema::isQualifiedMemberAccess(Expr *E) {
13264   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13265     if (!DRE->getQualifier())
13266       return false;
13267 
13268     ValueDecl *VD = DRE->getDecl();
13269     if (!VD->isCXXClassMember())
13270       return false;
13271 
13272     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13273       return true;
13274     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13275       return Method->isInstance();
13276 
13277     return false;
13278   }
13279 
13280   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13281     if (!ULE->getQualifier())
13282       return false;
13283 
13284     for (NamedDecl *D : ULE->decls()) {
13285       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13286         if (Method->isInstance())
13287           return true;
13288       } else {
13289         // Overload set does not contain methods.
13290         break;
13291       }
13292     }
13293 
13294     return false;
13295   }
13296 
13297   return false;
13298 }
13299 
13300 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13301                               UnaryOperatorKind Opc, Expr *Input) {
13302   // First things first: handle placeholders so that the
13303   // overloaded-operator check considers the right type.
13304   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13305     // Increment and decrement of pseudo-object references.
13306     if (pty->getKind() == BuiltinType::PseudoObject &&
13307         UnaryOperator::isIncrementDecrementOp(Opc))
13308       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13309 
13310     // extension is always a builtin operator.
13311     if (Opc == UO_Extension)
13312       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13313 
13314     // & gets special logic for several kinds of placeholder.
13315     // The builtin code knows what to do.
13316     if (Opc == UO_AddrOf &&
13317         (pty->getKind() == BuiltinType::Overload ||
13318          pty->getKind() == BuiltinType::UnknownAny ||
13319          pty->getKind() == BuiltinType::BoundMember))
13320       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13321 
13322     // Anything else needs to be handled now.
13323     ExprResult Result = CheckPlaceholderExpr(Input);
13324     if (Result.isInvalid()) return ExprError();
13325     Input = Result.get();
13326   }
13327 
13328   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13329       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13330       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13331     // Find all of the overloaded operators visible from this
13332     // point. We perform both an operator-name lookup from the local
13333     // scope and an argument-dependent lookup based on the types of
13334     // the arguments.
13335     UnresolvedSet<16> Functions;
13336     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13337     if (S && OverOp != OO_None)
13338       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13339                                    Functions);
13340 
13341     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13342   }
13343 
13344   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13345 }
13346 
13347 // Unary Operators.  'Tok' is the token for the operator.
13348 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13349                               tok::TokenKind Op, Expr *Input) {
13350   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13351 }
13352 
13353 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13354 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13355                                 LabelDecl *TheDecl) {
13356   TheDecl->markUsed(Context);
13357   // Create the AST node.  The address of a label always has type 'void*'.
13358   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13359                                      Context.getPointerType(Context.VoidTy));
13360 }
13361 
13362 void Sema::ActOnStartStmtExpr() {
13363   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13364 }
13365 
13366 void Sema::ActOnStmtExprError() {
13367   // Note that function is also called by TreeTransform when leaving a
13368   // StmtExpr scope without rebuilding anything.
13369 
13370   DiscardCleanupsInEvaluationContext();
13371   PopExpressionEvaluationContext();
13372 }
13373 
13374 ExprResult
13375 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13376                     SourceLocation RPLoc) { // "({..})"
13377   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13378   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13379 
13380   if (hasAnyUnrecoverableErrorsInThisFunction())
13381     DiscardCleanupsInEvaluationContext();
13382   assert(!Cleanup.exprNeedsCleanups() &&
13383          "cleanups within StmtExpr not correctly bound!");
13384   PopExpressionEvaluationContext();
13385 
13386   // FIXME: there are a variety of strange constraints to enforce here, for
13387   // example, it is not possible to goto into a stmt expression apparently.
13388   // More semantic analysis is needed.
13389 
13390   // If there are sub-stmts in the compound stmt, take the type of the last one
13391   // as the type of the stmtexpr.
13392   QualType Ty = Context.VoidTy;
13393   bool StmtExprMayBindToTemp = false;
13394   if (!Compound->body_empty()) {
13395     if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
13396       if (const Expr *Value = LastStmt->getExprStmt()) {
13397         StmtExprMayBindToTemp = true;
13398         Ty = Value->getType();
13399       }
13400     }
13401   }
13402 
13403   // FIXME: Check that expression type is complete/non-abstract; statement
13404   // expressions are not lvalues.
13405   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13406   if (StmtExprMayBindToTemp)
13407     return MaybeBindToTemporary(ResStmtExpr);
13408   return ResStmtExpr;
13409 }
13410 
13411 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13412   if (ER.isInvalid())
13413     return ExprError();
13414 
13415   // Do function/array conversion on the last expression, but not
13416   // lvalue-to-rvalue.  However, initialize an unqualified type.
13417   ER = DefaultFunctionArrayConversion(ER.get());
13418   if (ER.isInvalid())
13419     return ExprError();
13420   Expr *E = ER.get();
13421 
13422   if (E->isTypeDependent())
13423     return E;
13424 
13425   // In ARC, if the final expression ends in a consume, splice
13426   // the consume out and bind it later.  In the alternate case
13427   // (when dealing with a retainable type), the result
13428   // initialization will create a produce.  In both cases the
13429   // result will be +1, and we'll need to balance that out with
13430   // a bind.
13431   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13432   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13433     return Cast->getSubExpr();
13434 
13435   // FIXME: Provide a better location for the initialization.
13436   return PerformCopyInitialization(
13437       InitializedEntity::InitializeStmtExprResult(
13438           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13439       SourceLocation(), E);
13440 }
13441 
13442 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13443                                       TypeSourceInfo *TInfo,
13444                                       ArrayRef<OffsetOfComponent> Components,
13445                                       SourceLocation RParenLoc) {
13446   QualType ArgTy = TInfo->getType();
13447   bool Dependent = ArgTy->isDependentType();
13448   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13449 
13450   // We must have at least one component that refers to the type, and the first
13451   // one is known to be a field designator.  Verify that the ArgTy represents
13452   // a struct/union/class.
13453   if (!Dependent && !ArgTy->isRecordType())
13454     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13455                        << ArgTy << TypeRange);
13456 
13457   // Type must be complete per C99 7.17p3 because a declaring a variable
13458   // with an incomplete type would be ill-formed.
13459   if (!Dependent
13460       && RequireCompleteType(BuiltinLoc, ArgTy,
13461                              diag::err_offsetof_incomplete_type, TypeRange))
13462     return ExprError();
13463 
13464   bool DidWarnAboutNonPOD = false;
13465   QualType CurrentType = ArgTy;
13466   SmallVector<OffsetOfNode, 4> Comps;
13467   SmallVector<Expr*, 4> Exprs;
13468   for (const OffsetOfComponent &OC : Components) {
13469     if (OC.isBrackets) {
13470       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13471       if (!CurrentType->isDependentType()) {
13472         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13473         if(!AT)
13474           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13475                            << CurrentType);
13476         CurrentType = AT->getElementType();
13477       } else
13478         CurrentType = Context.DependentTy;
13479 
13480       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13481       if (IdxRval.isInvalid())
13482         return ExprError();
13483       Expr *Idx = IdxRval.get();
13484 
13485       // The expression must be an integral expression.
13486       // FIXME: An integral constant expression?
13487       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13488           !Idx->getType()->isIntegerType())
13489         return ExprError(
13490             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13491             << Idx->getSourceRange());
13492 
13493       // Record this array index.
13494       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13495       Exprs.push_back(Idx);
13496       continue;
13497     }
13498 
13499     // Offset of a field.
13500     if (CurrentType->isDependentType()) {
13501       // We have the offset of a field, but we can't look into the dependent
13502       // type. Just record the identifier of the field.
13503       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13504       CurrentType = Context.DependentTy;
13505       continue;
13506     }
13507 
13508     // We need to have a complete type to look into.
13509     if (RequireCompleteType(OC.LocStart, CurrentType,
13510                             diag::err_offsetof_incomplete_type))
13511       return ExprError();
13512 
13513     // Look for the designated field.
13514     const RecordType *RC = CurrentType->getAs<RecordType>();
13515     if (!RC)
13516       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13517                        << CurrentType);
13518     RecordDecl *RD = RC->getDecl();
13519 
13520     // C++ [lib.support.types]p5:
13521     //   The macro offsetof accepts a restricted set of type arguments in this
13522     //   International Standard. type shall be a POD structure or a POD union
13523     //   (clause 9).
13524     // C++11 [support.types]p4:
13525     //   If type is not a standard-layout class (Clause 9), the results are
13526     //   undefined.
13527     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13528       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13529       unsigned DiagID =
13530         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13531                             : diag::ext_offsetof_non_pod_type;
13532 
13533       if (!IsSafe && !DidWarnAboutNonPOD &&
13534           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13535                               PDiag(DiagID)
13536                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13537                               << CurrentType))
13538         DidWarnAboutNonPOD = true;
13539     }
13540 
13541     // Look for the field.
13542     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13543     LookupQualifiedName(R, RD);
13544     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13545     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13546     if (!MemberDecl) {
13547       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13548         MemberDecl = IndirectMemberDecl->getAnonField();
13549     }
13550 
13551     if (!MemberDecl)
13552       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13553                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13554                                                               OC.LocEnd));
13555 
13556     // C99 7.17p3:
13557     //   (If the specified member is a bit-field, the behavior is undefined.)
13558     //
13559     // We diagnose this as an error.
13560     if (MemberDecl->isBitField()) {
13561       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13562         << MemberDecl->getDeclName()
13563         << SourceRange(BuiltinLoc, RParenLoc);
13564       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13565       return ExprError();
13566     }
13567 
13568     RecordDecl *Parent = MemberDecl->getParent();
13569     if (IndirectMemberDecl)
13570       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13571 
13572     // If the member was found in a base class, introduce OffsetOfNodes for
13573     // the base class indirections.
13574     CXXBasePaths Paths;
13575     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13576                       Paths)) {
13577       if (Paths.getDetectedVirtual()) {
13578         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13579           << MemberDecl->getDeclName()
13580           << SourceRange(BuiltinLoc, RParenLoc);
13581         return ExprError();
13582       }
13583 
13584       CXXBasePath &Path = Paths.front();
13585       for (const CXXBasePathElement &B : Path)
13586         Comps.push_back(OffsetOfNode(B.Base));
13587     }
13588 
13589     if (IndirectMemberDecl) {
13590       for (auto *FI : IndirectMemberDecl->chain()) {
13591         assert(isa<FieldDecl>(FI));
13592         Comps.push_back(OffsetOfNode(OC.LocStart,
13593                                      cast<FieldDecl>(FI), OC.LocEnd));
13594       }
13595     } else
13596       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13597 
13598     CurrentType = MemberDecl->getType().getNonReferenceType();
13599   }
13600 
13601   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13602                               Comps, Exprs, RParenLoc);
13603 }
13604 
13605 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13606                                       SourceLocation BuiltinLoc,
13607                                       SourceLocation TypeLoc,
13608                                       ParsedType ParsedArgTy,
13609                                       ArrayRef<OffsetOfComponent> Components,
13610                                       SourceLocation RParenLoc) {
13611 
13612   TypeSourceInfo *ArgTInfo;
13613   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13614   if (ArgTy.isNull())
13615     return ExprError();
13616 
13617   if (!ArgTInfo)
13618     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13619 
13620   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13621 }
13622 
13623 
13624 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13625                                  Expr *CondExpr,
13626                                  Expr *LHSExpr, Expr *RHSExpr,
13627                                  SourceLocation RPLoc) {
13628   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13629 
13630   ExprValueKind VK = VK_RValue;
13631   ExprObjectKind OK = OK_Ordinary;
13632   QualType resType;
13633   bool ValueDependent = false;
13634   bool CondIsTrue = false;
13635   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13636     resType = Context.DependentTy;
13637     ValueDependent = true;
13638   } else {
13639     // The conditional expression is required to be a constant expression.
13640     llvm::APSInt condEval(32);
13641     ExprResult CondICE
13642       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13643           diag::err_typecheck_choose_expr_requires_constant, false);
13644     if (CondICE.isInvalid())
13645       return ExprError();
13646     CondExpr = CondICE.get();
13647     CondIsTrue = condEval.getZExtValue();
13648 
13649     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13650     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13651 
13652     resType = ActiveExpr->getType();
13653     ValueDependent = ActiveExpr->isValueDependent();
13654     VK = ActiveExpr->getValueKind();
13655     OK = ActiveExpr->getObjectKind();
13656   }
13657 
13658   return new (Context)
13659       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13660                  CondIsTrue, resType->isDependentType(), ValueDependent);
13661 }
13662 
13663 //===----------------------------------------------------------------------===//
13664 // Clang Extensions.
13665 //===----------------------------------------------------------------------===//
13666 
13667 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13668 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13669   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13670 
13671   if (LangOpts.CPlusPlus) {
13672     Decl *ManglingContextDecl;
13673     if (MangleNumberingContext *MCtx =
13674             getCurrentMangleNumberContext(Block->getDeclContext(),
13675                                           ManglingContextDecl)) {
13676       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13677       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13678     }
13679   }
13680 
13681   PushBlockScope(CurScope, Block);
13682   CurContext->addDecl(Block);
13683   if (CurScope)
13684     PushDeclContext(CurScope, Block);
13685   else
13686     CurContext = Block;
13687 
13688   getCurBlock()->HasImplicitReturnType = true;
13689 
13690   // Enter a new evaluation context to insulate the block from any
13691   // cleanups from the enclosing full-expression.
13692   PushExpressionEvaluationContext(
13693       ExpressionEvaluationContext::PotentiallyEvaluated);
13694 }
13695 
13696 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13697                                Scope *CurScope) {
13698   assert(ParamInfo.getIdentifier() == nullptr &&
13699          "block-id should have no identifier!");
13700   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13701   BlockScopeInfo *CurBlock = getCurBlock();
13702 
13703   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13704   QualType T = Sig->getType();
13705 
13706   // FIXME: We should allow unexpanded parameter packs here, but that would,
13707   // in turn, make the block expression contain unexpanded parameter packs.
13708   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13709     // Drop the parameters.
13710     FunctionProtoType::ExtProtoInfo EPI;
13711     EPI.HasTrailingReturn = false;
13712     EPI.TypeQuals.addConst();
13713     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13714     Sig = Context.getTrivialTypeSourceInfo(T);
13715   }
13716 
13717   // GetTypeForDeclarator always produces a function type for a block
13718   // literal signature.  Furthermore, it is always a FunctionProtoType
13719   // unless the function was written with a typedef.
13720   assert(T->isFunctionType() &&
13721          "GetTypeForDeclarator made a non-function block signature");
13722 
13723   // Look for an explicit signature in that function type.
13724   FunctionProtoTypeLoc ExplicitSignature;
13725 
13726   if ((ExplicitSignature = Sig->getTypeLoc()
13727                                .getAsAdjusted<FunctionProtoTypeLoc>())) {
13728 
13729     // Check whether that explicit signature was synthesized by
13730     // GetTypeForDeclarator.  If so, don't save that as part of the
13731     // written signature.
13732     if (ExplicitSignature.getLocalRangeBegin() ==
13733         ExplicitSignature.getLocalRangeEnd()) {
13734       // This would be much cheaper if we stored TypeLocs instead of
13735       // TypeSourceInfos.
13736       TypeLoc Result = ExplicitSignature.getReturnLoc();
13737       unsigned Size = Result.getFullDataSize();
13738       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13739       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13740 
13741       ExplicitSignature = FunctionProtoTypeLoc();
13742     }
13743   }
13744 
13745   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13746   CurBlock->FunctionType = T;
13747 
13748   const FunctionType *Fn = T->getAs<FunctionType>();
13749   QualType RetTy = Fn->getReturnType();
13750   bool isVariadic =
13751     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13752 
13753   CurBlock->TheDecl->setIsVariadic(isVariadic);
13754 
13755   // Context.DependentTy is used as a placeholder for a missing block
13756   // return type.  TODO:  what should we do with declarators like:
13757   //   ^ * { ... }
13758   // If the answer is "apply template argument deduction"....
13759   if (RetTy != Context.DependentTy) {
13760     CurBlock->ReturnType = RetTy;
13761     CurBlock->TheDecl->setBlockMissingReturnType(false);
13762     CurBlock->HasImplicitReturnType = false;
13763   }
13764 
13765   // Push block parameters from the declarator if we had them.
13766   SmallVector<ParmVarDecl*, 8> Params;
13767   if (ExplicitSignature) {
13768     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13769       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13770       if (Param->getIdentifier() == nullptr &&
13771           !Param->isImplicit() &&
13772           !Param->isInvalidDecl() &&
13773           !getLangOpts().CPlusPlus)
13774         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13775       Params.push_back(Param);
13776     }
13777 
13778   // Fake up parameter variables if we have a typedef, like
13779   //   ^ fntype { ... }
13780   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13781     for (const auto &I : Fn->param_types()) {
13782       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13783           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13784       Params.push_back(Param);
13785     }
13786   }
13787 
13788   // Set the parameters on the block decl.
13789   if (!Params.empty()) {
13790     CurBlock->TheDecl->setParams(Params);
13791     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13792                              /*CheckParameterNames=*/false);
13793   }
13794 
13795   // Finally we can process decl attributes.
13796   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13797 
13798   // Put the parameter variables in scope.
13799   for (auto AI : CurBlock->TheDecl->parameters()) {
13800     AI->setOwningFunction(CurBlock->TheDecl);
13801 
13802     // If this has an identifier, add it to the scope stack.
13803     if (AI->getIdentifier()) {
13804       CheckShadow(CurBlock->TheScope, AI);
13805 
13806       PushOnScopeChains(AI, CurBlock->TheScope);
13807     }
13808   }
13809 }
13810 
13811 /// ActOnBlockError - If there is an error parsing a block, this callback
13812 /// is invoked to pop the information about the block from the action impl.
13813 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13814   // Leave the expression-evaluation context.
13815   DiscardCleanupsInEvaluationContext();
13816   PopExpressionEvaluationContext();
13817 
13818   // Pop off CurBlock, handle nested blocks.
13819   PopDeclContext();
13820   PopFunctionScopeInfo();
13821 }
13822 
13823 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13824 /// literal was successfully completed.  ^(int x){...}
13825 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13826                                     Stmt *Body, Scope *CurScope) {
13827   // If blocks are disabled, emit an error.
13828   if (!LangOpts.Blocks)
13829     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13830 
13831   // Leave the expression-evaluation context.
13832   if (hasAnyUnrecoverableErrorsInThisFunction())
13833     DiscardCleanupsInEvaluationContext();
13834   assert(!Cleanup.exprNeedsCleanups() &&
13835          "cleanups within block not correctly bound!");
13836   PopExpressionEvaluationContext();
13837 
13838   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13839   BlockDecl *BD = BSI->TheDecl;
13840 
13841   if (BSI->HasImplicitReturnType)
13842     deduceClosureReturnType(*BSI);
13843 
13844   PopDeclContext();
13845 
13846   QualType RetTy = Context.VoidTy;
13847   if (!BSI->ReturnType.isNull())
13848     RetTy = BSI->ReturnType;
13849 
13850   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13851   QualType BlockTy;
13852 
13853   // Set the captured variables on the block.
13854   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13855   SmallVector<BlockDecl::Capture, 4> Captures;
13856   for (Capture &Cap : BSI->Captures) {
13857     if (Cap.isThisCapture())
13858       continue;
13859     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13860                               Cap.isNested(), Cap.getInitExpr());
13861     Captures.push_back(NewCap);
13862   }
13863   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13864 
13865   // If the user wrote a function type in some form, try to use that.
13866   if (!BSI->FunctionType.isNull()) {
13867     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13868 
13869     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13870     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13871 
13872     // Turn protoless block types into nullary block types.
13873     if (isa<FunctionNoProtoType>(FTy)) {
13874       FunctionProtoType::ExtProtoInfo EPI;
13875       EPI.ExtInfo = Ext;
13876       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13877 
13878     // Otherwise, if we don't need to change anything about the function type,
13879     // preserve its sugar structure.
13880     } else if (FTy->getReturnType() == RetTy &&
13881                (!NoReturn || FTy->getNoReturnAttr())) {
13882       BlockTy = BSI->FunctionType;
13883 
13884     // Otherwise, make the minimal modifications to the function type.
13885     } else {
13886       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13887       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13888       EPI.TypeQuals = Qualifiers();
13889       EPI.ExtInfo = Ext;
13890       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13891     }
13892 
13893   // If we don't have a function type, just build one from nothing.
13894   } else {
13895     FunctionProtoType::ExtProtoInfo EPI;
13896     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13897     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13898   }
13899 
13900   DiagnoseUnusedParameters(BD->parameters());
13901   BlockTy = Context.getBlockPointerType(BlockTy);
13902 
13903   // If needed, diagnose invalid gotos and switches in the block.
13904   if (getCurFunction()->NeedsScopeChecking() &&
13905       !PP.isCodeCompletionEnabled())
13906     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13907 
13908   BD->setBody(cast<CompoundStmt>(Body));
13909 
13910   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13911     DiagnoseUnguardedAvailabilityViolations(BD);
13912 
13913   // Try to apply the named return value optimization. We have to check again
13914   // if we can do this, though, because blocks keep return statements around
13915   // to deduce an implicit return type.
13916   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13917       !BD->isDependentContext())
13918     computeNRVO(Body, BSI);
13919 
13920   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13921   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13922   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13923 
13924   // If the block isn't obviously global, i.e. it captures anything at
13925   // all, then we need to do a few things in the surrounding context:
13926   if (Result->getBlockDecl()->hasCaptures()) {
13927     // First, this expression has a new cleanup object.
13928     ExprCleanupObjects.push_back(Result->getBlockDecl());
13929     Cleanup.setExprNeedsCleanups(true);
13930 
13931     // It also gets a branch-protected scope if any of the captured
13932     // variables needs destruction.
13933     for (const auto &CI : Result->getBlockDecl()->captures()) {
13934       const VarDecl *var = CI.getVariable();
13935       if (var->getType().isDestructedType() != QualType::DK_none) {
13936         setFunctionHasBranchProtectedScope();
13937         break;
13938       }
13939     }
13940   }
13941 
13942   if (getCurFunction())
13943     getCurFunction()->addBlock(BD);
13944 
13945   return Result;
13946 }
13947 
13948 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13949                             SourceLocation RPLoc) {
13950   TypeSourceInfo *TInfo;
13951   GetTypeFromParser(Ty, &TInfo);
13952   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13953 }
13954 
13955 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13956                                 Expr *E, TypeSourceInfo *TInfo,
13957                                 SourceLocation RPLoc) {
13958   Expr *OrigExpr = E;
13959   bool IsMS = false;
13960 
13961   // CUDA device code does not support varargs.
13962   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13963     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13964       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13965       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13966         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13967     }
13968   }
13969 
13970   // NVPTX does not support va_arg expression.
13971   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
13972       Context.getTargetInfo().getTriple().isNVPTX())
13973     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
13974 
13975   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13976   // as Microsoft ABI on an actual Microsoft platform, where
13977   // __builtin_ms_va_list and __builtin_va_list are the same.)
13978   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13979       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13980     QualType MSVaListType = Context.getBuiltinMSVaListType();
13981     if (Context.hasSameType(MSVaListType, E->getType())) {
13982       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13983         return ExprError();
13984       IsMS = true;
13985     }
13986   }
13987 
13988   // Get the va_list type
13989   QualType VaListType = Context.getBuiltinVaListType();
13990   if (!IsMS) {
13991     if (VaListType->isArrayType()) {
13992       // Deal with implicit array decay; for example, on x86-64,
13993       // va_list is an array, but it's supposed to decay to
13994       // a pointer for va_arg.
13995       VaListType = Context.getArrayDecayedType(VaListType);
13996       // Make sure the input expression also decays appropriately.
13997       ExprResult Result = UsualUnaryConversions(E);
13998       if (Result.isInvalid())
13999         return ExprError();
14000       E = Result.get();
14001     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14002       // If va_list is a record type and we are compiling in C++ mode,
14003       // check the argument using reference binding.
14004       InitializedEntity Entity = InitializedEntity::InitializeParameter(
14005           Context, Context.getLValueReferenceType(VaListType), false);
14006       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14007       if (Init.isInvalid())
14008         return ExprError();
14009       E = Init.getAs<Expr>();
14010     } else {
14011       // Otherwise, the va_list argument must be an l-value because
14012       // it is modified by va_arg.
14013       if (!E->isTypeDependent() &&
14014           CheckForModifiableLvalue(E, BuiltinLoc, *this))
14015         return ExprError();
14016     }
14017   }
14018 
14019   if (!IsMS && !E->isTypeDependent() &&
14020       !Context.hasSameType(VaListType, E->getType()))
14021     return ExprError(
14022         Diag(E->getBeginLoc(),
14023              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14024         << OrigExpr->getType() << E->getSourceRange());
14025 
14026   if (!TInfo->getType()->isDependentType()) {
14027     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14028                             diag::err_second_parameter_to_va_arg_incomplete,
14029                             TInfo->getTypeLoc()))
14030       return ExprError();
14031 
14032     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14033                                TInfo->getType(),
14034                                diag::err_second_parameter_to_va_arg_abstract,
14035                                TInfo->getTypeLoc()))
14036       return ExprError();
14037 
14038     if (!TInfo->getType().isPODType(Context)) {
14039       Diag(TInfo->getTypeLoc().getBeginLoc(),
14040            TInfo->getType()->isObjCLifetimeType()
14041              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14042              : diag::warn_second_parameter_to_va_arg_not_pod)
14043         << TInfo->getType()
14044         << TInfo->getTypeLoc().getSourceRange();
14045     }
14046 
14047     // Check for va_arg where arguments of the given type will be promoted
14048     // (i.e. this va_arg is guaranteed to have undefined behavior).
14049     QualType PromoteType;
14050     if (TInfo->getType()->isPromotableIntegerType()) {
14051       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14052       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14053         PromoteType = QualType();
14054     }
14055     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14056       PromoteType = Context.DoubleTy;
14057     if (!PromoteType.isNull())
14058       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14059                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14060                           << TInfo->getType()
14061                           << PromoteType
14062                           << TInfo->getTypeLoc().getSourceRange());
14063   }
14064 
14065   QualType T = TInfo->getType().getNonLValueExprType(Context);
14066   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14067 }
14068 
14069 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14070   // The type of __null will be int or long, depending on the size of
14071   // pointers on the target.
14072   QualType Ty;
14073   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14074   if (pw == Context.getTargetInfo().getIntWidth())
14075     Ty = Context.IntTy;
14076   else if (pw == Context.getTargetInfo().getLongWidth())
14077     Ty = Context.LongTy;
14078   else if (pw == Context.getTargetInfo().getLongLongWidth())
14079     Ty = Context.LongLongTy;
14080   else {
14081     llvm_unreachable("I don't know size of pointer!");
14082   }
14083 
14084   return new (Context) GNUNullExpr(Ty, TokenLoc);
14085 }
14086 
14087 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14088                                     SourceLocation BuiltinLoc,
14089                                     SourceLocation RPLoc) {
14090   return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14091 }
14092 
14093 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14094                                     SourceLocation BuiltinLoc,
14095                                     SourceLocation RPLoc,
14096                                     DeclContext *ParentContext) {
14097   return new (Context)
14098       SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14099 }
14100 
14101 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14102                                               bool Diagnose) {
14103   if (!getLangOpts().ObjC)
14104     return false;
14105 
14106   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14107   if (!PT)
14108     return false;
14109 
14110   if (!PT->isObjCIdType()) {
14111     // Check if the destination is the 'NSString' interface.
14112     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14113     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14114       return false;
14115   }
14116 
14117   // Ignore any parens, implicit casts (should only be
14118   // array-to-pointer decays), and not-so-opaque values.  The last is
14119   // important for making this trigger for property assignments.
14120   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14121   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14122     if (OV->getSourceExpr())
14123       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14124 
14125   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14126   if (!SL || !SL->isAscii())
14127     return false;
14128   if (Diagnose) {
14129     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14130         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14131     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14132   }
14133   return true;
14134 }
14135 
14136 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14137                                               const Expr *SrcExpr) {
14138   if (!DstType->isFunctionPointerType() ||
14139       !SrcExpr->getType()->isFunctionType())
14140     return false;
14141 
14142   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14143   if (!DRE)
14144     return false;
14145 
14146   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14147   if (!FD)
14148     return false;
14149 
14150   return !S.checkAddressOfFunctionIsAvailable(FD,
14151                                               /*Complain=*/true,
14152                                               SrcExpr->getBeginLoc());
14153 }
14154 
14155 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14156                                     SourceLocation Loc,
14157                                     QualType DstType, QualType SrcType,
14158                                     Expr *SrcExpr, AssignmentAction Action,
14159                                     bool *Complained) {
14160   if (Complained)
14161     *Complained = false;
14162 
14163   // Decode the result (notice that AST's are still created for extensions).
14164   bool CheckInferredResultType = false;
14165   bool isInvalid = false;
14166   unsigned DiagKind = 0;
14167   FixItHint Hint;
14168   ConversionFixItGenerator ConvHints;
14169   bool MayHaveConvFixit = false;
14170   bool MayHaveFunctionDiff = false;
14171   const ObjCInterfaceDecl *IFace = nullptr;
14172   const ObjCProtocolDecl *PDecl = nullptr;
14173 
14174   switch (ConvTy) {
14175   case Compatible:
14176       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14177       return false;
14178 
14179   case PointerToInt:
14180     DiagKind = diag::ext_typecheck_convert_pointer_int;
14181     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14182     MayHaveConvFixit = true;
14183     break;
14184   case IntToPointer:
14185     DiagKind = diag::ext_typecheck_convert_int_pointer;
14186     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14187     MayHaveConvFixit = true;
14188     break;
14189   case IncompatiblePointer:
14190     if (Action == AA_Passing_CFAudited)
14191       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14192     else if (SrcType->isFunctionPointerType() &&
14193              DstType->isFunctionPointerType())
14194       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14195     else
14196       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14197 
14198     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14199       SrcType->isObjCObjectPointerType();
14200     if (Hint.isNull() && !CheckInferredResultType) {
14201       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14202     }
14203     else if (CheckInferredResultType) {
14204       SrcType = SrcType.getUnqualifiedType();
14205       DstType = DstType.getUnqualifiedType();
14206     }
14207     MayHaveConvFixit = true;
14208     break;
14209   case IncompatiblePointerSign:
14210     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14211     break;
14212   case FunctionVoidPointer:
14213     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14214     break;
14215   case IncompatiblePointerDiscardsQualifiers: {
14216     // Perform array-to-pointer decay if necessary.
14217     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14218 
14219     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14220     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14221     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14222       DiagKind = diag::err_typecheck_incompatible_address_space;
14223       break;
14224 
14225     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14226       DiagKind = diag::err_typecheck_incompatible_ownership;
14227       break;
14228     }
14229 
14230     llvm_unreachable("unknown error case for discarding qualifiers!");
14231     // fallthrough
14232   }
14233   case CompatiblePointerDiscardsQualifiers:
14234     // If the qualifiers lost were because we were applying the
14235     // (deprecated) C++ conversion from a string literal to a char*
14236     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14237     // Ideally, this check would be performed in
14238     // checkPointerTypesForAssignment. However, that would require a
14239     // bit of refactoring (so that the second argument is an
14240     // expression, rather than a type), which should be done as part
14241     // of a larger effort to fix checkPointerTypesForAssignment for
14242     // C++ semantics.
14243     if (getLangOpts().CPlusPlus &&
14244         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14245       return false;
14246     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14247     break;
14248   case IncompatibleNestedPointerQualifiers:
14249     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14250     break;
14251   case IncompatibleNestedPointerAddressSpaceMismatch:
14252     DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14253     break;
14254   case IntToBlockPointer:
14255     DiagKind = diag::err_int_to_block_pointer;
14256     break;
14257   case IncompatibleBlockPointer:
14258     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14259     break;
14260   case IncompatibleObjCQualifiedId: {
14261     if (SrcType->isObjCQualifiedIdType()) {
14262       const ObjCObjectPointerType *srcOPT =
14263                 SrcType->getAs<ObjCObjectPointerType>();
14264       for (auto *srcProto : srcOPT->quals()) {
14265         PDecl = srcProto;
14266         break;
14267       }
14268       if (const ObjCInterfaceType *IFaceT =
14269             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14270         IFace = IFaceT->getDecl();
14271     }
14272     else if (DstType->isObjCQualifiedIdType()) {
14273       const ObjCObjectPointerType *dstOPT =
14274         DstType->getAs<ObjCObjectPointerType>();
14275       for (auto *dstProto : dstOPT->quals()) {
14276         PDecl = dstProto;
14277         break;
14278       }
14279       if (const ObjCInterfaceType *IFaceT =
14280             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14281         IFace = IFaceT->getDecl();
14282     }
14283     DiagKind = diag::warn_incompatible_qualified_id;
14284     break;
14285   }
14286   case IncompatibleVectors:
14287     DiagKind = diag::warn_incompatible_vectors;
14288     break;
14289   case IncompatibleObjCWeakRef:
14290     DiagKind = diag::err_arc_weak_unavailable_assign;
14291     break;
14292   case Incompatible:
14293     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14294       if (Complained)
14295         *Complained = true;
14296       return true;
14297     }
14298 
14299     DiagKind = diag::err_typecheck_convert_incompatible;
14300     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14301     MayHaveConvFixit = true;
14302     isInvalid = true;
14303     MayHaveFunctionDiff = true;
14304     break;
14305   }
14306 
14307   QualType FirstType, SecondType;
14308   switch (Action) {
14309   case AA_Assigning:
14310   case AA_Initializing:
14311     // The destination type comes first.
14312     FirstType = DstType;
14313     SecondType = SrcType;
14314     break;
14315 
14316   case AA_Returning:
14317   case AA_Passing:
14318   case AA_Passing_CFAudited:
14319   case AA_Converting:
14320   case AA_Sending:
14321   case AA_Casting:
14322     // The source type comes first.
14323     FirstType = SrcType;
14324     SecondType = DstType;
14325     break;
14326   }
14327 
14328   PartialDiagnostic FDiag = PDiag(DiagKind);
14329   if (Action == AA_Passing_CFAudited)
14330     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14331   else
14332     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14333 
14334   // If we can fix the conversion, suggest the FixIts.
14335   assert(ConvHints.isNull() || Hint.isNull());
14336   if (!ConvHints.isNull()) {
14337     for (FixItHint &H : ConvHints.Hints)
14338       FDiag << H;
14339   } else {
14340     FDiag << Hint;
14341   }
14342   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14343 
14344   if (MayHaveFunctionDiff)
14345     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14346 
14347   Diag(Loc, FDiag);
14348   if (DiagKind == diag::warn_incompatible_qualified_id &&
14349       PDecl && IFace && !IFace->hasDefinition())
14350       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14351         << IFace << PDecl;
14352 
14353   if (SecondType == Context.OverloadTy)
14354     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14355                               FirstType, /*TakingAddress=*/true);
14356 
14357   if (CheckInferredResultType)
14358     EmitRelatedResultTypeNote(SrcExpr);
14359 
14360   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14361     EmitRelatedResultTypeNoteForReturn(DstType);
14362 
14363   if (Complained)
14364     *Complained = true;
14365   return isInvalid;
14366 }
14367 
14368 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14369                                                  llvm::APSInt *Result) {
14370   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14371   public:
14372     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14373       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14374     }
14375   } Diagnoser;
14376 
14377   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14378 }
14379 
14380 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14381                                                  llvm::APSInt *Result,
14382                                                  unsigned DiagID,
14383                                                  bool AllowFold) {
14384   class IDDiagnoser : public VerifyICEDiagnoser {
14385     unsigned DiagID;
14386 
14387   public:
14388     IDDiagnoser(unsigned DiagID)
14389       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14390 
14391     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14392       S.Diag(Loc, DiagID) << SR;
14393     }
14394   } Diagnoser(DiagID);
14395 
14396   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14397 }
14398 
14399 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14400                                             SourceRange SR) {
14401   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14402 }
14403 
14404 ExprResult
14405 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14406                                       VerifyICEDiagnoser &Diagnoser,
14407                                       bool AllowFold) {
14408   SourceLocation DiagLoc = E->getBeginLoc();
14409 
14410   if (getLangOpts().CPlusPlus11) {
14411     // C++11 [expr.const]p5:
14412     //   If an expression of literal class type is used in a context where an
14413     //   integral constant expression is required, then that class type shall
14414     //   have a single non-explicit conversion function to an integral or
14415     //   unscoped enumeration type
14416     ExprResult Converted;
14417     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14418     public:
14419       CXX11ConvertDiagnoser(bool Silent)
14420           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14421                                 Silent, true) {}
14422 
14423       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14424                                            QualType T) override {
14425         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14426       }
14427 
14428       SemaDiagnosticBuilder diagnoseIncomplete(
14429           Sema &S, SourceLocation Loc, QualType T) override {
14430         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14431       }
14432 
14433       SemaDiagnosticBuilder diagnoseExplicitConv(
14434           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14435         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14436       }
14437 
14438       SemaDiagnosticBuilder noteExplicitConv(
14439           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14440         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14441                  << ConvTy->isEnumeralType() << ConvTy;
14442       }
14443 
14444       SemaDiagnosticBuilder diagnoseAmbiguous(
14445           Sema &S, SourceLocation Loc, QualType T) override {
14446         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14447       }
14448 
14449       SemaDiagnosticBuilder noteAmbiguous(
14450           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14451         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14452                  << ConvTy->isEnumeralType() << ConvTy;
14453       }
14454 
14455       SemaDiagnosticBuilder diagnoseConversion(
14456           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14457         llvm_unreachable("conversion functions are permitted");
14458       }
14459     } ConvertDiagnoser(Diagnoser.Suppress);
14460 
14461     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14462                                                     ConvertDiagnoser);
14463     if (Converted.isInvalid())
14464       return Converted;
14465     E = Converted.get();
14466     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14467       return ExprError();
14468   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14469     // An ICE must be of integral or unscoped enumeration type.
14470     if (!Diagnoser.Suppress)
14471       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14472     return ExprError();
14473   }
14474 
14475   if (!isa<ConstantExpr>(E))
14476     E = ConstantExpr::Create(Context, E);
14477 
14478   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14479   // in the non-ICE case.
14480   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14481     if (Result)
14482       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14483     return E;
14484   }
14485 
14486   Expr::EvalResult EvalResult;
14487   SmallVector<PartialDiagnosticAt, 8> Notes;
14488   EvalResult.Diag = &Notes;
14489 
14490   // Try to evaluate the expression, and produce diagnostics explaining why it's
14491   // not a constant expression as a side-effect.
14492   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14493                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14494 
14495   // In C++11, we can rely on diagnostics being produced for any expression
14496   // which is not a constant expression. If no diagnostics were produced, then
14497   // this is a constant expression.
14498   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14499     if (Result)
14500       *Result = EvalResult.Val.getInt();
14501     return E;
14502   }
14503 
14504   // If our only note is the usual "invalid subexpression" note, just point
14505   // the caret at its location rather than producing an essentially
14506   // redundant note.
14507   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14508         diag::note_invalid_subexpr_in_const_expr) {
14509     DiagLoc = Notes[0].first;
14510     Notes.clear();
14511   }
14512 
14513   if (!Folded || !AllowFold) {
14514     if (!Diagnoser.Suppress) {
14515       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14516       for (const PartialDiagnosticAt &Note : Notes)
14517         Diag(Note.first, Note.second);
14518     }
14519 
14520     return ExprError();
14521   }
14522 
14523   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14524   for (const PartialDiagnosticAt &Note : Notes)
14525     Diag(Note.first, Note.second);
14526 
14527   if (Result)
14528     *Result = EvalResult.Val.getInt();
14529   return E;
14530 }
14531 
14532 namespace {
14533   // Handle the case where we conclude a expression which we speculatively
14534   // considered to be unevaluated is actually evaluated.
14535   class TransformToPE : public TreeTransform<TransformToPE> {
14536     typedef TreeTransform<TransformToPE> BaseTransform;
14537 
14538   public:
14539     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14540 
14541     // Make sure we redo semantic analysis
14542     bool AlwaysRebuild() { return true; }
14543 
14544     // We need to special-case DeclRefExprs referring to FieldDecls which
14545     // are not part of a member pointer formation; normal TreeTransforming
14546     // doesn't catch this case because of the way we represent them in the AST.
14547     // FIXME: This is a bit ugly; is it really the best way to handle this
14548     // case?
14549     //
14550     // Error on DeclRefExprs referring to FieldDecls.
14551     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14552       if (isa<FieldDecl>(E->getDecl()) &&
14553           !SemaRef.isUnevaluatedContext())
14554         return SemaRef.Diag(E->getLocation(),
14555                             diag::err_invalid_non_static_member_use)
14556             << E->getDecl() << E->getSourceRange();
14557 
14558       return BaseTransform::TransformDeclRefExpr(E);
14559     }
14560 
14561     // Exception: filter out member pointer formation
14562     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14563       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14564         return E;
14565 
14566       return BaseTransform::TransformUnaryOperator(E);
14567     }
14568 
14569     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14570       // Lambdas never need to be transformed.
14571       return E;
14572     }
14573   };
14574 }
14575 
14576 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14577   assert(isUnevaluatedContext() &&
14578          "Should only transform unevaluated expressions");
14579   ExprEvalContexts.back().Context =
14580       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14581   if (isUnevaluatedContext())
14582     return E;
14583   return TransformToPE(*this).TransformExpr(E);
14584 }
14585 
14586 void
14587 Sema::PushExpressionEvaluationContext(
14588     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14589     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14590   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14591                                 LambdaContextDecl, ExprContext);
14592   Cleanup.reset();
14593   if (!MaybeODRUseExprs.empty())
14594     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14595 }
14596 
14597 void
14598 Sema::PushExpressionEvaluationContext(
14599     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14600     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14601   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14602   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14603 }
14604 
14605 namespace {
14606 
14607 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14608   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14609   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14610     if (E->getOpcode() == UO_Deref)
14611       return CheckPossibleDeref(S, E->getSubExpr());
14612   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14613     return CheckPossibleDeref(S, E->getBase());
14614   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14615     return CheckPossibleDeref(S, E->getBase());
14616   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14617     QualType Inner;
14618     QualType Ty = E->getType();
14619     if (const auto *Ptr = Ty->getAs<PointerType>())
14620       Inner = Ptr->getPointeeType();
14621     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14622       Inner = Arr->getElementType();
14623     else
14624       return nullptr;
14625 
14626     if (Inner->hasAttr(attr::NoDeref))
14627       return E;
14628   }
14629   return nullptr;
14630 }
14631 
14632 } // namespace
14633 
14634 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14635   for (const Expr *E : Rec.PossibleDerefs) {
14636     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14637     if (DeclRef) {
14638       const ValueDecl *Decl = DeclRef->getDecl();
14639       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14640           << Decl->getName() << E->getSourceRange();
14641       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14642     } else {
14643       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14644           << E->getSourceRange();
14645     }
14646   }
14647   Rec.PossibleDerefs.clear();
14648 }
14649 
14650 void Sema::PopExpressionEvaluationContext() {
14651   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14652   unsigned NumTypos = Rec.NumTypos;
14653 
14654   if (!Rec.Lambdas.empty()) {
14655     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14656     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14657         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14658       unsigned D;
14659       if (Rec.isUnevaluated()) {
14660         // C++11 [expr.prim.lambda]p2:
14661         //   A lambda-expression shall not appear in an unevaluated operand
14662         //   (Clause 5).
14663         D = diag::err_lambda_unevaluated_operand;
14664       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14665         // C++1y [expr.const]p2:
14666         //   A conditional-expression e is a core constant expression unless the
14667         //   evaluation of e, following the rules of the abstract machine, would
14668         //   evaluate [...] a lambda-expression.
14669         D = diag::err_lambda_in_constant_expression;
14670       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14671         // C++17 [expr.prim.lamda]p2:
14672         // A lambda-expression shall not appear [...] in a template-argument.
14673         D = diag::err_lambda_in_invalid_context;
14674       } else
14675         llvm_unreachable("Couldn't infer lambda error message.");
14676 
14677       for (const auto *L : Rec.Lambdas)
14678         Diag(L->getBeginLoc(), D);
14679     } else {
14680       // Mark the capture expressions odr-used. This was deferred
14681       // during lambda expression creation.
14682       for (auto *Lambda : Rec.Lambdas) {
14683         for (auto *C : Lambda->capture_inits())
14684           MarkDeclarationsReferencedInExpr(C);
14685       }
14686     }
14687   }
14688 
14689   WarnOnPendingNoDerefs(Rec);
14690 
14691   // When are coming out of an unevaluated context, clear out any
14692   // temporaries that we may have created as part of the evaluation of
14693   // the expression in that context: they aren't relevant because they
14694   // will never be constructed.
14695   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14696     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14697                              ExprCleanupObjects.end());
14698     Cleanup = Rec.ParentCleanup;
14699     CleanupVarDeclMarking();
14700     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14701   // Otherwise, merge the contexts together.
14702   } else {
14703     Cleanup.mergeFrom(Rec.ParentCleanup);
14704     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14705                             Rec.SavedMaybeODRUseExprs.end());
14706   }
14707 
14708   // Pop the current expression evaluation context off the stack.
14709   ExprEvalContexts.pop_back();
14710 
14711   // The global expression evaluation context record is never popped.
14712   ExprEvalContexts.back().NumTypos += NumTypos;
14713 }
14714 
14715 void Sema::DiscardCleanupsInEvaluationContext() {
14716   ExprCleanupObjects.erase(
14717          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14718          ExprCleanupObjects.end());
14719   Cleanup.reset();
14720   MaybeODRUseExprs.clear();
14721 }
14722 
14723 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14724   ExprResult Result = CheckPlaceholderExpr(E);
14725   if (Result.isInvalid())
14726     return ExprError();
14727   E = Result.get();
14728   if (!E->getType()->isVariablyModifiedType())
14729     return E;
14730   return TransformToPotentiallyEvaluated(E);
14731 }
14732 
14733 /// Are we within a context in which some evaluation could be performed (be it
14734 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14735 /// captured by C++'s idea of an "unevaluated context".
14736 static bool isEvaluatableContext(Sema &SemaRef) {
14737   switch (SemaRef.ExprEvalContexts.back().Context) {
14738     case Sema::ExpressionEvaluationContext::Unevaluated:
14739     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14740       // Expressions in this context are never evaluated.
14741       return false;
14742 
14743     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14744     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14745     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14746     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14747       // Expressions in this context could be evaluated.
14748       return true;
14749 
14750     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14751       // Referenced declarations will only be used if the construct in the
14752       // containing expression is used, at which point we'll be given another
14753       // turn to mark them.
14754       return false;
14755   }
14756   llvm_unreachable("Invalid context");
14757 }
14758 
14759 /// Are we within a context in which references to resolved functions or to
14760 /// variables result in odr-use?
14761 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14762   // An expression in a template is not really an expression until it's been
14763   // instantiated, so it doesn't trigger odr-use.
14764   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14765     return false;
14766 
14767   switch (SemaRef.ExprEvalContexts.back().Context) {
14768     case Sema::ExpressionEvaluationContext::Unevaluated:
14769     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14770     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14771     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14772       return false;
14773 
14774     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14775     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14776       return true;
14777 
14778     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14779       return false;
14780   }
14781   llvm_unreachable("Invalid context");
14782 }
14783 
14784 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14785   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14786   return Func->isConstexpr() &&
14787          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14788 }
14789 
14790 /// Mark a function referenced, and check whether it is odr-used
14791 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14792 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14793                                   bool MightBeOdrUse) {
14794   assert(Func && "No function?");
14795 
14796   Func->setReferenced();
14797 
14798   // C++11 [basic.def.odr]p3:
14799   //   A function whose name appears as a potentially-evaluated expression is
14800   //   odr-used if it is the unique lookup result or the selected member of a
14801   //   set of overloaded functions [...].
14802   //
14803   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14804   // can just check that here.
14805   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14806 
14807   // Determine whether we require a function definition to exist, per
14808   // C++11 [temp.inst]p3:
14809   //   Unless a function template specialization has been explicitly
14810   //   instantiated or explicitly specialized, the function template
14811   //   specialization is implicitly instantiated when the specialization is
14812   //   referenced in a context that requires a function definition to exist.
14813   //
14814   // That is either when this is an odr-use, or when a usage of a constexpr
14815   // function occurs within an evaluatable context.
14816   bool NeedDefinition =
14817       OdrUse || (isEvaluatableContext(*this) &&
14818                  isImplicitlyDefinableConstexprFunction(Func));
14819 
14820   // C++14 [temp.expl.spec]p6:
14821   //   If a template [...] is explicitly specialized then that specialization
14822   //   shall be declared before the first use of that specialization that would
14823   //   cause an implicit instantiation to take place, in every translation unit
14824   //   in which such a use occurs
14825   if (NeedDefinition &&
14826       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14827        Func->getMemberSpecializationInfo()))
14828     checkSpecializationVisibility(Loc, Func);
14829 
14830   // C++14 [except.spec]p17:
14831   //   An exception-specification is considered to be needed when:
14832   //   - the function is odr-used or, if it appears in an unevaluated operand,
14833   //     would be odr-used if the expression were potentially-evaluated;
14834   //
14835   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14836   // function is a pure virtual function we're calling, and in that case the
14837   // function was selected by overload resolution and we need to resolve its
14838   // exception specification for a different reason.
14839   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14840   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14841     ResolveExceptionSpec(Loc, FPT);
14842 
14843   if (getLangOpts().CUDA)
14844     CheckCUDACall(Loc, Func);
14845 
14846   // If we don't need to mark the function as used, and we don't need to
14847   // try to provide a definition, there's nothing more to do.
14848   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14849       (!NeedDefinition || Func->getBody()))
14850     return;
14851 
14852   // Note that this declaration has been used.
14853   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14854     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14855     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14856       if (Constructor->isDefaultConstructor()) {
14857         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14858           return;
14859         DefineImplicitDefaultConstructor(Loc, Constructor);
14860       } else if (Constructor->isCopyConstructor()) {
14861         DefineImplicitCopyConstructor(Loc, Constructor);
14862       } else if (Constructor->isMoveConstructor()) {
14863         DefineImplicitMoveConstructor(Loc, Constructor);
14864       }
14865     } else if (Constructor->getInheritedConstructor()) {
14866       DefineInheritingConstructor(Loc, Constructor);
14867     }
14868   } else if (CXXDestructorDecl *Destructor =
14869                  dyn_cast<CXXDestructorDecl>(Func)) {
14870     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14871     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14872       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14873         return;
14874       DefineImplicitDestructor(Loc, Destructor);
14875     }
14876     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14877       MarkVTableUsed(Loc, Destructor->getParent());
14878   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14879     if (MethodDecl->isOverloadedOperator() &&
14880         MethodDecl->getOverloadedOperator() == OO_Equal) {
14881       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14882       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14883         if (MethodDecl->isCopyAssignmentOperator())
14884           DefineImplicitCopyAssignment(Loc, MethodDecl);
14885         else if (MethodDecl->isMoveAssignmentOperator())
14886           DefineImplicitMoveAssignment(Loc, MethodDecl);
14887       }
14888     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14889                MethodDecl->getParent()->isLambda()) {
14890       CXXConversionDecl *Conversion =
14891           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14892       if (Conversion->isLambdaToBlockPointerConversion())
14893         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14894       else
14895         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14896     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14897       MarkVTableUsed(Loc, MethodDecl->getParent());
14898   }
14899 
14900   // Recursive functions should be marked when used from another function.
14901   // FIXME: Is this really right?
14902   if (CurContext == Func) return;
14903 
14904   // Implicit instantiation of function templates and member functions of
14905   // class templates.
14906   if (Func->isImplicitlyInstantiable()) {
14907     TemplateSpecializationKind TSK =
14908         Func->getTemplateSpecializationKindForInstantiation();
14909     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14910     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14911     if (FirstInstantiation) {
14912       PointOfInstantiation = Loc;
14913       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14914     } else if (TSK != TSK_ImplicitInstantiation) {
14915       // Use the point of use as the point of instantiation, instead of the
14916       // point of explicit instantiation (which we track as the actual point of
14917       // instantiation). This gives better backtraces in diagnostics.
14918       PointOfInstantiation = Loc;
14919     }
14920 
14921     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14922         Func->isConstexpr()) {
14923       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14924           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14925           CodeSynthesisContexts.size())
14926         PendingLocalImplicitInstantiations.push_back(
14927             std::make_pair(Func, PointOfInstantiation));
14928       else if (Func->isConstexpr())
14929         // Do not defer instantiations of constexpr functions, to avoid the
14930         // expression evaluator needing to call back into Sema if it sees a
14931         // call to such a function.
14932         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14933       else {
14934         Func->setInstantiationIsPending(true);
14935         PendingInstantiations.push_back(std::make_pair(Func,
14936                                                        PointOfInstantiation));
14937         // Notify the consumer that a function was implicitly instantiated.
14938         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14939       }
14940     }
14941   } else {
14942     // Walk redefinitions, as some of them may be instantiable.
14943     for (auto i : Func->redecls()) {
14944       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14945         MarkFunctionReferenced(Loc, i, OdrUse);
14946     }
14947   }
14948 
14949   if (!OdrUse) return;
14950 
14951   // Keep track of used but undefined functions.
14952   if (!Func->isDefined()) {
14953     if (mightHaveNonExternalLinkage(Func))
14954       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14955     else if (Func->getMostRecentDecl()->isInlined() &&
14956              !LangOpts.GNUInline &&
14957              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14958       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14959     else if (isExternalWithNoLinkageType(Func))
14960       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14961   }
14962 
14963   Func->markUsed(Context);
14964 
14965   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
14966     checkOpenMPDeviceFunction(Loc, Func);
14967 }
14968 
14969 static void
14970 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14971                                    ValueDecl *var, DeclContext *DC) {
14972   DeclContext *VarDC = var->getDeclContext();
14973 
14974   //  If the parameter still belongs to the translation unit, then
14975   //  we're actually just using one parameter in the declaration of
14976   //  the next.
14977   if (isa<ParmVarDecl>(var) &&
14978       isa<TranslationUnitDecl>(VarDC))
14979     return;
14980 
14981   // For C code, don't diagnose about capture if we're not actually in code
14982   // right now; it's impossible to write a non-constant expression outside of
14983   // function context, so we'll get other (more useful) diagnostics later.
14984   //
14985   // For C++, things get a bit more nasty... it would be nice to suppress this
14986   // diagnostic for certain cases like using a local variable in an array bound
14987   // for a member of a local class, but the correct predicate is not obvious.
14988   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14989     return;
14990 
14991   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14992   unsigned ContextKind = 3; // unknown
14993   if (isa<CXXMethodDecl>(VarDC) &&
14994       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14995     ContextKind = 2;
14996   } else if (isa<FunctionDecl>(VarDC)) {
14997     ContextKind = 0;
14998   } else if (isa<BlockDecl>(VarDC)) {
14999     ContextKind = 1;
15000   }
15001 
15002   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
15003     << var << ValueKind << ContextKind << VarDC;
15004   S.Diag(var->getLocation(), diag::note_entity_declared_at)
15005       << var;
15006 
15007   // FIXME: Add additional diagnostic info about class etc. which prevents
15008   // capture.
15009 }
15010 
15011 
15012 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
15013                                       bool &SubCapturesAreNested,
15014                                       QualType &CaptureType,
15015                                       QualType &DeclRefType) {
15016    // Check whether we've already captured it.
15017   if (CSI->CaptureMap.count(Var)) {
15018     // If we found a capture, any subcaptures are nested.
15019     SubCapturesAreNested = true;
15020 
15021     // Retrieve the capture type for this variable.
15022     CaptureType = CSI->getCapture(Var).getCaptureType();
15023 
15024     // Compute the type of an expression that refers to this variable.
15025     DeclRefType = CaptureType.getNonReferenceType();
15026 
15027     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
15028     // are mutable in the sense that user can change their value - they are
15029     // private instances of the captured declarations.
15030     const Capture &Cap = CSI->getCapture(Var);
15031     if (Cap.isCopyCapture() &&
15032         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
15033         !(isa<CapturedRegionScopeInfo>(CSI) &&
15034           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
15035       DeclRefType.addConst();
15036     return true;
15037   }
15038   return false;
15039 }
15040 
15041 // Only block literals, captured statements, and lambda expressions can
15042 // capture; other scopes don't work.
15043 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15044                                  SourceLocation Loc,
15045                                  const bool Diagnose, Sema &S) {
15046   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15047     return getLambdaAwareParentOfDeclContext(DC);
15048   else if (Var->hasLocalStorage()) {
15049     if (Diagnose)
15050        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15051   }
15052   return nullptr;
15053 }
15054 
15055 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15056 // certain types of variables (unnamed, variably modified types etc.)
15057 // so check for eligibility.
15058 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15059                                  SourceLocation Loc,
15060                                  const bool Diagnose, Sema &S) {
15061 
15062   bool IsBlock = isa<BlockScopeInfo>(CSI);
15063   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15064 
15065   // Lambdas are not allowed to capture unnamed variables
15066   // (e.g. anonymous unions).
15067   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15068   // assuming that's the intent.
15069   if (IsLambda && !Var->getDeclName()) {
15070     if (Diagnose) {
15071       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15072       S.Diag(Var->getLocation(), diag::note_declared_at);
15073     }
15074     return false;
15075   }
15076 
15077   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15078   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15079     if (Diagnose) {
15080       S.Diag(Loc, diag::err_ref_vm_type);
15081       S.Diag(Var->getLocation(), diag::note_previous_decl)
15082         << Var->getDeclName();
15083     }
15084     return false;
15085   }
15086   // Prohibit structs with flexible array members too.
15087   // We cannot capture what is in the tail end of the struct.
15088   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15089     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15090       if (Diagnose) {
15091         if (IsBlock)
15092           S.Diag(Loc, diag::err_ref_flexarray_type);
15093         else
15094           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15095             << Var->getDeclName();
15096         S.Diag(Var->getLocation(), diag::note_previous_decl)
15097           << Var->getDeclName();
15098       }
15099       return false;
15100     }
15101   }
15102   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15103   // Lambdas and captured statements are not allowed to capture __block
15104   // variables; they don't support the expected semantics.
15105   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15106     if (Diagnose) {
15107       S.Diag(Loc, diag::err_capture_block_variable)
15108         << Var->getDeclName() << !IsLambda;
15109       S.Diag(Var->getLocation(), diag::note_previous_decl)
15110         << Var->getDeclName();
15111     }
15112     return false;
15113   }
15114   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15115   if (S.getLangOpts().OpenCL && IsBlock &&
15116       Var->getType()->isBlockPointerType()) {
15117     if (Diagnose)
15118       S.Diag(Loc, diag::err_opencl_block_ref_block);
15119     return false;
15120   }
15121 
15122   return true;
15123 }
15124 
15125 // Returns true if the capture by block was successful.
15126 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15127                                  SourceLocation Loc,
15128                                  const bool BuildAndDiagnose,
15129                                  QualType &CaptureType,
15130                                  QualType &DeclRefType,
15131                                  const bool Nested,
15132                                  Sema &S) {
15133   Expr *CopyExpr = nullptr;
15134   bool ByRef = false;
15135 
15136   // Blocks are not allowed to capture arrays, excepting OpenCL.
15137   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15138   // (decayed to pointers).
15139   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15140     if (BuildAndDiagnose) {
15141       S.Diag(Loc, diag::err_ref_array_type);
15142       S.Diag(Var->getLocation(), diag::note_previous_decl)
15143       << Var->getDeclName();
15144     }
15145     return false;
15146   }
15147 
15148   // Forbid the block-capture of autoreleasing variables.
15149   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15150     if (BuildAndDiagnose) {
15151       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15152         << /*block*/ 0;
15153       S.Diag(Var->getLocation(), diag::note_previous_decl)
15154         << Var->getDeclName();
15155     }
15156     return false;
15157   }
15158 
15159   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15160   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15161     // This function finds out whether there is an AttributedType of kind
15162     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15163     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15164     // rather than being added implicitly by the compiler.
15165     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15166       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15167         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15168           return true;
15169 
15170         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15171         Ty = AttrTy->getModifiedType();
15172       }
15173 
15174       return false;
15175     };
15176 
15177     QualType PointeeTy = PT->getPointeeType();
15178 
15179     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
15180         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15181         !IsObjCOwnershipAttributedType(PointeeTy)) {
15182       if (BuildAndDiagnose) {
15183         SourceLocation VarLoc = Var->getLocation();
15184         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15185         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15186       }
15187     }
15188   }
15189 
15190   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15191   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15192       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15193     // Block capture by reference does not change the capture or
15194     // declaration reference types.
15195     ByRef = true;
15196   } else {
15197     // Block capture by copy introduces 'const'.
15198     CaptureType = CaptureType.getNonReferenceType().withConst();
15199     DeclRefType = CaptureType;
15200 
15201     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15202       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15203         // The capture logic needs the destructor, so make sure we mark it.
15204         // Usually this is unnecessary because most local variables have
15205         // their destructors marked at declaration time, but parameters are
15206         // an exception because it's technically only the call site that
15207         // actually requires the destructor.
15208         if (isa<ParmVarDecl>(Var))
15209           S.FinalizeVarWithDestructor(Var, Record);
15210 
15211         // Enter a new evaluation context to insulate the copy
15212         // full-expression.
15213         EnterExpressionEvaluationContext scope(
15214             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
15215 
15216         // According to the blocks spec, the capture of a variable from
15217         // the stack requires a const copy constructor.  This is not true
15218         // of the copy/move done to move a __block variable to the heap.
15219         Expr *DeclRef = new (S.Context) DeclRefExpr(
15220             S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15221 
15222         ExprResult Result
15223           = S.PerformCopyInitialization(
15224               InitializedEntity::InitializeBlock(Var->getLocation(),
15225                                                   CaptureType, false),
15226               Loc, DeclRef);
15227 
15228         // Build a full-expression copy expression if initialization
15229         // succeeded and used a non-trivial constructor.  Recover from
15230         // errors by pretending that the copy isn't necessary.
15231         if (!Result.isInvalid() &&
15232             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15233                 ->isTrivial()) {
15234           Result = S.MaybeCreateExprWithCleanups(Result);
15235           CopyExpr = Result.get();
15236         }
15237       }
15238     }
15239   }
15240 
15241   // Actually capture the variable.
15242   if (BuildAndDiagnose)
15243     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15244                     SourceLocation(), CaptureType, CopyExpr);
15245 
15246   return true;
15247 
15248 }
15249 
15250 
15251 /// Capture the given variable in the captured region.
15252 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15253                                     VarDecl *Var,
15254                                     SourceLocation Loc,
15255                                     const bool BuildAndDiagnose,
15256                                     QualType &CaptureType,
15257                                     QualType &DeclRefType,
15258                                     const bool RefersToCapturedVariable,
15259                                     Sema &S) {
15260   // By default, capture variables by reference.
15261   bool ByRef = true;
15262   // Using an LValue reference type is consistent with Lambdas (see below).
15263   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15264     if (S.isOpenMPCapturedDecl(Var)) {
15265       bool HasConst = DeclRefType.isConstQualified();
15266       DeclRefType = DeclRefType.getUnqualifiedType();
15267       // Don't lose diagnostics about assignments to const.
15268       if (HasConst)
15269         DeclRefType.addConst();
15270     }
15271     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15272   }
15273 
15274   if (ByRef)
15275     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15276   else
15277     CaptureType = DeclRefType;
15278 
15279   Expr *CopyExpr = nullptr;
15280   if (BuildAndDiagnose) {
15281     // The current implementation assumes that all variables are captured
15282     // by references. Since there is no capture by copy, no expression
15283     // evaluation will be needed.
15284     RecordDecl *RD = RSI->TheRecordDecl;
15285 
15286     FieldDecl *Field
15287       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15288                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15289                           nullptr, false, ICIS_NoInit);
15290     Field->setImplicit(true);
15291     Field->setAccess(AS_private);
15292     RD->addDecl(Field);
15293     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15294       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15295 
15296     CopyExpr = new (S.Context) DeclRefExpr(
15297         S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15298     Var->setReferenced(true);
15299     Var->markUsed(S.Context);
15300   }
15301 
15302   // Actually capture the variable.
15303   if (BuildAndDiagnose)
15304     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15305                     SourceLocation(), CaptureType, CopyExpr);
15306 
15307 
15308   return true;
15309 }
15310 
15311 /// Create a field within the lambda class for the variable
15312 /// being captured.
15313 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
15314                                     QualType FieldType, QualType DeclRefType,
15315                                     SourceLocation Loc,
15316                                     bool RefersToCapturedVariable) {
15317   CXXRecordDecl *Lambda = LSI->Lambda;
15318 
15319   // Build the non-static data member.
15320   FieldDecl *Field
15321     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15322                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15323                         nullptr, false, ICIS_NoInit);
15324   // If the variable being captured has an invalid type, mark the lambda class
15325   // as invalid as well.
15326   if (!FieldType->isDependentType()) {
15327     if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15328       Lambda->setInvalidDecl();
15329       Field->setInvalidDecl();
15330     } else {
15331       NamedDecl *Def;
15332       FieldType->isIncompleteType(&Def);
15333       if (Def && Def->isInvalidDecl()) {
15334         Lambda->setInvalidDecl();
15335         Field->setInvalidDecl();
15336       }
15337     }
15338   }
15339   Field->setImplicit(true);
15340   Field->setAccess(AS_private);
15341   Lambda->addDecl(Field);
15342 }
15343 
15344 /// Capture the given variable in the lambda.
15345 static bool captureInLambda(LambdaScopeInfo *LSI,
15346                             VarDecl *Var,
15347                             SourceLocation Loc,
15348                             const bool BuildAndDiagnose,
15349                             QualType &CaptureType,
15350                             QualType &DeclRefType,
15351                             const bool RefersToCapturedVariable,
15352                             const Sema::TryCaptureKind Kind,
15353                             SourceLocation EllipsisLoc,
15354                             const bool IsTopScope,
15355                             Sema &S) {
15356 
15357   // Determine whether we are capturing by reference or by value.
15358   bool ByRef = false;
15359   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15360     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15361   } else {
15362     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15363   }
15364 
15365   // Compute the type of the field that will capture this variable.
15366   if (ByRef) {
15367     // C++11 [expr.prim.lambda]p15:
15368     //   An entity is captured by reference if it is implicitly or
15369     //   explicitly captured but not captured by copy. It is
15370     //   unspecified whether additional unnamed non-static data
15371     //   members are declared in the closure type for entities
15372     //   captured by reference.
15373     //
15374     // FIXME: It is not clear whether we want to build an lvalue reference
15375     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15376     // to do the former, while EDG does the latter. Core issue 1249 will
15377     // clarify, but for now we follow GCC because it's a more permissive and
15378     // easily defensible position.
15379     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15380   } else {
15381     // C++11 [expr.prim.lambda]p14:
15382     //   For each entity captured by copy, an unnamed non-static
15383     //   data member is declared in the closure type. The
15384     //   declaration order of these members is unspecified. The type
15385     //   of such a data member is the type of the corresponding
15386     //   captured entity if the entity is not a reference to an
15387     //   object, or the referenced type otherwise. [Note: If the
15388     //   captured entity is a reference to a function, the
15389     //   corresponding data member is also a reference to a
15390     //   function. - end note ]
15391     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15392       if (!RefType->getPointeeType()->isFunctionType())
15393         CaptureType = RefType->getPointeeType();
15394     }
15395 
15396     // Forbid the lambda copy-capture of autoreleasing variables.
15397     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15398       if (BuildAndDiagnose) {
15399         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15400         S.Diag(Var->getLocation(), diag::note_previous_decl)
15401           << Var->getDeclName();
15402       }
15403       return false;
15404     }
15405 
15406     // Make sure that by-copy captures are of a complete and non-abstract type.
15407     if (BuildAndDiagnose) {
15408       if (!CaptureType->isDependentType() &&
15409           S.RequireCompleteType(Loc, CaptureType,
15410                                 diag::err_capture_of_incomplete_type,
15411                                 Var->getDeclName()))
15412         return false;
15413 
15414       if (S.RequireNonAbstractType(Loc, CaptureType,
15415                                    diag::err_capture_of_abstract_type))
15416         return false;
15417     }
15418   }
15419 
15420   // Capture this variable in the lambda.
15421   if (BuildAndDiagnose)
15422     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15423                             RefersToCapturedVariable);
15424 
15425   // Compute the type of a reference to this captured variable.
15426   if (ByRef)
15427     DeclRefType = CaptureType.getNonReferenceType();
15428   else {
15429     // C++ [expr.prim.lambda]p5:
15430     //   The closure type for a lambda-expression has a public inline
15431     //   function call operator [...]. This function call operator is
15432     //   declared const (9.3.1) if and only if the lambda-expression's
15433     //   parameter-declaration-clause is not followed by mutable.
15434     DeclRefType = CaptureType.getNonReferenceType();
15435     if (!LSI->Mutable && !CaptureType->isReferenceType())
15436       DeclRefType.addConst();
15437   }
15438 
15439   // Add the capture.
15440   if (BuildAndDiagnose)
15441     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15442                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15443 
15444   return true;
15445 }
15446 
15447 bool Sema::tryCaptureVariable(
15448     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15449     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15450     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15451   // An init-capture is notionally from the context surrounding its
15452   // declaration, but its parent DC is the lambda class.
15453   DeclContext *VarDC = Var->getDeclContext();
15454   if (Var->isInitCapture())
15455     VarDC = VarDC->getParent();
15456 
15457   DeclContext *DC = CurContext;
15458   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15459       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15460   // We need to sync up the Declaration Context with the
15461   // FunctionScopeIndexToStopAt
15462   if (FunctionScopeIndexToStopAt) {
15463     unsigned FSIndex = FunctionScopes.size() - 1;
15464     while (FSIndex != MaxFunctionScopesIndex) {
15465       DC = getLambdaAwareParentOfDeclContext(DC);
15466       --FSIndex;
15467     }
15468   }
15469 
15470 
15471   // If the variable is declared in the current context, there is no need to
15472   // capture it.
15473   if (VarDC == DC) return true;
15474 
15475   // Capture global variables if it is required to use private copy of this
15476   // variable.
15477   bool IsGlobal = !Var->hasLocalStorage();
15478   if (IsGlobal &&
15479       !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
15480                                                 MaxFunctionScopesIndex)))
15481     return true;
15482   Var = Var->getCanonicalDecl();
15483 
15484   // Walk up the stack to determine whether we can capture the variable,
15485   // performing the "simple" checks that don't depend on type. We stop when
15486   // we've either hit the declared scope of the variable or find an existing
15487   // capture of that variable.  We start from the innermost capturing-entity
15488   // (the DC) and ensure that all intervening capturing-entities
15489   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15490   // declcontext can either capture the variable or have already captured
15491   // the variable.
15492   CaptureType = Var->getType();
15493   DeclRefType = CaptureType.getNonReferenceType();
15494   bool Nested = false;
15495   bool Explicit = (Kind != TryCapture_Implicit);
15496   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15497   do {
15498     // Only block literals, captured statements, and lambda expressions can
15499     // capture; other scopes don't work.
15500     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15501                                                               ExprLoc,
15502                                                               BuildAndDiagnose,
15503                                                               *this);
15504     // We need to check for the parent *first* because, if we *have*
15505     // private-captured a global variable, we need to recursively capture it in
15506     // intermediate blocks, lambdas, etc.
15507     if (!ParentDC) {
15508       if (IsGlobal) {
15509         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15510         break;
15511       }
15512       return true;
15513     }
15514 
15515     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15516     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15517 
15518 
15519     // Check whether we've already captured it.
15520     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15521                                              DeclRefType)) {
15522       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15523       break;
15524     }
15525     // If we are instantiating a generic lambda call operator body,
15526     // we do not want to capture new variables.  What was captured
15527     // during either a lambdas transformation or initial parsing
15528     // should be used.
15529     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15530       if (BuildAndDiagnose) {
15531         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15532         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15533           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15534           Diag(Var->getLocation(), diag::note_previous_decl)
15535              << Var->getDeclName();
15536           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15537         } else
15538           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15539       }
15540       return true;
15541     }
15542     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15543     // certain types of variables (unnamed, variably modified types etc.)
15544     // so check for eligibility.
15545     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15546        return true;
15547 
15548     // Try to capture variable-length arrays types.
15549     if (Var->getType()->isVariablyModifiedType()) {
15550       // We're going to walk down into the type and look for VLA
15551       // expressions.
15552       QualType QTy = Var->getType();
15553       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15554         QTy = PVD->getOriginalType();
15555       captureVariablyModifiedType(Context, QTy, CSI);
15556     }
15557 
15558     if (getLangOpts().OpenMP) {
15559       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15560         // OpenMP private variables should not be captured in outer scope, so
15561         // just break here. Similarly, global variables that are captured in a
15562         // target region should not be captured outside the scope of the region.
15563         if (RSI->CapRegionKind == CR_OpenMP) {
15564           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15565           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15566                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15567           // When we detect target captures we are looking from inside the
15568           // target region, therefore we need to propagate the capture from the
15569           // enclosing region. Therefore, the capture is not initially nested.
15570           if (IsTargetCap)
15571             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15572 
15573           if (IsTargetCap || IsOpenMPPrivateDecl) {
15574             Nested = !IsTargetCap;
15575             DeclRefType = DeclRefType.getUnqualifiedType();
15576             CaptureType = Context.getLValueReferenceType(DeclRefType);
15577             break;
15578           }
15579         }
15580       }
15581     }
15582     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15583       // No capture-default, and this is not an explicit capture
15584       // so cannot capture this variable.
15585       if (BuildAndDiagnose) {
15586         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15587         Diag(Var->getLocation(), diag::note_previous_decl)
15588           << Var->getDeclName();
15589         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15590           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15591                diag::note_lambda_decl);
15592         // FIXME: If we error out because an outer lambda can not implicitly
15593         // capture a variable that an inner lambda explicitly captures, we
15594         // should have the inner lambda do the explicit capture - because
15595         // it makes for cleaner diagnostics later.  This would purely be done
15596         // so that the diagnostic does not misleadingly claim that a variable
15597         // can not be captured by a lambda implicitly even though it is captured
15598         // explicitly.  Suggestion:
15599         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15600         //    at the function head
15601         //  - cache the StartingDeclContext - this must be a lambda
15602         //  - captureInLambda in the innermost lambda the variable.
15603       }
15604       return true;
15605     }
15606 
15607     FunctionScopesIndex--;
15608     DC = ParentDC;
15609     Explicit = false;
15610   } while (!VarDC->Equals(DC));
15611 
15612   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15613   // computing the type of the capture at each step, checking type-specific
15614   // requirements, and adding captures if requested.
15615   // If the variable had already been captured previously, we start capturing
15616   // at the lambda nested within that one.
15617   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15618        ++I) {
15619     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15620 
15621     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15622       if (!captureInBlock(BSI, Var, ExprLoc,
15623                           BuildAndDiagnose, CaptureType,
15624                           DeclRefType, Nested, *this))
15625         return true;
15626       Nested = true;
15627     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15628       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15629                                    BuildAndDiagnose, CaptureType,
15630                                    DeclRefType, Nested, *this))
15631         return true;
15632       Nested = true;
15633     } else {
15634       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15635       if (!captureInLambda(LSI, Var, ExprLoc,
15636                            BuildAndDiagnose, CaptureType,
15637                            DeclRefType, Nested, Kind, EllipsisLoc,
15638                             /*IsTopScope*/I == N - 1, *this))
15639         return true;
15640       Nested = true;
15641     }
15642   }
15643   return false;
15644 }
15645 
15646 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15647                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15648   QualType CaptureType;
15649   QualType DeclRefType;
15650   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15651                             /*BuildAndDiagnose=*/true, CaptureType,
15652                             DeclRefType, nullptr);
15653 }
15654 
15655 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15656   QualType CaptureType;
15657   QualType DeclRefType;
15658   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15659                              /*BuildAndDiagnose=*/false, CaptureType,
15660                              DeclRefType, nullptr);
15661 }
15662 
15663 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15664   QualType CaptureType;
15665   QualType DeclRefType;
15666 
15667   // Determine whether we can capture this variable.
15668   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15669                          /*BuildAndDiagnose=*/false, CaptureType,
15670                          DeclRefType, nullptr))
15671     return QualType();
15672 
15673   return DeclRefType;
15674 }
15675 
15676 
15677 
15678 // If either the type of the variable or the initializer is dependent,
15679 // return false. Otherwise, determine whether the variable is a constant
15680 // expression. Use this if you need to know if a variable that might or
15681 // might not be dependent is truly a constant expression.
15682 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15683     ASTContext &Context) {
15684 
15685   if (Var->getType()->isDependentType())
15686     return false;
15687   const VarDecl *DefVD = nullptr;
15688   Var->getAnyInitializer(DefVD);
15689   if (!DefVD)
15690     return false;
15691   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15692   Expr *Init = cast<Expr>(Eval->Value);
15693   if (Init->isValueDependent())
15694     return false;
15695   return IsVariableAConstantExpression(Var, Context);
15696 }
15697 
15698 
15699 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15700   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15701   // an object that satisfies the requirements for appearing in a
15702   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15703   // is immediately applied."  This function handles the lvalue-to-rvalue
15704   // conversion part.
15705   MaybeODRUseExprs.erase(E->IgnoreParens());
15706 
15707   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15708   // to a variable that is a constant expression, and if so, identify it as
15709   // a reference to a variable that does not involve an odr-use of that
15710   // variable.
15711   if (LambdaScopeInfo *LSI = getCurLambda()) {
15712     Expr *SansParensExpr = E->IgnoreParens();
15713     VarDecl *Var = nullptr;
15714     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15715       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15716     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15717       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15718 
15719     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15720       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15721   }
15722 }
15723 
15724 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15725   Res = CorrectDelayedTyposInExpr(Res);
15726 
15727   if (!Res.isUsable())
15728     return Res;
15729 
15730   // If a constant-expression is a reference to a variable where we delay
15731   // deciding whether it is an odr-use, just assume we will apply the
15732   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15733   // (a non-type template argument), we have special handling anyway.
15734   UpdateMarkingForLValueToRValue(Res.get());
15735   return Res;
15736 }
15737 
15738 void Sema::CleanupVarDeclMarking() {
15739   // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
15740   // call.
15741   MaybeODRUseExprSet LocalMaybeODRUseExprs;
15742   std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
15743 
15744   for (Expr *E : LocalMaybeODRUseExprs) {
15745     VarDecl *Var;
15746     SourceLocation Loc;
15747     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15748       Var = cast<VarDecl>(DRE->getDecl());
15749       Loc = DRE->getLocation();
15750     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15751       Var = cast<VarDecl>(ME->getMemberDecl());
15752       Loc = ME->getMemberLoc();
15753     } else {
15754       llvm_unreachable("Unexpected expression");
15755     }
15756 
15757     MarkVarDeclODRUsed(Var, Loc, *this,
15758                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15759   }
15760 
15761   assert(MaybeODRUseExprs.empty() &&
15762          "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
15763 }
15764 
15765 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15766                                     VarDecl *Var, Expr *E) {
15767   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15768          "Invalid Expr argument to DoMarkVarDeclReferenced");
15769   Var->setReferenced();
15770 
15771   if (Var->isInvalidDecl())
15772     return;
15773 
15774   auto *MSI = Var->getMemberSpecializationInfo();
15775   TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
15776                                        : Var->getTemplateSpecializationKind();
15777 
15778   bool OdrUseContext = isOdrUseContext(SemaRef);
15779   bool UsableInConstantExpr =
15780       Var->isUsableInConstantExpressions(SemaRef.Context);
15781   bool NeedDefinition =
15782       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15783 
15784   VarTemplateSpecializationDecl *VarSpec =
15785       dyn_cast<VarTemplateSpecializationDecl>(Var);
15786   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15787          "Can't instantiate a partial template specialization.");
15788 
15789   // If this might be a member specialization of a static data member, check
15790   // the specialization is visible. We already did the checks for variable
15791   // template specializations when we created them.
15792   if (NeedDefinition && TSK != TSK_Undeclared &&
15793       !isa<VarTemplateSpecializationDecl>(Var))
15794     SemaRef.checkSpecializationVisibility(Loc, Var);
15795 
15796   // Perform implicit instantiation of static data members, static data member
15797   // templates of class templates, and variable template specializations. Delay
15798   // instantiations of variable templates, except for those that could be used
15799   // in a constant expression.
15800   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15801     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15802     // instantiation declaration if a variable is usable in a constant
15803     // expression (among other cases).
15804     bool TryInstantiating =
15805         TSK == TSK_ImplicitInstantiation ||
15806         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15807 
15808     if (TryInstantiating) {
15809       SourceLocation PointOfInstantiation =
15810           MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
15811       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15812       if (FirstInstantiation) {
15813         PointOfInstantiation = Loc;
15814         if (MSI)
15815           MSI->setPointOfInstantiation(PointOfInstantiation);
15816         else
15817           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15818       }
15819 
15820       bool InstantiationDependent = false;
15821       bool IsNonDependent =
15822           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15823                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15824                   : true;
15825 
15826       // Do not instantiate specializations that are still type-dependent.
15827       if (IsNonDependent) {
15828         if (UsableInConstantExpr) {
15829           // Do not defer instantiations of variables that could be used in a
15830           // constant expression.
15831           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15832         } else if (FirstInstantiation ||
15833                    isa<VarTemplateSpecializationDecl>(Var)) {
15834           // FIXME: For a specialization of a variable template, we don't
15835           // distinguish between "declaration and type implicitly instantiated"
15836           // and "implicit instantiation of definition requested", so we have
15837           // no direct way to avoid enqueueing the pending instantiation
15838           // multiple times.
15839           SemaRef.PendingInstantiations
15840               .push_back(std::make_pair(Var, PointOfInstantiation));
15841         }
15842       }
15843     }
15844   }
15845 
15846   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15847   // the requirements for appearing in a constant expression (5.19) and, if
15848   // it is an object, the lvalue-to-rvalue conversion (4.1)
15849   // is immediately applied."  We check the first part here, and
15850   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15851   // Note that we use the C++11 definition everywhere because nothing in
15852   // C++03 depends on whether we get the C++03 version correct. The second
15853   // part does not apply to references, since they are not objects.
15854   if (OdrUseContext && E &&
15855       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15856     // A reference initialized by a constant expression can never be
15857     // odr-used, so simply ignore it.
15858     if (!Var->getType()->isReferenceType() ||
15859         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15860       SemaRef.MaybeODRUseExprs.insert(E);
15861   } else if (OdrUseContext) {
15862     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15863                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15864   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15865     // If this is a dependent context, we don't need to mark variables as
15866     // odr-used, but we may still need to track them for lambda capture.
15867     // FIXME: Do we also need to do this inside dependent typeid expressions
15868     // (which are modeled as unevaluated at this point)?
15869     const bool RefersToEnclosingScope =
15870         (SemaRef.CurContext != Var->getDeclContext() &&
15871          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15872     if (RefersToEnclosingScope) {
15873       LambdaScopeInfo *const LSI =
15874           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15875       if (LSI && (!LSI->CallOperator ||
15876                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15877         // If a variable could potentially be odr-used, defer marking it so
15878         // until we finish analyzing the full expression for any
15879         // lvalue-to-rvalue
15880         // or discarded value conversions that would obviate odr-use.
15881         // Add it to the list of potential captures that will be analyzed
15882         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15883         // unless the variable is a reference that was initialized by a constant
15884         // expression (this will never need to be captured or odr-used).
15885         assert(E && "Capture variable should be used in an expression.");
15886         if (!Var->getType()->isReferenceType() ||
15887             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15888           LSI->addPotentialCapture(E->IgnoreParens());
15889       }
15890     }
15891   }
15892 }
15893 
15894 /// Mark a variable referenced, and check whether it is odr-used
15895 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15896 /// used directly for normal expressions referring to VarDecl.
15897 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15898   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15899 }
15900 
15901 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15902                                Decl *D, Expr *E, bool MightBeOdrUse) {
15903   if (SemaRef.isInOpenMPDeclareTargetContext())
15904     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15905 
15906   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15907     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15908     return;
15909   }
15910 
15911   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15912 
15913   // If this is a call to a method via a cast, also mark the method in the
15914   // derived class used in case codegen can devirtualize the call.
15915   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15916   if (!ME)
15917     return;
15918   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15919   if (!MD)
15920     return;
15921   // Only attempt to devirtualize if this is truly a virtual call.
15922   bool IsVirtualCall = MD->isVirtual() &&
15923                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15924   if (!IsVirtualCall)
15925     return;
15926 
15927   // If it's possible to devirtualize the call, mark the called function
15928   // referenced.
15929   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15930       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15931   if (DM)
15932     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15933 }
15934 
15935 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15936 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15937   // TODO: update this with DR# once a defect report is filed.
15938   // C++11 defect. The address of a pure member should not be an ODR use, even
15939   // if it's a qualified reference.
15940   bool OdrUse = true;
15941   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15942     if (Method->isVirtual() &&
15943         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15944       OdrUse = false;
15945   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15946 }
15947 
15948 /// Perform reference-marking and odr-use handling for a MemberExpr.
15949 void Sema::MarkMemberReferenced(MemberExpr *E) {
15950   // C++11 [basic.def.odr]p2:
15951   //   A non-overloaded function whose name appears as a potentially-evaluated
15952   //   expression or a member of a set of candidate functions, if selected by
15953   //   overload resolution when referred to from a potentially-evaluated
15954   //   expression, is odr-used, unless it is a pure virtual function and its
15955   //   name is not explicitly qualified.
15956   bool MightBeOdrUse = true;
15957   if (E->performsVirtualDispatch(getLangOpts())) {
15958     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15959       if (Method->isPure())
15960         MightBeOdrUse = false;
15961   }
15962   SourceLocation Loc =
15963       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15964   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15965 }
15966 
15967 /// Perform marking for a reference to an arbitrary declaration.  It
15968 /// marks the declaration referenced, and performs odr-use checking for
15969 /// functions and variables. This method should not be used when building a
15970 /// normal expression which refers to a variable.
15971 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15972                                  bool MightBeOdrUse) {
15973   if (MightBeOdrUse) {
15974     if (auto *VD = dyn_cast<VarDecl>(D)) {
15975       MarkVariableReferenced(Loc, VD);
15976       return;
15977     }
15978   }
15979   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15980     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15981     return;
15982   }
15983   D->setReferenced();
15984 }
15985 
15986 namespace {
15987   // Mark all of the declarations used by a type as referenced.
15988   // FIXME: Not fully implemented yet! We need to have a better understanding
15989   // of when we're entering a context we should not recurse into.
15990   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15991   // TreeTransforms rebuilding the type in a new context. Rather than
15992   // duplicating the TreeTransform logic, we should consider reusing it here.
15993   // Currently that causes problems when rebuilding LambdaExprs.
15994   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15995     Sema &S;
15996     SourceLocation Loc;
15997 
15998   public:
15999     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
16000 
16001     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
16002 
16003     bool TraverseTemplateArgument(const TemplateArgument &Arg);
16004   };
16005 }
16006 
16007 bool MarkReferencedDecls::TraverseTemplateArgument(
16008     const TemplateArgument &Arg) {
16009   {
16010     // A non-type template argument is a constant-evaluated context.
16011     EnterExpressionEvaluationContext Evaluated(
16012         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
16013     if (Arg.getKind() == TemplateArgument::Declaration) {
16014       if (Decl *D = Arg.getAsDecl())
16015         S.MarkAnyDeclReferenced(Loc, D, true);
16016     } else if (Arg.getKind() == TemplateArgument::Expression) {
16017       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
16018     }
16019   }
16020 
16021   return Inherited::TraverseTemplateArgument(Arg);
16022 }
16023 
16024 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
16025   MarkReferencedDecls Marker(*this, Loc);
16026   Marker.TraverseType(T);
16027 }
16028 
16029 namespace {
16030   /// Helper class that marks all of the declarations referenced by
16031   /// potentially-evaluated subexpressions as "referenced".
16032   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
16033     Sema &S;
16034     bool SkipLocalVariables;
16035 
16036   public:
16037     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
16038 
16039     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
16040       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
16041 
16042     void VisitDeclRefExpr(DeclRefExpr *E) {
16043       // If we were asked not to visit local variables, don't.
16044       if (SkipLocalVariables) {
16045         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
16046           if (VD->hasLocalStorage())
16047             return;
16048       }
16049 
16050       S.MarkDeclRefReferenced(E);
16051     }
16052 
16053     void VisitMemberExpr(MemberExpr *E) {
16054       S.MarkMemberReferenced(E);
16055       Inherited::VisitMemberExpr(E);
16056     }
16057 
16058     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16059       S.MarkFunctionReferenced(
16060           E->getBeginLoc(),
16061           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16062       Visit(E->getSubExpr());
16063     }
16064 
16065     void VisitCXXNewExpr(CXXNewExpr *E) {
16066       if (E->getOperatorNew())
16067         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16068       if (E->getOperatorDelete())
16069         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16070       Inherited::VisitCXXNewExpr(E);
16071     }
16072 
16073     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16074       if (E->getOperatorDelete())
16075         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16076       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16077       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16078         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16079         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16080       }
16081 
16082       Inherited::VisitCXXDeleteExpr(E);
16083     }
16084 
16085     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16086       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16087       Inherited::VisitCXXConstructExpr(E);
16088     }
16089 
16090     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16091       Visit(E->getExpr());
16092     }
16093 
16094     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
16095       Inherited::VisitImplicitCastExpr(E);
16096 
16097       if (E->getCastKind() == CK_LValueToRValue)
16098         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
16099     }
16100   };
16101 }
16102 
16103 /// Mark any declarations that appear within this expression or any
16104 /// potentially-evaluated subexpressions as "referenced".
16105 ///
16106 /// \param SkipLocalVariables If true, don't mark local variables as
16107 /// 'referenced'.
16108 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16109                                             bool SkipLocalVariables) {
16110   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16111 }
16112 
16113 /// Emit a diagnostic that describes an effect on the run-time behavior
16114 /// of the program being compiled.
16115 ///
16116 /// This routine emits the given diagnostic when the code currently being
16117 /// type-checked is "potentially evaluated", meaning that there is a
16118 /// possibility that the code will actually be executable. Code in sizeof()
16119 /// expressions, code used only during overload resolution, etc., are not
16120 /// potentially evaluated. This routine will suppress such diagnostics or,
16121 /// in the absolutely nutty case of potentially potentially evaluated
16122 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16123 /// later.
16124 ///
16125 /// This routine should be used for all diagnostics that describe the run-time
16126 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16127 /// Failure to do so will likely result in spurious diagnostics or failures
16128 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16129 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
16130                                const PartialDiagnostic &PD) {
16131   switch (ExprEvalContexts.back().Context) {
16132   case ExpressionEvaluationContext::Unevaluated:
16133   case ExpressionEvaluationContext::UnevaluatedList:
16134   case ExpressionEvaluationContext::UnevaluatedAbstract:
16135   case ExpressionEvaluationContext::DiscardedStatement:
16136     // The argument will never be evaluated, so don't complain.
16137     break;
16138 
16139   case ExpressionEvaluationContext::ConstantEvaluated:
16140     // Relevant diagnostics should be produced by constant evaluation.
16141     break;
16142 
16143   case ExpressionEvaluationContext::PotentiallyEvaluated:
16144   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16145     if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
16146       FunctionScopes.back()->PossiblyUnreachableDiags.
16147         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
16148       return true;
16149     }
16150 
16151     // The initializer of a constexpr variable or of the first declaration of a
16152     // static data member is not syntactically a constant evaluated constant,
16153     // but nonetheless is always required to be a constant expression, so we
16154     // can skip diagnosing.
16155     // FIXME: Using the mangling context here is a hack.
16156     if (auto *VD = dyn_cast_or_null<VarDecl>(
16157             ExprEvalContexts.back().ManglingContextDecl)) {
16158       if (VD->isConstexpr() ||
16159           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16160         break;
16161       // FIXME: For any other kind of variable, we should build a CFG for its
16162       // initializer and check whether the context in question is reachable.
16163     }
16164 
16165     Diag(Loc, PD);
16166     return true;
16167   }
16168 
16169   return false;
16170 }
16171 
16172 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16173                                const PartialDiagnostic &PD) {
16174   return DiagRuntimeBehavior(
16175       Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
16176 }
16177 
16178 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16179                                CallExpr *CE, FunctionDecl *FD) {
16180   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16181     return false;
16182 
16183   // If we're inside a decltype's expression, don't check for a valid return
16184   // type or construct temporaries until we know whether this is the last call.
16185   if (ExprEvalContexts.back().ExprContext ==
16186       ExpressionEvaluationContextRecord::EK_Decltype) {
16187     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16188     return false;
16189   }
16190 
16191   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16192     FunctionDecl *FD;
16193     CallExpr *CE;
16194 
16195   public:
16196     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16197       : FD(FD), CE(CE) { }
16198 
16199     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16200       if (!FD) {
16201         S.Diag(Loc, diag::err_call_incomplete_return)
16202           << T << CE->getSourceRange();
16203         return;
16204       }
16205 
16206       S.Diag(Loc, diag::err_call_function_incomplete_return)
16207         << CE->getSourceRange() << FD->getDeclName() << T;
16208       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16209           << FD->getDeclName();
16210     }
16211   } Diagnoser(FD, CE);
16212 
16213   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16214     return true;
16215 
16216   return false;
16217 }
16218 
16219 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16220 // will prevent this condition from triggering, which is what we want.
16221 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16222   SourceLocation Loc;
16223 
16224   unsigned diagnostic = diag::warn_condition_is_assignment;
16225   bool IsOrAssign = false;
16226 
16227   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16228     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16229       return;
16230 
16231     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16232 
16233     // Greylist some idioms by putting them into a warning subcategory.
16234     if (ObjCMessageExpr *ME
16235           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16236       Selector Sel = ME->getSelector();
16237 
16238       // self = [<foo> init...]
16239       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16240         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16241 
16242       // <foo> = [<bar> nextObject]
16243       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16244         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16245     }
16246 
16247     Loc = Op->getOperatorLoc();
16248   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16249     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16250       return;
16251 
16252     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16253     Loc = Op->getOperatorLoc();
16254   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16255     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16256   else {
16257     // Not an assignment.
16258     return;
16259   }
16260 
16261   Diag(Loc, diagnostic) << E->getSourceRange();
16262 
16263   SourceLocation Open = E->getBeginLoc();
16264   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16265   Diag(Loc, diag::note_condition_assign_silence)
16266         << FixItHint::CreateInsertion(Open, "(")
16267         << FixItHint::CreateInsertion(Close, ")");
16268 
16269   if (IsOrAssign)
16270     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16271       << FixItHint::CreateReplacement(Loc, "!=");
16272   else
16273     Diag(Loc, diag::note_condition_assign_to_comparison)
16274       << FixItHint::CreateReplacement(Loc, "==");
16275 }
16276 
16277 /// Redundant parentheses over an equality comparison can indicate
16278 /// that the user intended an assignment used as condition.
16279 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16280   // Don't warn if the parens came from a macro.
16281   SourceLocation parenLoc = ParenE->getBeginLoc();
16282   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16283     return;
16284   // Don't warn for dependent expressions.
16285   if (ParenE->isTypeDependent())
16286     return;
16287 
16288   Expr *E = ParenE->IgnoreParens();
16289 
16290   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16291     if (opE->getOpcode() == BO_EQ &&
16292         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16293                                                            == Expr::MLV_Valid) {
16294       SourceLocation Loc = opE->getOperatorLoc();
16295 
16296       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16297       SourceRange ParenERange = ParenE->getSourceRange();
16298       Diag(Loc, diag::note_equality_comparison_silence)
16299         << FixItHint::CreateRemoval(ParenERange.getBegin())
16300         << FixItHint::CreateRemoval(ParenERange.getEnd());
16301       Diag(Loc, diag::note_equality_comparison_to_assign)
16302         << FixItHint::CreateReplacement(Loc, "=");
16303     }
16304 }
16305 
16306 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16307                                        bool IsConstexpr) {
16308   DiagnoseAssignmentAsCondition(E);
16309   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16310     DiagnoseEqualityWithExtraParens(parenE);
16311 
16312   ExprResult result = CheckPlaceholderExpr(E);
16313   if (result.isInvalid()) return ExprError();
16314   E = result.get();
16315 
16316   if (!E->isTypeDependent()) {
16317     if (getLangOpts().CPlusPlus)
16318       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16319 
16320     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16321     if (ERes.isInvalid())
16322       return ExprError();
16323     E = ERes.get();
16324 
16325     QualType T = E->getType();
16326     if (!T->isScalarType()) { // C99 6.8.4.1p1
16327       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16328         << T << E->getSourceRange();
16329       return ExprError();
16330     }
16331     CheckBoolLikeConversion(E, Loc);
16332   }
16333 
16334   return E;
16335 }
16336 
16337 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16338                                            Expr *SubExpr, ConditionKind CK) {
16339   // Empty conditions are valid in for-statements.
16340   if (!SubExpr)
16341     return ConditionResult();
16342 
16343   ExprResult Cond;
16344   switch (CK) {
16345   case ConditionKind::Boolean:
16346     Cond = CheckBooleanCondition(Loc, SubExpr);
16347     break;
16348 
16349   case ConditionKind::ConstexprIf:
16350     Cond = CheckBooleanCondition(Loc, SubExpr, true);
16351     break;
16352 
16353   case ConditionKind::Switch:
16354     Cond = CheckSwitchCondition(Loc, SubExpr);
16355     break;
16356   }
16357   if (Cond.isInvalid())
16358     return ConditionError();
16359 
16360   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16361   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16362   if (!FullExpr.get())
16363     return ConditionError();
16364 
16365   return ConditionResult(*this, nullptr, FullExpr,
16366                          CK == ConditionKind::ConstexprIf);
16367 }
16368 
16369 namespace {
16370   /// A visitor for rebuilding a call to an __unknown_any expression
16371   /// to have an appropriate type.
16372   struct RebuildUnknownAnyFunction
16373     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16374 
16375     Sema &S;
16376 
16377     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16378 
16379     ExprResult VisitStmt(Stmt *S) {
16380       llvm_unreachable("unexpected statement!");
16381     }
16382 
16383     ExprResult VisitExpr(Expr *E) {
16384       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16385         << E->getSourceRange();
16386       return ExprError();
16387     }
16388 
16389     /// Rebuild an expression which simply semantically wraps another
16390     /// expression which it shares the type and value kind of.
16391     template <class T> ExprResult rebuildSugarExpr(T *E) {
16392       ExprResult SubResult = Visit(E->getSubExpr());
16393       if (SubResult.isInvalid()) return ExprError();
16394 
16395       Expr *SubExpr = SubResult.get();
16396       E->setSubExpr(SubExpr);
16397       E->setType(SubExpr->getType());
16398       E->setValueKind(SubExpr->getValueKind());
16399       assert(E->getObjectKind() == OK_Ordinary);
16400       return E;
16401     }
16402 
16403     ExprResult VisitParenExpr(ParenExpr *E) {
16404       return rebuildSugarExpr(E);
16405     }
16406 
16407     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16408       return rebuildSugarExpr(E);
16409     }
16410 
16411     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16412       ExprResult SubResult = Visit(E->getSubExpr());
16413       if (SubResult.isInvalid()) return ExprError();
16414 
16415       Expr *SubExpr = SubResult.get();
16416       E->setSubExpr(SubExpr);
16417       E->setType(S.Context.getPointerType(SubExpr->getType()));
16418       assert(E->getValueKind() == VK_RValue);
16419       assert(E->getObjectKind() == OK_Ordinary);
16420       return E;
16421     }
16422 
16423     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16424       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16425 
16426       E->setType(VD->getType());
16427 
16428       assert(E->getValueKind() == VK_RValue);
16429       if (S.getLangOpts().CPlusPlus &&
16430           !(isa<CXXMethodDecl>(VD) &&
16431             cast<CXXMethodDecl>(VD)->isInstance()))
16432         E->setValueKind(VK_LValue);
16433 
16434       return E;
16435     }
16436 
16437     ExprResult VisitMemberExpr(MemberExpr *E) {
16438       return resolveDecl(E, E->getMemberDecl());
16439     }
16440 
16441     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16442       return resolveDecl(E, E->getDecl());
16443     }
16444   };
16445 }
16446 
16447 /// Given a function expression of unknown-any type, try to rebuild it
16448 /// to have a function type.
16449 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16450   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16451   if (Result.isInvalid()) return ExprError();
16452   return S.DefaultFunctionArrayConversion(Result.get());
16453 }
16454 
16455 namespace {
16456   /// A visitor for rebuilding an expression of type __unknown_anytype
16457   /// into one which resolves the type directly on the referring
16458   /// expression.  Strict preservation of the original source
16459   /// structure is not a goal.
16460   struct RebuildUnknownAnyExpr
16461     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16462 
16463     Sema &S;
16464 
16465     /// The current destination type.
16466     QualType DestType;
16467 
16468     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16469       : S(S), DestType(CastType) {}
16470 
16471     ExprResult VisitStmt(Stmt *S) {
16472       llvm_unreachable("unexpected statement!");
16473     }
16474 
16475     ExprResult VisitExpr(Expr *E) {
16476       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16477         << E->getSourceRange();
16478       return ExprError();
16479     }
16480 
16481     ExprResult VisitCallExpr(CallExpr *E);
16482     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16483 
16484     /// Rebuild an expression which simply semantically wraps another
16485     /// expression which it shares the type and value kind of.
16486     template <class T> ExprResult rebuildSugarExpr(T *E) {
16487       ExprResult SubResult = Visit(E->getSubExpr());
16488       if (SubResult.isInvalid()) return ExprError();
16489       Expr *SubExpr = SubResult.get();
16490       E->setSubExpr(SubExpr);
16491       E->setType(SubExpr->getType());
16492       E->setValueKind(SubExpr->getValueKind());
16493       assert(E->getObjectKind() == OK_Ordinary);
16494       return E;
16495     }
16496 
16497     ExprResult VisitParenExpr(ParenExpr *E) {
16498       return rebuildSugarExpr(E);
16499     }
16500 
16501     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16502       return rebuildSugarExpr(E);
16503     }
16504 
16505     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16506       const PointerType *Ptr = DestType->getAs<PointerType>();
16507       if (!Ptr) {
16508         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16509           << E->getSourceRange();
16510         return ExprError();
16511       }
16512 
16513       if (isa<CallExpr>(E->getSubExpr())) {
16514         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16515           << E->getSourceRange();
16516         return ExprError();
16517       }
16518 
16519       assert(E->getValueKind() == VK_RValue);
16520       assert(E->getObjectKind() == OK_Ordinary);
16521       E->setType(DestType);
16522 
16523       // Build the sub-expression as if it were an object of the pointee type.
16524       DestType = Ptr->getPointeeType();
16525       ExprResult SubResult = Visit(E->getSubExpr());
16526       if (SubResult.isInvalid()) return ExprError();
16527       E->setSubExpr(SubResult.get());
16528       return E;
16529     }
16530 
16531     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16532 
16533     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16534 
16535     ExprResult VisitMemberExpr(MemberExpr *E) {
16536       return resolveDecl(E, E->getMemberDecl());
16537     }
16538 
16539     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16540       return resolveDecl(E, E->getDecl());
16541     }
16542   };
16543 }
16544 
16545 /// Rebuilds a call expression which yielded __unknown_anytype.
16546 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16547   Expr *CalleeExpr = E->getCallee();
16548 
16549   enum FnKind {
16550     FK_MemberFunction,
16551     FK_FunctionPointer,
16552     FK_BlockPointer
16553   };
16554 
16555   FnKind Kind;
16556   QualType CalleeType = CalleeExpr->getType();
16557   if (CalleeType == S.Context.BoundMemberTy) {
16558     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16559     Kind = FK_MemberFunction;
16560     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16561   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16562     CalleeType = Ptr->getPointeeType();
16563     Kind = FK_FunctionPointer;
16564   } else {
16565     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16566     Kind = FK_BlockPointer;
16567   }
16568   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16569 
16570   // Verify that this is a legal result type of a function.
16571   if (DestType->isArrayType() || DestType->isFunctionType()) {
16572     unsigned diagID = diag::err_func_returning_array_function;
16573     if (Kind == FK_BlockPointer)
16574       diagID = diag::err_block_returning_array_function;
16575 
16576     S.Diag(E->getExprLoc(), diagID)
16577       << DestType->isFunctionType() << DestType;
16578     return ExprError();
16579   }
16580 
16581   // Otherwise, go ahead and set DestType as the call's result.
16582   E->setType(DestType.getNonLValueExprType(S.Context));
16583   E->setValueKind(Expr::getValueKindForType(DestType));
16584   assert(E->getObjectKind() == OK_Ordinary);
16585 
16586   // Rebuild the function type, replacing the result type with DestType.
16587   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16588   if (Proto) {
16589     // __unknown_anytype(...) is a special case used by the debugger when
16590     // it has no idea what a function's signature is.
16591     //
16592     // We want to build this call essentially under the K&R
16593     // unprototyped rules, but making a FunctionNoProtoType in C++
16594     // would foul up all sorts of assumptions.  However, we cannot
16595     // simply pass all arguments as variadic arguments, nor can we
16596     // portably just call the function under a non-variadic type; see
16597     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16598     // However, it turns out that in practice it is generally safe to
16599     // call a function declared as "A foo(B,C,D);" under the prototype
16600     // "A foo(B,C,D,...);".  The only known exception is with the
16601     // Windows ABI, where any variadic function is implicitly cdecl
16602     // regardless of its normal CC.  Therefore we change the parameter
16603     // types to match the types of the arguments.
16604     //
16605     // This is a hack, but it is far superior to moving the
16606     // corresponding target-specific code from IR-gen to Sema/AST.
16607 
16608     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16609     SmallVector<QualType, 8> ArgTypes;
16610     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16611       ArgTypes.reserve(E->getNumArgs());
16612       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16613         Expr *Arg = E->getArg(i);
16614         QualType ArgType = Arg->getType();
16615         if (E->isLValue()) {
16616           ArgType = S.Context.getLValueReferenceType(ArgType);
16617         } else if (E->isXValue()) {
16618           ArgType = S.Context.getRValueReferenceType(ArgType);
16619         }
16620         ArgTypes.push_back(ArgType);
16621       }
16622       ParamTypes = ArgTypes;
16623     }
16624     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16625                                          Proto->getExtProtoInfo());
16626   } else {
16627     DestType = S.Context.getFunctionNoProtoType(DestType,
16628                                                 FnType->getExtInfo());
16629   }
16630 
16631   // Rebuild the appropriate pointer-to-function type.
16632   switch (Kind) {
16633   case FK_MemberFunction:
16634     // Nothing to do.
16635     break;
16636 
16637   case FK_FunctionPointer:
16638     DestType = S.Context.getPointerType(DestType);
16639     break;
16640 
16641   case FK_BlockPointer:
16642     DestType = S.Context.getBlockPointerType(DestType);
16643     break;
16644   }
16645 
16646   // Finally, we can recurse.
16647   ExprResult CalleeResult = Visit(CalleeExpr);
16648   if (!CalleeResult.isUsable()) return ExprError();
16649   E->setCallee(CalleeResult.get());
16650 
16651   // Bind a temporary if necessary.
16652   return S.MaybeBindToTemporary(E);
16653 }
16654 
16655 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16656   // Verify that this is a legal result type of a call.
16657   if (DestType->isArrayType() || DestType->isFunctionType()) {
16658     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16659       << DestType->isFunctionType() << DestType;
16660     return ExprError();
16661   }
16662 
16663   // Rewrite the method result type if available.
16664   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16665     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16666     Method->setReturnType(DestType);
16667   }
16668 
16669   // Change the type of the message.
16670   E->setType(DestType.getNonReferenceType());
16671   E->setValueKind(Expr::getValueKindForType(DestType));
16672 
16673   return S.MaybeBindToTemporary(E);
16674 }
16675 
16676 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16677   // The only case we should ever see here is a function-to-pointer decay.
16678   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16679     assert(E->getValueKind() == VK_RValue);
16680     assert(E->getObjectKind() == OK_Ordinary);
16681 
16682     E->setType(DestType);
16683 
16684     // Rebuild the sub-expression as the pointee (function) type.
16685     DestType = DestType->castAs<PointerType>()->getPointeeType();
16686 
16687     ExprResult Result = Visit(E->getSubExpr());
16688     if (!Result.isUsable()) return ExprError();
16689 
16690     E->setSubExpr(Result.get());
16691     return E;
16692   } else if (E->getCastKind() == CK_LValueToRValue) {
16693     assert(E->getValueKind() == VK_RValue);
16694     assert(E->getObjectKind() == OK_Ordinary);
16695 
16696     assert(isa<BlockPointerType>(E->getType()));
16697 
16698     E->setType(DestType);
16699 
16700     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16701     DestType = S.Context.getLValueReferenceType(DestType);
16702 
16703     ExprResult Result = Visit(E->getSubExpr());
16704     if (!Result.isUsable()) return ExprError();
16705 
16706     E->setSubExpr(Result.get());
16707     return E;
16708   } else {
16709     llvm_unreachable("Unhandled cast type!");
16710   }
16711 }
16712 
16713 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16714   ExprValueKind ValueKind = VK_LValue;
16715   QualType Type = DestType;
16716 
16717   // We know how to make this work for certain kinds of decls:
16718 
16719   //  - functions
16720   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16721     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16722       DestType = Ptr->getPointeeType();
16723       ExprResult Result = resolveDecl(E, VD);
16724       if (Result.isInvalid()) return ExprError();
16725       return S.ImpCastExprToType(Result.get(), Type,
16726                                  CK_FunctionToPointerDecay, VK_RValue);
16727     }
16728 
16729     if (!Type->isFunctionType()) {
16730       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16731         << VD << E->getSourceRange();
16732       return ExprError();
16733     }
16734     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16735       // We must match the FunctionDecl's type to the hack introduced in
16736       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16737       // type. See the lengthy commentary in that routine.
16738       QualType FDT = FD->getType();
16739       const FunctionType *FnType = FDT->castAs<FunctionType>();
16740       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16741       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16742       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16743         SourceLocation Loc = FD->getLocation();
16744         FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
16745                                       FD->getDeclContext(),
16746                                       Loc, Loc, FD->getNameInfo().getName(),
16747                                       DestType, FD->getTypeSourceInfo(),
16748                                       SC_None, false/*isInlineSpecified*/,
16749                                       FD->hasPrototype(),
16750                                       false/*isConstexprSpecified*/);
16751 
16752         if (FD->getQualifier())
16753           NewFD->setQualifierInfo(FD->getQualifierLoc());
16754 
16755         SmallVector<ParmVarDecl*, 16> Params;
16756         for (const auto &AI : FT->param_types()) {
16757           ParmVarDecl *Param =
16758             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16759           Param->setScopeInfo(0, Params.size());
16760           Params.push_back(Param);
16761         }
16762         NewFD->setParams(Params);
16763         DRE->setDecl(NewFD);
16764         VD = DRE->getDecl();
16765       }
16766     }
16767 
16768     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16769       if (MD->isInstance()) {
16770         ValueKind = VK_RValue;
16771         Type = S.Context.BoundMemberTy;
16772       }
16773 
16774     // Function references aren't l-values in C.
16775     if (!S.getLangOpts().CPlusPlus)
16776       ValueKind = VK_RValue;
16777 
16778   //  - variables
16779   } else if (isa<VarDecl>(VD)) {
16780     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16781       Type = RefTy->getPointeeType();
16782     } else if (Type->isFunctionType()) {
16783       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16784         << VD << E->getSourceRange();
16785       return ExprError();
16786     }
16787 
16788   //  - nothing else
16789   } else {
16790     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16791       << VD << E->getSourceRange();
16792     return ExprError();
16793   }
16794 
16795   // Modifying the declaration like this is friendly to IR-gen but
16796   // also really dangerous.
16797   VD->setType(DestType);
16798   E->setType(Type);
16799   E->setValueKind(ValueKind);
16800   return E;
16801 }
16802 
16803 /// Check a cast of an unknown-any type.  We intentionally only
16804 /// trigger this for C-style casts.
16805 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16806                                      Expr *CastExpr, CastKind &CastKind,
16807                                      ExprValueKind &VK, CXXCastPath &Path) {
16808   // The type we're casting to must be either void or complete.
16809   if (!CastType->isVoidType() &&
16810       RequireCompleteType(TypeRange.getBegin(), CastType,
16811                           diag::err_typecheck_cast_to_incomplete))
16812     return ExprError();
16813 
16814   // Rewrite the casted expression from scratch.
16815   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16816   if (!result.isUsable()) return ExprError();
16817 
16818   CastExpr = result.get();
16819   VK = CastExpr->getValueKind();
16820   CastKind = CK_NoOp;
16821 
16822   return CastExpr;
16823 }
16824 
16825 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16826   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16827 }
16828 
16829 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16830                                     Expr *arg, QualType &paramType) {
16831   // If the syntactic form of the argument is not an explicit cast of
16832   // any sort, just do default argument promotion.
16833   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16834   if (!castArg) {
16835     ExprResult result = DefaultArgumentPromotion(arg);
16836     if (result.isInvalid()) return ExprError();
16837     paramType = result.get()->getType();
16838     return result;
16839   }
16840 
16841   // Otherwise, use the type that was written in the explicit cast.
16842   assert(!arg->hasPlaceholderType());
16843   paramType = castArg->getTypeAsWritten();
16844 
16845   // Copy-initialize a parameter of that type.
16846   InitializedEntity entity =
16847     InitializedEntity::InitializeParameter(Context, paramType,
16848                                            /*consumed*/ false);
16849   return PerformCopyInitialization(entity, callLoc, arg);
16850 }
16851 
16852 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16853   Expr *orig = E;
16854   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16855   while (true) {
16856     E = E->IgnoreParenImpCasts();
16857     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16858       E = call->getCallee();
16859       diagID = diag::err_uncasted_call_of_unknown_any;
16860     } else {
16861       break;
16862     }
16863   }
16864 
16865   SourceLocation loc;
16866   NamedDecl *d;
16867   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16868     loc = ref->getLocation();
16869     d = ref->getDecl();
16870   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16871     loc = mem->getMemberLoc();
16872     d = mem->getMemberDecl();
16873   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16874     diagID = diag::err_uncasted_call_of_unknown_any;
16875     loc = msg->getSelectorStartLoc();
16876     d = msg->getMethodDecl();
16877     if (!d) {
16878       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16879         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16880         << orig->getSourceRange();
16881       return ExprError();
16882     }
16883   } else {
16884     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16885       << E->getSourceRange();
16886     return ExprError();
16887   }
16888 
16889   S.Diag(loc, diagID) << d << orig->getSourceRange();
16890 
16891   // Never recoverable.
16892   return ExprError();
16893 }
16894 
16895 /// Check for operands with placeholder types and complain if found.
16896 /// Returns ExprError() if there was an error and no recovery was possible.
16897 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16898   if (!getLangOpts().CPlusPlus) {
16899     // C cannot handle TypoExpr nodes on either side of a binop because it
16900     // doesn't handle dependent types properly, so make sure any TypoExprs have
16901     // been dealt with before checking the operands.
16902     ExprResult Result = CorrectDelayedTyposInExpr(E);
16903     if (!Result.isUsable()) return ExprError();
16904     E = Result.get();
16905   }
16906 
16907   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16908   if (!placeholderType) return E;
16909 
16910   switch (placeholderType->getKind()) {
16911 
16912   // Overloaded expressions.
16913   case BuiltinType::Overload: {
16914     // Try to resolve a single function template specialization.
16915     // This is obligatory.
16916     ExprResult Result = E;
16917     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16918       return Result;
16919 
16920     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16921     // leaves Result unchanged on failure.
16922     Result = E;
16923     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16924       return Result;
16925 
16926     // If that failed, try to recover with a call.
16927     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16928                          /*complain*/ true);
16929     return Result;
16930   }
16931 
16932   // Bound member functions.
16933   case BuiltinType::BoundMember: {
16934     ExprResult result = E;
16935     const Expr *BME = E->IgnoreParens();
16936     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16937     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16938     if (isa<CXXPseudoDestructorExpr>(BME)) {
16939       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16940     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16941       if (ME->getMemberNameInfo().getName().getNameKind() ==
16942           DeclarationName::CXXDestructorName)
16943         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16944     }
16945     tryToRecoverWithCall(result, PD,
16946                          /*complain*/ true);
16947     return result;
16948   }
16949 
16950   // ARC unbridged casts.
16951   case BuiltinType::ARCUnbridgedCast: {
16952     Expr *realCast = stripARCUnbridgedCast(E);
16953     diagnoseARCUnbridgedCast(realCast);
16954     return realCast;
16955   }
16956 
16957   // Expressions of unknown type.
16958   case BuiltinType::UnknownAny:
16959     return diagnoseUnknownAnyExpr(*this, E);
16960 
16961   // Pseudo-objects.
16962   case BuiltinType::PseudoObject:
16963     return checkPseudoObjectRValue(E);
16964 
16965   case BuiltinType::BuiltinFn: {
16966     // Accept __noop without parens by implicitly converting it to a call expr.
16967     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16968     if (DRE) {
16969       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16970       if (FD->getBuiltinID() == Builtin::BI__noop) {
16971         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16972                               CK_BuiltinFnToFnPtr)
16973                 .get();
16974         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16975                                 VK_RValue, SourceLocation());
16976       }
16977     }
16978 
16979     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16980     return ExprError();
16981   }
16982 
16983   // Expressions of unknown type.
16984   case BuiltinType::OMPArraySection:
16985     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16986     return ExprError();
16987 
16988   // Everything else should be impossible.
16989 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16990   case BuiltinType::Id:
16991 #include "clang/Basic/OpenCLImageTypes.def"
16992 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16993   case BuiltinType::Id:
16994 #include "clang/Basic/OpenCLExtensionTypes.def"
16995 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16996 #define PLACEHOLDER_TYPE(Id, SingletonId)
16997 #include "clang/AST/BuiltinTypes.def"
16998     break;
16999   }
17000 
17001   llvm_unreachable("invalid placeholder type!");
17002 }
17003 
17004 bool Sema::CheckCaseExpression(Expr *E) {
17005   if (E->isTypeDependent())
17006     return true;
17007   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
17008     return E->getType()->isIntegralOrEnumerationType();
17009   return false;
17010 }
17011 
17012 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
17013 ExprResult
17014 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
17015   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
17016          "Unknown Objective-C Boolean value!");
17017   QualType BoolT = Context.ObjCBuiltinBoolTy;
17018   if (!Context.getBOOLDecl()) {
17019     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
17020                         Sema::LookupOrdinaryName);
17021     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
17022       NamedDecl *ND = Result.getFoundDecl();
17023       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
17024         Context.setBOOLDecl(TD);
17025     }
17026   }
17027   if (Context.getBOOLDecl())
17028     BoolT = Context.getBOOLType();
17029   return new (Context)
17030       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
17031 }
17032 
17033 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
17034     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
17035     SourceLocation RParen) {
17036 
17037   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
17038 
17039   auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
17040     return Spec.getPlatform() == Platform;
17041   });
17042 
17043   VersionTuple Version;
17044   if (Spec != AvailSpecs.end())
17045     Version = Spec->getVersion();
17046 
17047   // The use of `@available` in the enclosing function should be analyzed to
17048   // warn when it's used inappropriately (i.e. not if(@available)).
17049   if (getCurFunctionOrMethodDecl())
17050     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
17051   else if (getCurBlock() || getCurLambda())
17052     getCurFunction()->HasPotentialAvailabilityViolations = true;
17053 
17054   return new (Context)
17055       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
17056 }
17057