1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/FixedPoint.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/Overload.h"
42 #include "clang/Sema/ParsedTemplate.h"
43 #include "clang/Sema/Scope.h"
44 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/SemaFixItUtils.h"
46 #include "clang/Sema/SemaInternal.h"
47 #include "clang/Sema/Template.h"
48 #include "llvm/Support/ConvertUTF.h"
49 using namespace clang;
50 using namespace sema;
51 
52 /// Determine whether the use of this declaration is valid, without
53 /// emitting diagnostics.
54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
55   // See if this is an auto-typed variable whose initializer we are parsing.
56   if (ParsingInitForAutoVars.count(D))
57     return false;
58 
59   // See if this is a deleted function.
60   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
61     if (FD->isDeleted())
62       return false;
63 
64     // If the function has a deduced return type, and we can't deduce it,
65     // then we can't use it either.
66     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
67         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
68       return false;
69   }
70 
71   // See if this function is unavailable.
72   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
73       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
74     return false;
75 
76   return true;
77 }
78 
79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
80   // Warn if this is used but marked unused.
81   if (const auto *A = D->getAttr<UnusedAttr>()) {
82     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
83     // should diagnose them.
84     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
85         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
86       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
87       if (DC && !DC->hasAttr<UnusedAttr>())
88         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
89     }
90   }
91 }
92 
93 /// Emit a note explaining that this function is deleted.
94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
95   assert(Decl->isDeleted());
96 
97   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
98 
99   if (Method && Method->isDeleted() && Method->isDefaulted()) {
100     // If the method was explicitly defaulted, point at that declaration.
101     if (!Method->isImplicit())
102       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
103 
104     // Try to diagnose why this special member function was implicitly
105     // deleted. This might fail, if that reason no longer applies.
106     CXXSpecialMember CSM = getSpecialMember(Method);
107     if (CSM != CXXInvalid)
108       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
109 
110     return;
111   }
112 
113   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
114   if (Ctor && Ctor->isInheritingConstructor())
115     return NoteDeletedInheritingConstructor(Ctor);
116 
117   Diag(Decl->getLocation(), diag::note_availability_specified_here)
118     << Decl << true;
119 }
120 
121 /// Determine whether a FunctionDecl was ever declared with an
122 /// explicit storage class.
123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
124   for (auto I : D->redecls()) {
125     if (I->getStorageClass() != SC_None)
126       return true;
127   }
128   return false;
129 }
130 
131 /// Check whether we're in an extern inline function and referring to a
132 /// variable or function with internal linkage (C11 6.7.4p3).
133 ///
134 /// This is only a warning because we used to silently accept this code, but
135 /// in many cases it will not behave correctly. This is not enabled in C++ mode
136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
137 /// and so while there may still be user mistakes, most of the time we can't
138 /// prove that there are errors.
139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
140                                                       const NamedDecl *D,
141                                                       SourceLocation Loc) {
142   // This is disabled under C++; there are too many ways for this to fire in
143   // contexts where the warning is a false positive, or where it is technically
144   // correct but benign.
145   if (S.getLangOpts().CPlusPlus)
146     return;
147 
148   // Check if this is an inlined function or method.
149   FunctionDecl *Current = S.getCurFunctionDecl();
150   if (!Current)
151     return;
152   if (!Current->isInlined())
153     return;
154   if (!Current->isExternallyVisible())
155     return;
156 
157   // Check if the decl has internal linkage.
158   if (D->getFormalLinkage() != InternalLinkage)
159     return;
160 
161   // Downgrade from ExtWarn to Extension if
162   //  (1) the supposedly external inline function is in the main file,
163   //      and probably won't be included anywhere else.
164   //  (2) the thing we're referencing is a pure function.
165   //  (3) the thing we're referencing is another inline function.
166   // This last can give us false negatives, but it's better than warning on
167   // wrappers for simple C library functions.
168   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
169   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
170   if (!DowngradeWarning && UsedFn)
171     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
172 
173   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
174                                : diag::ext_internal_in_extern_inline)
175     << /*IsVar=*/!UsedFn << D;
176 
177   S.MaybeSuggestAddingStaticToDecl(Current);
178 
179   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
180       << D;
181 }
182 
183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
184   const FunctionDecl *First = Cur->getFirstDecl();
185 
186   // Suggest "static" on the function, if possible.
187   if (!hasAnyExplicitStorageClass(First)) {
188     SourceLocation DeclBegin = First->getSourceRange().getBegin();
189     Diag(DeclBegin, diag::note_convert_inline_to_static)
190       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
191   }
192 }
193 
194 /// Determine whether the use of this declaration is valid, and
195 /// emit any corresponding diagnostics.
196 ///
197 /// This routine diagnoses various problems with referencing
198 /// declarations that can occur when using a declaration. For example,
199 /// it might warn if a deprecated or unavailable declaration is being
200 /// used, or produce an error (and return true) if a C++0x deleted
201 /// function is being used.
202 ///
203 /// \returns true if there was an error (this declaration cannot be
204 /// referenced), false otherwise.
205 ///
206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
207                              const ObjCInterfaceDecl *UnknownObjCClass,
208                              bool ObjCPropertyAccess,
209                              bool AvoidPartialAvailabilityChecks,
210                              ObjCInterfaceDecl *ClassReceiver) {
211   SourceLocation Loc = Locs.front();
212   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
213     // If there were any diagnostics suppressed by template argument deduction,
214     // emit them now.
215     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
216     if (Pos != SuppressedDiagnostics.end()) {
217       for (const PartialDiagnosticAt &Suppressed : Pos->second)
218         Diag(Suppressed.first, Suppressed.second);
219 
220       // Clear out the list of suppressed diagnostics, so that we don't emit
221       // them again for this specialization. However, we don't obsolete this
222       // entry from the table, because we want to avoid ever emitting these
223       // diagnostics again.
224       Pos->second.clear();
225     }
226 
227     // C++ [basic.start.main]p3:
228     //   The function 'main' shall not be used within a program.
229     if (cast<FunctionDecl>(D)->isMain())
230       Diag(Loc, diag::ext_main_used);
231   }
232 
233   // See if this is an auto-typed variable whose initializer we are parsing.
234   if (ParsingInitForAutoVars.count(D)) {
235     if (isa<BindingDecl>(D)) {
236       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
237         << D->getDeclName();
238     } else {
239       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
240         << D->getDeclName() << cast<VarDecl>(D)->getType();
241     }
242     return true;
243   }
244 
245   // See if this is a deleted function.
246   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
247     if (FD->isDeleted()) {
248       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
249       if (Ctor && Ctor->isInheritingConstructor())
250         Diag(Loc, diag::err_deleted_inherited_ctor_use)
251             << Ctor->getParent()
252             << Ctor->getInheritedConstructor().getConstructor()->getParent();
253       else
254         Diag(Loc, diag::err_deleted_function_use);
255       NoteDeletedFunction(FD);
256       return true;
257     }
258 
259     // If the function has a deduced return type, and we can't deduce it,
260     // then we can't use it either.
261     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
262         DeduceReturnType(FD, Loc))
263       return true;
264 
265     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
266       return true;
267   }
268 
269   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
270     // Lambdas are only default-constructible or assignable in C++2a onwards.
271     if (MD->getParent()->isLambda() &&
272         ((isa<CXXConstructorDecl>(MD) &&
273           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
274          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
275       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
276         << !isa<CXXConstructorDecl>(MD);
277     }
278   }
279 
280   auto getReferencedObjCProp = [](const NamedDecl *D) ->
281                                       const ObjCPropertyDecl * {
282     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
283       return MD->findPropertyDecl();
284     return nullptr;
285   };
286   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
287     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
288       return true;
289   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
290       return true;
291   }
292 
293   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
294   // Only the variables omp_in and omp_out are allowed in the combiner.
295   // Only the variables omp_priv and omp_orig are allowed in the
296   // initializer-clause.
297   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
298   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
299       isa<VarDecl>(D)) {
300     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
301         << getCurFunction()->HasOMPDeclareReductionCombiner;
302     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
303     return true;
304   }
305 
306   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
307                              AvoidPartialAvailabilityChecks, ClassReceiver);
308 
309   DiagnoseUnusedOfDecl(*this, D, Loc);
310 
311   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
312 
313   return false;
314 }
315 
316 /// Retrieve the message suffix that should be added to a
317 /// diagnostic complaining about the given function being deleted or
318 /// unavailable.
319 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
320   std::string Message;
321   if (FD->getAvailability(&Message))
322     return ": " + Message;
323 
324   return std::string();
325 }
326 
327 /// DiagnoseSentinelCalls - This routine checks whether a call or
328 /// message-send is to a declaration with the sentinel attribute, and
329 /// if so, it checks that the requirements of the sentinel are
330 /// satisfied.
331 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
332                                  ArrayRef<Expr *> Args) {
333   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
334   if (!attr)
335     return;
336 
337   // The number of formal parameters of the declaration.
338   unsigned numFormalParams;
339 
340   // The kind of declaration.  This is also an index into a %select in
341   // the diagnostic.
342   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
343 
344   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
345     numFormalParams = MD->param_size();
346     calleeType = CT_Method;
347   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
348     numFormalParams = FD->param_size();
349     calleeType = CT_Function;
350   } else if (isa<VarDecl>(D)) {
351     QualType type = cast<ValueDecl>(D)->getType();
352     const FunctionType *fn = nullptr;
353     if (const PointerType *ptr = type->getAs<PointerType>()) {
354       fn = ptr->getPointeeType()->getAs<FunctionType>();
355       if (!fn) return;
356       calleeType = CT_Function;
357     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
358       fn = ptr->getPointeeType()->castAs<FunctionType>();
359       calleeType = CT_Block;
360     } else {
361       return;
362     }
363 
364     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
365       numFormalParams = proto->getNumParams();
366     } else {
367       numFormalParams = 0;
368     }
369   } else {
370     return;
371   }
372 
373   // "nullPos" is the number of formal parameters at the end which
374   // effectively count as part of the variadic arguments.  This is
375   // useful if you would prefer to not have *any* formal parameters,
376   // but the language forces you to have at least one.
377   unsigned nullPos = attr->getNullPos();
378   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
379   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
380 
381   // The number of arguments which should follow the sentinel.
382   unsigned numArgsAfterSentinel = attr->getSentinel();
383 
384   // If there aren't enough arguments for all the formal parameters,
385   // the sentinel, and the args after the sentinel, complain.
386   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
387     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
388     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
389     return;
390   }
391 
392   // Otherwise, find the sentinel expression.
393   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
394   if (!sentinelExpr) return;
395   if (sentinelExpr->isValueDependent()) return;
396   if (Context.isSentinelNullExpr(sentinelExpr)) return;
397 
398   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
399   // or 'NULL' if those are actually defined in the context.  Only use
400   // 'nil' for ObjC methods, where it's much more likely that the
401   // variadic arguments form a list of object pointers.
402   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
403   std::string NullValue;
404   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
405     NullValue = "nil";
406   else if (getLangOpts().CPlusPlus11)
407     NullValue = "nullptr";
408   else if (PP.isMacroDefined("NULL"))
409     NullValue = "NULL";
410   else
411     NullValue = "(void*) 0";
412 
413   if (MissingNilLoc.isInvalid())
414     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
415   else
416     Diag(MissingNilLoc, diag::warn_missing_sentinel)
417       << int(calleeType)
418       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
419   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
420 }
421 
422 SourceRange Sema::getExprRange(Expr *E) const {
423   return E ? E->getSourceRange() : SourceRange();
424 }
425 
426 //===----------------------------------------------------------------------===//
427 //  Standard Promotions and Conversions
428 //===----------------------------------------------------------------------===//
429 
430 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
431 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
432   // Handle any placeholder expressions which made it here.
433   if (E->getType()->isPlaceholderType()) {
434     ExprResult result = CheckPlaceholderExpr(E);
435     if (result.isInvalid()) return ExprError();
436     E = result.get();
437   }
438 
439   QualType Ty = E->getType();
440   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
441 
442   if (Ty->isFunctionType()) {
443     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
444       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
445         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
446           return ExprError();
447 
448     E = ImpCastExprToType(E, Context.getPointerType(Ty),
449                           CK_FunctionToPointerDecay).get();
450   } else if (Ty->isArrayType()) {
451     // In C90 mode, arrays only promote to pointers if the array expression is
452     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
453     // type 'array of type' is converted to an expression that has type 'pointer
454     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
455     // that has type 'array of type' ...".  The relevant change is "an lvalue"
456     // (C90) to "an expression" (C99).
457     //
458     // C++ 4.2p1:
459     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
460     // T" can be converted to an rvalue of type "pointer to T".
461     //
462     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
463       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
464                             CK_ArrayToPointerDecay).get();
465   }
466   return E;
467 }
468 
469 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
470   // Check to see if we are dereferencing a null pointer.  If so,
471   // and if not volatile-qualified, this is undefined behavior that the
472   // optimizer will delete, so warn about it.  People sometimes try to use this
473   // to get a deterministic trap and are surprised by clang's behavior.  This
474   // only handles the pattern "*null", which is a very syntactic check.
475   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
476     if (UO->getOpcode() == UO_Deref &&
477         UO->getSubExpr()->IgnoreParenCasts()->
478           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
479         !UO->getType().isVolatileQualified()) {
480     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
481                           S.PDiag(diag::warn_indirection_through_null)
482                             << UO->getSubExpr()->getSourceRange());
483     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
484                         S.PDiag(diag::note_indirection_through_null));
485   }
486 }
487 
488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
489                                     SourceLocation AssignLoc,
490                                     const Expr* RHS) {
491   const ObjCIvarDecl *IV = OIRE->getDecl();
492   if (!IV)
493     return;
494 
495   DeclarationName MemberName = IV->getDeclName();
496   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
497   if (!Member || !Member->isStr("isa"))
498     return;
499 
500   const Expr *Base = OIRE->getBase();
501   QualType BaseType = Base->getType();
502   if (OIRE->isArrow())
503     BaseType = BaseType->getPointeeType();
504   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
505     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
506       ObjCInterfaceDecl *ClassDeclared = nullptr;
507       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
508       if (!ClassDeclared->getSuperClass()
509           && (*ClassDeclared->ivar_begin()) == IV) {
510         if (RHS) {
511           NamedDecl *ObjectSetClass =
512             S.LookupSingleName(S.TUScope,
513                                &S.Context.Idents.get("object_setClass"),
514                                SourceLocation(), S.LookupOrdinaryName);
515           if (ObjectSetClass) {
516             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
517             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
518                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
519                                               "object_setClass(")
520                 << FixItHint::CreateReplacement(
521                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
522                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
523           }
524           else
525             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
526         } else {
527           NamedDecl *ObjectGetClass =
528             S.LookupSingleName(S.TUScope,
529                                &S.Context.Idents.get("object_getClass"),
530                                SourceLocation(), S.LookupOrdinaryName);
531           if (ObjectGetClass)
532             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
533                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
534                                               "object_getClass(")
535                 << FixItHint::CreateReplacement(
536                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
537           else
538             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
539         }
540         S.Diag(IV->getLocation(), diag::note_ivar_decl);
541       }
542     }
543 }
544 
545 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
546   // Handle any placeholder expressions which made it here.
547   if (E->getType()->isPlaceholderType()) {
548     ExprResult result = CheckPlaceholderExpr(E);
549     if (result.isInvalid()) return ExprError();
550     E = result.get();
551   }
552 
553   // C++ [conv.lval]p1:
554   //   A glvalue of a non-function, non-array type T can be
555   //   converted to a prvalue.
556   if (!E->isGLValue()) return E;
557 
558   QualType T = E->getType();
559   assert(!T.isNull() && "r-value conversion on typeless expression?");
560 
561   // We don't want to throw lvalue-to-rvalue casts on top of
562   // expressions of certain types in C++.
563   if (getLangOpts().CPlusPlus &&
564       (E->getType() == Context.OverloadTy ||
565        T->isDependentType() ||
566        T->isRecordType()))
567     return E;
568 
569   // The C standard is actually really unclear on this point, and
570   // DR106 tells us what the result should be but not why.  It's
571   // generally best to say that void types just doesn't undergo
572   // lvalue-to-rvalue at all.  Note that expressions of unqualified
573   // 'void' type are never l-values, but qualified void can be.
574   if (T->isVoidType())
575     return E;
576 
577   // OpenCL usually rejects direct accesses to values of 'half' type.
578   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
579       T->isHalfType()) {
580     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
581       << 0 << T;
582     return ExprError();
583   }
584 
585   CheckForNullPointerDereference(*this, E);
586   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
587     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
588                                      &Context.Idents.get("object_getClass"),
589                                      SourceLocation(), LookupOrdinaryName);
590     if (ObjectGetClass)
591       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
592           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
593           << FixItHint::CreateReplacement(
594                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
595     else
596       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
597   }
598   else if (const ObjCIvarRefExpr *OIRE =
599             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
600     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
601 
602   // C++ [conv.lval]p1:
603   //   [...] If T is a non-class type, the type of the prvalue is the
604   //   cv-unqualified version of T. Otherwise, the type of the
605   //   rvalue is T.
606   //
607   // C99 6.3.2.1p2:
608   //   If the lvalue has qualified type, the value has the unqualified
609   //   version of the type of the lvalue; otherwise, the value has the
610   //   type of the lvalue.
611   if (T.hasQualifiers())
612     T = T.getUnqualifiedType();
613 
614   // Under the MS ABI, lock down the inheritance model now.
615   if (T->isMemberPointerType() &&
616       Context.getTargetInfo().getCXXABI().isMicrosoft())
617     (void)isCompleteType(E->getExprLoc(), T);
618 
619   UpdateMarkingForLValueToRValue(E);
620 
621   // Loading a __weak object implicitly retains the value, so we need a cleanup to
622   // balance that.
623   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
624     Cleanup.setExprNeedsCleanups(true);
625 
626   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
627                                             nullptr, VK_RValue);
628 
629   // C11 6.3.2.1p2:
630   //   ... if the lvalue has atomic type, the value has the non-atomic version
631   //   of the type of the lvalue ...
632   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
633     T = Atomic->getValueType().getUnqualifiedType();
634     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
635                                    nullptr, VK_RValue);
636   }
637 
638   return Res;
639 }
640 
641 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
642   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
643   if (Res.isInvalid())
644     return ExprError();
645   Res = DefaultLvalueConversion(Res.get());
646   if (Res.isInvalid())
647     return ExprError();
648   return Res;
649 }
650 
651 /// CallExprUnaryConversions - a special case of an unary conversion
652 /// performed on a function designator of a call expression.
653 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
654   QualType Ty = E->getType();
655   ExprResult Res = E;
656   // Only do implicit cast for a function type, but not for a pointer
657   // to function type.
658   if (Ty->isFunctionType()) {
659     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
660                             CK_FunctionToPointerDecay).get();
661     if (Res.isInvalid())
662       return ExprError();
663   }
664   Res = DefaultLvalueConversion(Res.get());
665   if (Res.isInvalid())
666     return ExprError();
667   return Res.get();
668 }
669 
670 /// UsualUnaryConversions - Performs various conversions that are common to most
671 /// operators (C99 6.3). The conversions of array and function types are
672 /// sometimes suppressed. For example, the array->pointer conversion doesn't
673 /// apply if the array is an argument to the sizeof or address (&) operators.
674 /// In these instances, this routine should *not* be called.
675 ExprResult Sema::UsualUnaryConversions(Expr *E) {
676   // First, convert to an r-value.
677   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
678   if (Res.isInvalid())
679     return ExprError();
680   E = Res.get();
681 
682   QualType Ty = E->getType();
683   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
684 
685   // Half FP have to be promoted to float unless it is natively supported
686   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
687     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
688 
689   // Try to perform integral promotions if the object has a theoretically
690   // promotable type.
691   if (Ty->isIntegralOrUnscopedEnumerationType()) {
692     // C99 6.3.1.1p2:
693     //
694     //   The following may be used in an expression wherever an int or
695     //   unsigned int may be used:
696     //     - an object or expression with an integer type whose integer
697     //       conversion rank is less than or equal to the rank of int
698     //       and unsigned int.
699     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
700     //
701     //   If an int can represent all values of the original type, the
702     //   value is converted to an int; otherwise, it is converted to an
703     //   unsigned int. These are called the integer promotions. All
704     //   other types are unchanged by the integer promotions.
705 
706     QualType PTy = Context.isPromotableBitField(E);
707     if (!PTy.isNull()) {
708       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
709       return E;
710     }
711     if (Ty->isPromotableIntegerType()) {
712       QualType PT = Context.getPromotedIntegerType(Ty);
713       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
714       return E;
715     }
716   }
717   return E;
718 }
719 
720 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
721 /// do not have a prototype. Arguments that have type float or __fp16
722 /// are promoted to double. All other argument types are converted by
723 /// UsualUnaryConversions().
724 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
725   QualType Ty = E->getType();
726   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
727 
728   ExprResult Res = UsualUnaryConversions(E);
729   if (Res.isInvalid())
730     return ExprError();
731   E = Res.get();
732 
733   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
734   // promote to double.
735   // Note that default argument promotion applies only to float (and
736   // half/fp16); it does not apply to _Float16.
737   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
738   if (BTy && (BTy->getKind() == BuiltinType::Half ||
739               BTy->getKind() == BuiltinType::Float)) {
740     if (getLangOpts().OpenCL &&
741         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
742         if (BTy->getKind() == BuiltinType::Half) {
743             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
744         }
745     } else {
746       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
747     }
748   }
749 
750   // C++ performs lvalue-to-rvalue conversion as a default argument
751   // promotion, even on class types, but note:
752   //   C++11 [conv.lval]p2:
753   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
754   //     operand or a subexpression thereof the value contained in the
755   //     referenced object is not accessed. Otherwise, if the glvalue
756   //     has a class type, the conversion copy-initializes a temporary
757   //     of type T from the glvalue and the result of the conversion
758   //     is a prvalue for the temporary.
759   // FIXME: add some way to gate this entire thing for correctness in
760   // potentially potentially evaluated contexts.
761   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
762     ExprResult Temp = PerformCopyInitialization(
763                        InitializedEntity::InitializeTemporary(E->getType()),
764                                                 E->getExprLoc(), E);
765     if (Temp.isInvalid())
766       return ExprError();
767     E = Temp.get();
768   }
769 
770   return E;
771 }
772 
773 /// Determine the degree of POD-ness for an expression.
774 /// Incomplete types are considered POD, since this check can be performed
775 /// when we're in an unevaluated context.
776 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
777   if (Ty->isIncompleteType()) {
778     // C++11 [expr.call]p7:
779     //   After these conversions, if the argument does not have arithmetic,
780     //   enumeration, pointer, pointer to member, or class type, the program
781     //   is ill-formed.
782     //
783     // Since we've already performed array-to-pointer and function-to-pointer
784     // decay, the only such type in C++ is cv void. This also handles
785     // initializer lists as variadic arguments.
786     if (Ty->isVoidType())
787       return VAK_Invalid;
788 
789     if (Ty->isObjCObjectType())
790       return VAK_Invalid;
791     return VAK_Valid;
792   }
793 
794   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
795     return VAK_Invalid;
796 
797   if (Ty.isCXX98PODType(Context))
798     return VAK_Valid;
799 
800   // C++11 [expr.call]p7:
801   //   Passing a potentially-evaluated argument of class type (Clause 9)
802   //   having a non-trivial copy constructor, a non-trivial move constructor,
803   //   or a non-trivial destructor, with no corresponding parameter,
804   //   is conditionally-supported with implementation-defined semantics.
805   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
806     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
807       if (!Record->hasNonTrivialCopyConstructor() &&
808           !Record->hasNonTrivialMoveConstructor() &&
809           !Record->hasNonTrivialDestructor())
810         return VAK_ValidInCXX11;
811 
812   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
813     return VAK_Valid;
814 
815   if (Ty->isObjCObjectType())
816     return VAK_Invalid;
817 
818   if (getLangOpts().MSVCCompat)
819     return VAK_MSVCUndefined;
820 
821   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
822   // permitted to reject them. We should consider doing so.
823   return VAK_Undefined;
824 }
825 
826 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
827   // Don't allow one to pass an Objective-C interface to a vararg.
828   const QualType &Ty = E->getType();
829   VarArgKind VAK = isValidVarArgType(Ty);
830 
831   // Complain about passing non-POD types through varargs.
832   switch (VAK) {
833   case VAK_ValidInCXX11:
834     DiagRuntimeBehavior(
835         E->getBeginLoc(), nullptr,
836         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
837     LLVM_FALLTHROUGH;
838   case VAK_Valid:
839     if (Ty->isRecordType()) {
840       // This is unlikely to be what the user intended. If the class has a
841       // 'c_str' member function, the user probably meant to call that.
842       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
843                           PDiag(diag::warn_pass_class_arg_to_vararg)
844                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
845     }
846     break;
847 
848   case VAK_Undefined:
849   case VAK_MSVCUndefined:
850     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
851                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
852                             << getLangOpts().CPlusPlus11 << Ty << CT);
853     break;
854 
855   case VAK_Invalid:
856     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
857       Diag(E->getBeginLoc(),
858            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
859           << Ty << CT;
860     else if (Ty->isObjCObjectType())
861       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
862                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
863                               << Ty << CT);
864     else
865       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
866           << isa<InitListExpr>(E) << Ty << CT;
867     break;
868   }
869 }
870 
871 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
872 /// will create a trap if the resulting type is not a POD type.
873 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
874                                                   FunctionDecl *FDecl) {
875   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
876     // Strip the unbridged-cast placeholder expression off, if applicable.
877     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
878         (CT == VariadicMethod ||
879          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
880       E = stripARCUnbridgedCast(E);
881 
882     // Otherwise, do normal placeholder checking.
883     } else {
884       ExprResult ExprRes = CheckPlaceholderExpr(E);
885       if (ExprRes.isInvalid())
886         return ExprError();
887       E = ExprRes.get();
888     }
889   }
890 
891   ExprResult ExprRes = DefaultArgumentPromotion(E);
892   if (ExprRes.isInvalid())
893     return ExprError();
894   E = ExprRes.get();
895 
896   // Diagnostics regarding non-POD argument types are
897   // emitted along with format string checking in Sema::CheckFunctionCall().
898   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
899     // Turn this into a trap.
900     CXXScopeSpec SS;
901     SourceLocation TemplateKWLoc;
902     UnqualifiedId Name;
903     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
904                        E->getBeginLoc());
905     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
906                                           Name, true, false);
907     if (TrapFn.isInvalid())
908       return ExprError();
909 
910     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
911                                     None, E->getEndLoc());
912     if (Call.isInvalid())
913       return ExprError();
914 
915     ExprResult Comma =
916         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
917     if (Comma.isInvalid())
918       return ExprError();
919     return Comma.get();
920   }
921 
922   if (!getLangOpts().CPlusPlus &&
923       RequireCompleteType(E->getExprLoc(), E->getType(),
924                           diag::err_call_incomplete_argument))
925     return ExprError();
926 
927   return E;
928 }
929 
930 /// Converts an integer to complex float type.  Helper function of
931 /// UsualArithmeticConversions()
932 ///
933 /// \return false if the integer expression is an integer type and is
934 /// successfully converted to the complex type.
935 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
936                                                   ExprResult &ComplexExpr,
937                                                   QualType IntTy,
938                                                   QualType ComplexTy,
939                                                   bool SkipCast) {
940   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
941   if (SkipCast) return false;
942   if (IntTy->isIntegerType()) {
943     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
944     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
945     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
946                                   CK_FloatingRealToComplex);
947   } else {
948     assert(IntTy->isComplexIntegerType());
949     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
950                                   CK_IntegralComplexToFloatingComplex);
951   }
952   return false;
953 }
954 
955 /// Handle arithmetic conversion with complex types.  Helper function of
956 /// UsualArithmeticConversions()
957 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
958                                              ExprResult &RHS, QualType LHSType,
959                                              QualType RHSType,
960                                              bool IsCompAssign) {
961   // if we have an integer operand, the result is the complex type.
962   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
963                                              /*skipCast*/false))
964     return LHSType;
965   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
966                                              /*skipCast*/IsCompAssign))
967     return RHSType;
968 
969   // This handles complex/complex, complex/float, or float/complex.
970   // When both operands are complex, the shorter operand is converted to the
971   // type of the longer, and that is the type of the result. This corresponds
972   // to what is done when combining two real floating-point operands.
973   // The fun begins when size promotion occur across type domains.
974   // From H&S 6.3.4: When one operand is complex and the other is a real
975   // floating-point type, the less precise type is converted, within it's
976   // real or complex domain, to the precision of the other type. For example,
977   // when combining a "long double" with a "double _Complex", the
978   // "double _Complex" is promoted to "long double _Complex".
979 
980   // Compute the rank of the two types, regardless of whether they are complex.
981   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
982 
983   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
984   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
985   QualType LHSElementType =
986       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
987   QualType RHSElementType =
988       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
989 
990   QualType ResultType = S.Context.getComplexType(LHSElementType);
991   if (Order < 0) {
992     // Promote the precision of the LHS if not an assignment.
993     ResultType = S.Context.getComplexType(RHSElementType);
994     if (!IsCompAssign) {
995       if (LHSComplexType)
996         LHS =
997             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
998       else
999         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1000     }
1001   } else if (Order > 0) {
1002     // Promote the precision of the RHS.
1003     if (RHSComplexType)
1004       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1005     else
1006       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1007   }
1008   return ResultType;
1009 }
1010 
1011 /// Handle arithmetic conversion from integer to float.  Helper function
1012 /// of UsualArithmeticConversions()
1013 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1014                                            ExprResult &IntExpr,
1015                                            QualType FloatTy, QualType IntTy,
1016                                            bool ConvertFloat, bool ConvertInt) {
1017   if (IntTy->isIntegerType()) {
1018     if (ConvertInt)
1019       // Convert intExpr to the lhs floating point type.
1020       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1021                                     CK_IntegralToFloating);
1022     return FloatTy;
1023   }
1024 
1025   // Convert both sides to the appropriate complex float.
1026   assert(IntTy->isComplexIntegerType());
1027   QualType result = S.Context.getComplexType(FloatTy);
1028 
1029   // _Complex int -> _Complex float
1030   if (ConvertInt)
1031     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1032                                   CK_IntegralComplexToFloatingComplex);
1033 
1034   // float -> _Complex float
1035   if (ConvertFloat)
1036     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1037                                     CK_FloatingRealToComplex);
1038 
1039   return result;
1040 }
1041 
1042 /// Handle arithmethic conversion with floating point types.  Helper
1043 /// function of UsualArithmeticConversions()
1044 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1045                                       ExprResult &RHS, QualType LHSType,
1046                                       QualType RHSType, bool IsCompAssign) {
1047   bool LHSFloat = LHSType->isRealFloatingType();
1048   bool RHSFloat = RHSType->isRealFloatingType();
1049 
1050   // If we have two real floating types, convert the smaller operand
1051   // to the bigger result.
1052   if (LHSFloat && RHSFloat) {
1053     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1054     if (order > 0) {
1055       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1056       return LHSType;
1057     }
1058 
1059     assert(order < 0 && "illegal float comparison");
1060     if (!IsCompAssign)
1061       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1062     return RHSType;
1063   }
1064 
1065   if (LHSFloat) {
1066     // Half FP has to be promoted to float unless it is natively supported
1067     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1068       LHSType = S.Context.FloatTy;
1069 
1070     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1071                                       /*convertFloat=*/!IsCompAssign,
1072                                       /*convertInt=*/ true);
1073   }
1074   assert(RHSFloat);
1075   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1076                                     /*convertInt=*/ true,
1077                                     /*convertFloat=*/!IsCompAssign);
1078 }
1079 
1080 /// Diagnose attempts to convert between __float128 and long double if
1081 /// there is no support for such conversion. Helper function of
1082 /// UsualArithmeticConversions().
1083 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1084                                       QualType RHSType) {
1085   /*  No issue converting if at least one of the types is not a floating point
1086       type or the two types have the same rank.
1087   */
1088   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1089       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1090     return false;
1091 
1092   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1093          "The remaining types must be floating point types.");
1094 
1095   auto *LHSComplex = LHSType->getAs<ComplexType>();
1096   auto *RHSComplex = RHSType->getAs<ComplexType>();
1097 
1098   QualType LHSElemType = LHSComplex ?
1099     LHSComplex->getElementType() : LHSType;
1100   QualType RHSElemType = RHSComplex ?
1101     RHSComplex->getElementType() : RHSType;
1102 
1103   // No issue if the two types have the same representation
1104   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1105       &S.Context.getFloatTypeSemantics(RHSElemType))
1106     return false;
1107 
1108   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1109                                 RHSElemType == S.Context.LongDoubleTy);
1110   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1111                             RHSElemType == S.Context.Float128Ty);
1112 
1113   // We've handled the situation where __float128 and long double have the same
1114   // representation. We allow all conversions for all possible long double types
1115   // except PPC's double double.
1116   return Float128AndLongDouble &&
1117     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1118      &llvm::APFloat::PPCDoubleDouble());
1119 }
1120 
1121 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1122 
1123 namespace {
1124 /// These helper callbacks are placed in an anonymous namespace to
1125 /// permit their use as function template parameters.
1126 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1127   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1128 }
1129 
1130 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1131   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1132                              CK_IntegralComplexCast);
1133 }
1134 }
1135 
1136 /// Handle integer arithmetic conversions.  Helper function of
1137 /// UsualArithmeticConversions()
1138 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1139 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1140                                         ExprResult &RHS, QualType LHSType,
1141                                         QualType RHSType, bool IsCompAssign) {
1142   // The rules for this case are in C99 6.3.1.8
1143   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1144   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1145   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1146   if (LHSSigned == RHSSigned) {
1147     // Same signedness; use the higher-ranked type
1148     if (order >= 0) {
1149       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1150       return LHSType;
1151     } else if (!IsCompAssign)
1152       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1153     return RHSType;
1154   } else if (order != (LHSSigned ? 1 : -1)) {
1155     // The unsigned type has greater than or equal rank to the
1156     // signed type, so use the unsigned type
1157     if (RHSSigned) {
1158       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159       return LHSType;
1160     } else if (!IsCompAssign)
1161       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162     return RHSType;
1163   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1164     // The two types are different widths; if we are here, that
1165     // means the signed type is larger than the unsigned type, so
1166     // use the signed type.
1167     if (LHSSigned) {
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 {
1174     // The signed type is higher-ranked than the unsigned type,
1175     // but isn't actually any bigger (like unsigned int and long
1176     // on most 32-bit systems).  Use the unsigned type corresponding
1177     // to the signed type.
1178     QualType result =
1179       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1180     RHS = (*doRHSCast)(S, RHS.get(), result);
1181     if (!IsCompAssign)
1182       LHS = (*doLHSCast)(S, LHS.get(), result);
1183     return result;
1184   }
1185 }
1186 
1187 /// Handle conversions with GCC complex int extension.  Helper function
1188 /// of UsualArithmeticConversions()
1189 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1190                                            ExprResult &RHS, QualType LHSType,
1191                                            QualType RHSType,
1192                                            bool IsCompAssign) {
1193   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1194   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1195 
1196   if (LHSComplexInt && RHSComplexInt) {
1197     QualType LHSEltType = LHSComplexInt->getElementType();
1198     QualType RHSEltType = RHSComplexInt->getElementType();
1199     QualType ScalarType =
1200       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1201         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1202 
1203     return S.Context.getComplexType(ScalarType);
1204   }
1205 
1206   if (LHSComplexInt) {
1207     QualType LHSEltType = LHSComplexInt->getElementType();
1208     QualType ScalarType =
1209       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1210         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1211     QualType ComplexType = S.Context.getComplexType(ScalarType);
1212     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1213                               CK_IntegralRealToComplex);
1214 
1215     return ComplexType;
1216   }
1217 
1218   assert(RHSComplexInt);
1219 
1220   QualType RHSEltType = RHSComplexInt->getElementType();
1221   QualType ScalarType =
1222     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1223       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1224   QualType ComplexType = S.Context.getComplexType(ScalarType);
1225 
1226   if (!IsCompAssign)
1227     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1228                               CK_IntegralRealToComplex);
1229   return ComplexType;
1230 }
1231 
1232 /// UsualArithmeticConversions - Performs various conversions that are common to
1233 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1234 /// routine returns the first non-arithmetic type found. The client is
1235 /// responsible for emitting appropriate error diagnostics.
1236 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1237                                           bool IsCompAssign) {
1238   if (!IsCompAssign) {
1239     LHS = UsualUnaryConversions(LHS.get());
1240     if (LHS.isInvalid())
1241       return QualType();
1242   }
1243 
1244   RHS = UsualUnaryConversions(RHS.get());
1245   if (RHS.isInvalid())
1246     return QualType();
1247 
1248   // For conversion purposes, we ignore any qualifiers.
1249   // For example, "const float" and "float" are equivalent.
1250   QualType LHSType =
1251     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1252   QualType RHSType =
1253     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1254 
1255   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1256   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1257     LHSType = AtomicLHS->getValueType();
1258 
1259   // If both types are identical, no conversion is needed.
1260   if (LHSType == RHSType)
1261     return LHSType;
1262 
1263   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1264   // The caller can deal with this (e.g. pointer + int).
1265   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1266     return QualType();
1267 
1268   // Apply unary and bitfield promotions to the LHS's type.
1269   QualType LHSUnpromotedType = LHSType;
1270   if (LHSType->isPromotableIntegerType())
1271     LHSType = Context.getPromotedIntegerType(LHSType);
1272   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1273   if (!LHSBitfieldPromoteTy.isNull())
1274     LHSType = LHSBitfieldPromoteTy;
1275   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1276     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1277 
1278   // If both types are identical, no conversion is needed.
1279   if (LHSType == RHSType)
1280     return LHSType;
1281 
1282   // At this point, we have two different arithmetic types.
1283 
1284   // Diagnose attempts to convert between __float128 and long double where
1285   // such conversions currently can't be handled.
1286   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1287     return QualType();
1288 
1289   // Handle complex types first (C99 6.3.1.8p1).
1290   if (LHSType->isComplexType() || RHSType->isComplexType())
1291     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1292                                         IsCompAssign);
1293 
1294   // Now handle "real" floating types (i.e. float, double, long double).
1295   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1296     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1297                                  IsCompAssign);
1298 
1299   // Handle GCC complex int extension.
1300   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1301     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1302                                       IsCompAssign);
1303 
1304   // Finally, we have two differing integer types.
1305   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1306            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1307 }
1308 
1309 
1310 //===----------------------------------------------------------------------===//
1311 //  Semantic Analysis for various Expression Types
1312 //===----------------------------------------------------------------------===//
1313 
1314 
1315 ExprResult
1316 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1317                                 SourceLocation DefaultLoc,
1318                                 SourceLocation RParenLoc,
1319                                 Expr *ControllingExpr,
1320                                 ArrayRef<ParsedType> ArgTypes,
1321                                 ArrayRef<Expr *> ArgExprs) {
1322   unsigned NumAssocs = ArgTypes.size();
1323   assert(NumAssocs == ArgExprs.size());
1324 
1325   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1326   for (unsigned i = 0; i < NumAssocs; ++i) {
1327     if (ArgTypes[i])
1328       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1329     else
1330       Types[i] = nullptr;
1331   }
1332 
1333   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1334                                              ControllingExpr,
1335                                              llvm::makeArrayRef(Types, NumAssocs),
1336                                              ArgExprs);
1337   delete [] Types;
1338   return ER;
1339 }
1340 
1341 ExprResult
1342 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1343                                  SourceLocation DefaultLoc,
1344                                  SourceLocation RParenLoc,
1345                                  Expr *ControllingExpr,
1346                                  ArrayRef<TypeSourceInfo *> Types,
1347                                  ArrayRef<Expr *> Exprs) {
1348   unsigned NumAssocs = Types.size();
1349   assert(NumAssocs == Exprs.size());
1350 
1351   // Decay and strip qualifiers for the controlling expression type, and handle
1352   // placeholder type replacement. See committee discussion from WG14 DR423.
1353   {
1354     EnterExpressionEvaluationContext Unevaluated(
1355         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1356     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1357     if (R.isInvalid())
1358       return ExprError();
1359     ControllingExpr = R.get();
1360   }
1361 
1362   // The controlling expression is an unevaluated operand, so side effects are
1363   // likely unintended.
1364   if (!inTemplateInstantiation() &&
1365       ControllingExpr->HasSideEffects(Context, false))
1366     Diag(ControllingExpr->getExprLoc(),
1367          diag::warn_side_effects_unevaluated_context);
1368 
1369   bool TypeErrorFound = false,
1370        IsResultDependent = ControllingExpr->isTypeDependent(),
1371        ContainsUnexpandedParameterPack
1372          = ControllingExpr->containsUnexpandedParameterPack();
1373 
1374   for (unsigned i = 0; i < NumAssocs; ++i) {
1375     if (Exprs[i]->containsUnexpandedParameterPack())
1376       ContainsUnexpandedParameterPack = true;
1377 
1378     if (Types[i]) {
1379       if (Types[i]->getType()->containsUnexpandedParameterPack())
1380         ContainsUnexpandedParameterPack = true;
1381 
1382       if (Types[i]->getType()->isDependentType()) {
1383         IsResultDependent = true;
1384       } else {
1385         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1386         // complete object type other than a variably modified type."
1387         unsigned D = 0;
1388         if (Types[i]->getType()->isIncompleteType())
1389           D = diag::err_assoc_type_incomplete;
1390         else if (!Types[i]->getType()->isObjectType())
1391           D = diag::err_assoc_type_nonobject;
1392         else if (Types[i]->getType()->isVariablyModifiedType())
1393           D = diag::err_assoc_type_variably_modified;
1394 
1395         if (D != 0) {
1396           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1397             << Types[i]->getTypeLoc().getSourceRange()
1398             << Types[i]->getType();
1399           TypeErrorFound = true;
1400         }
1401 
1402         // C11 6.5.1.1p2 "No two generic associations in the same generic
1403         // selection shall specify compatible types."
1404         for (unsigned j = i+1; j < NumAssocs; ++j)
1405           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1406               Context.typesAreCompatible(Types[i]->getType(),
1407                                          Types[j]->getType())) {
1408             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1409                  diag::err_assoc_compatible_types)
1410               << Types[j]->getTypeLoc().getSourceRange()
1411               << Types[j]->getType()
1412               << Types[i]->getType();
1413             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1414                  diag::note_compat_assoc)
1415               << Types[i]->getTypeLoc().getSourceRange()
1416               << Types[i]->getType();
1417             TypeErrorFound = true;
1418           }
1419       }
1420     }
1421   }
1422   if (TypeErrorFound)
1423     return ExprError();
1424 
1425   // If we determined that the generic selection is result-dependent, don't
1426   // try to compute the result expression.
1427   if (IsResultDependent)
1428     return new (Context) GenericSelectionExpr(
1429         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1430         ContainsUnexpandedParameterPack);
1431 
1432   SmallVector<unsigned, 1> CompatIndices;
1433   unsigned DefaultIndex = -1U;
1434   for (unsigned i = 0; i < NumAssocs; ++i) {
1435     if (!Types[i])
1436       DefaultIndex = i;
1437     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1438                                         Types[i]->getType()))
1439       CompatIndices.push_back(i);
1440   }
1441 
1442   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1443   // type compatible with at most one of the types named in its generic
1444   // association list."
1445   if (CompatIndices.size() > 1) {
1446     // We strip parens here because the controlling expression is typically
1447     // parenthesized in macro definitions.
1448     ControllingExpr = ControllingExpr->IgnoreParens();
1449     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1450         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1451         << (unsigned)CompatIndices.size();
1452     for (unsigned I : CompatIndices) {
1453       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1454            diag::note_compat_assoc)
1455         << Types[I]->getTypeLoc().getSourceRange()
1456         << Types[I]->getType();
1457     }
1458     return ExprError();
1459   }
1460 
1461   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1462   // its controlling expression shall have type compatible with exactly one of
1463   // the types named in its generic association list."
1464   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1465     // We strip parens here because the controlling expression is typically
1466     // parenthesized in macro definitions.
1467     ControllingExpr = ControllingExpr->IgnoreParens();
1468     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1469         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1470     return ExprError();
1471   }
1472 
1473   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1474   // type name that is compatible with the type of the controlling expression,
1475   // then the result expression of the generic selection is the expression
1476   // in that generic association. Otherwise, the result expression of the
1477   // generic selection is the expression in the default generic association."
1478   unsigned ResultIndex =
1479     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1480 
1481   return new (Context) GenericSelectionExpr(
1482       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1483       ContainsUnexpandedParameterPack, ResultIndex);
1484 }
1485 
1486 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1487 /// location of the token and the offset of the ud-suffix within it.
1488 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1489                                      unsigned Offset) {
1490   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1491                                         S.getLangOpts());
1492 }
1493 
1494 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1495 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1496 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1497                                                  IdentifierInfo *UDSuffix,
1498                                                  SourceLocation UDSuffixLoc,
1499                                                  ArrayRef<Expr*> Args,
1500                                                  SourceLocation LitEndLoc) {
1501   assert(Args.size() <= 2 && "too many arguments for literal operator");
1502 
1503   QualType ArgTy[2];
1504   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1505     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1506     if (ArgTy[ArgIdx]->isArrayType())
1507       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1508   }
1509 
1510   DeclarationName OpName =
1511     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1512   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1513   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1514 
1515   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1516   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1517                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1518                               /*AllowStringTemplate*/ false,
1519                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1520     return ExprError();
1521 
1522   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1523 }
1524 
1525 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1526 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1527 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1528 /// multiple tokens.  However, the common case is that StringToks points to one
1529 /// string.
1530 ///
1531 ExprResult
1532 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1533   assert(!StringToks.empty() && "Must have at least one string!");
1534 
1535   StringLiteralParser Literal(StringToks, PP);
1536   if (Literal.hadError)
1537     return ExprError();
1538 
1539   SmallVector<SourceLocation, 4> StringTokLocs;
1540   for (const Token &Tok : StringToks)
1541     StringTokLocs.push_back(Tok.getLocation());
1542 
1543   QualType CharTy = Context.CharTy;
1544   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1545   if (Literal.isWide()) {
1546     CharTy = Context.getWideCharType();
1547     Kind = StringLiteral::Wide;
1548   } else if (Literal.isUTF8()) {
1549     if (getLangOpts().Char8)
1550       CharTy = Context.Char8Ty;
1551     Kind = StringLiteral::UTF8;
1552   } else if (Literal.isUTF16()) {
1553     CharTy = Context.Char16Ty;
1554     Kind = StringLiteral::UTF16;
1555   } else if (Literal.isUTF32()) {
1556     CharTy = Context.Char32Ty;
1557     Kind = StringLiteral::UTF32;
1558   } else if (Literal.isPascal()) {
1559     CharTy = Context.UnsignedCharTy;
1560   }
1561 
1562   // Warn on initializing an array of char from a u8 string literal; this
1563   // becomes ill-formed in C++2a.
1564   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1565       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1566     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1567 
1568     // Create removals for all 'u8' prefixes in the string literal(s). This
1569     // ensures C++2a compatibility (but may change the program behavior when
1570     // built by non-Clang compilers for which the execution character set is
1571     // not always UTF-8).
1572     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1573     SourceLocation RemovalDiagLoc;
1574     for (const Token &Tok : StringToks) {
1575       if (Tok.getKind() == tok::utf8_string_literal) {
1576         if (RemovalDiagLoc.isInvalid())
1577           RemovalDiagLoc = Tok.getLocation();
1578         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1579             Tok.getLocation(),
1580             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1581                                            getSourceManager(), getLangOpts())));
1582       }
1583     }
1584     Diag(RemovalDiagLoc, RemovalDiag);
1585   }
1586 
1587 
1588   QualType CharTyConst = CharTy;
1589   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1590   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1591     CharTyConst.addConst();
1592 
1593   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1594 
1595   // Get an array type for the string, according to C99 6.4.5.  This includes
1596   // the nul terminator character as well as the string length for pascal
1597   // strings.
1598   QualType StrTy = Context.getConstantArrayType(
1599       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1600       ArrayType::Normal, 0);
1601 
1602   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1603   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1604                                              Kind, Literal.Pascal, StrTy,
1605                                              &StringTokLocs[0],
1606                                              StringTokLocs.size());
1607   if (Literal.getUDSuffix().empty())
1608     return Lit;
1609 
1610   // We're building a user-defined literal.
1611   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1612   SourceLocation UDSuffixLoc =
1613     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1614                    Literal.getUDSuffixOffset());
1615 
1616   // Make sure we're allowed user-defined literals here.
1617   if (!UDLScope)
1618     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1619 
1620   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1621   //   operator "" X (str, len)
1622   QualType SizeType = Context.getSizeType();
1623 
1624   DeclarationName OpName =
1625     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1626   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1627   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1628 
1629   QualType ArgTy[] = {
1630     Context.getArrayDecayedType(StrTy), SizeType
1631   };
1632 
1633   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1634   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1635                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1636                                 /*AllowStringTemplate*/ true,
1637                                 /*DiagnoseMissing*/ true)) {
1638 
1639   case LOLR_Cooked: {
1640     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1641     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1642                                                     StringTokLocs[0]);
1643     Expr *Args[] = { Lit, LenArg };
1644 
1645     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1646   }
1647 
1648   case LOLR_StringTemplate: {
1649     TemplateArgumentListInfo ExplicitArgs;
1650 
1651     unsigned CharBits = Context.getIntWidth(CharTy);
1652     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1653     llvm::APSInt Value(CharBits, CharIsUnsigned);
1654 
1655     TemplateArgument TypeArg(CharTy);
1656     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1657     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1658 
1659     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1660       Value = Lit->getCodeUnit(I);
1661       TemplateArgument Arg(Context, Value, CharTy);
1662       TemplateArgumentLocInfo ArgInfo;
1663       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1664     }
1665     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1666                                     &ExplicitArgs);
1667   }
1668   case LOLR_Raw:
1669   case LOLR_Template:
1670   case LOLR_ErrorNoDiagnostic:
1671     llvm_unreachable("unexpected literal operator lookup result");
1672   case LOLR_Error:
1673     return ExprError();
1674   }
1675   llvm_unreachable("unexpected literal operator lookup result");
1676 }
1677 
1678 ExprResult
1679 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1680                        SourceLocation Loc,
1681                        const CXXScopeSpec *SS) {
1682   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1683   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1684 }
1685 
1686 /// BuildDeclRefExpr - Build an expression that references a
1687 /// declaration that does not require a closure capture.
1688 ExprResult
1689 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1690                        const DeclarationNameInfo &NameInfo,
1691                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1692                        const TemplateArgumentListInfo *TemplateArgs) {
1693   bool RefersToCapturedVariable =
1694       isa<VarDecl>(D) &&
1695       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1696 
1697   DeclRefExpr *E;
1698   if (isa<VarTemplateSpecializationDecl>(D)) {
1699     VarTemplateSpecializationDecl *VarSpec =
1700         cast<VarTemplateSpecializationDecl>(D);
1701 
1702     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1703                                         : NestedNameSpecifierLoc(),
1704                             VarSpec->getTemplateKeywordLoc(), D,
1705                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1706                             FoundD, TemplateArgs);
1707   } else {
1708     assert(!TemplateArgs && "No template arguments for non-variable"
1709                             " template specialization references");
1710     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1711                                         : NestedNameSpecifierLoc(),
1712                             SourceLocation(), D, RefersToCapturedVariable,
1713                             NameInfo, Ty, VK, FoundD);
1714   }
1715 
1716   MarkDeclRefReferenced(E);
1717 
1718   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1719       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1720       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1721     getCurFunction()->recordUseOfWeak(E);
1722 
1723   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1724   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1725     FD = IFD->getAnonField();
1726   if (FD) {
1727     UnusedPrivateFields.remove(FD);
1728     // Just in case we're building an illegal pointer-to-member.
1729     if (FD->isBitField())
1730       E->setObjectKind(OK_BitField);
1731   }
1732 
1733   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1734   // designates a bit-field.
1735   if (auto *BD = dyn_cast<BindingDecl>(D))
1736     if (auto *BE = BD->getBinding())
1737       E->setObjectKind(BE->getObjectKind());
1738 
1739   return E;
1740 }
1741 
1742 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1743 /// possibly a list of template arguments.
1744 ///
1745 /// If this produces template arguments, it is permitted to call
1746 /// DecomposeTemplateName.
1747 ///
1748 /// This actually loses a lot of source location information for
1749 /// non-standard name kinds; we should consider preserving that in
1750 /// some way.
1751 void
1752 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1753                              TemplateArgumentListInfo &Buffer,
1754                              DeclarationNameInfo &NameInfo,
1755                              const TemplateArgumentListInfo *&TemplateArgs) {
1756   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1757     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1758     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1759 
1760     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1761                                        Id.TemplateId->NumArgs);
1762     translateTemplateArguments(TemplateArgsPtr, Buffer);
1763 
1764     TemplateName TName = Id.TemplateId->Template.get();
1765     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1766     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1767     TemplateArgs = &Buffer;
1768   } else {
1769     NameInfo = GetNameFromUnqualifiedId(Id);
1770     TemplateArgs = nullptr;
1771   }
1772 }
1773 
1774 static void emitEmptyLookupTypoDiagnostic(
1775     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1776     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1777     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1778   DeclContext *Ctx =
1779       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1780   if (!TC) {
1781     // Emit a special diagnostic for failed member lookups.
1782     // FIXME: computing the declaration context might fail here (?)
1783     if (Ctx)
1784       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1785                                                  << SS.getRange();
1786     else
1787       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1788     return;
1789   }
1790 
1791   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1792   bool DroppedSpecifier =
1793       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1794   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1795                         ? diag::note_implicit_param_decl
1796                         : diag::note_previous_decl;
1797   if (!Ctx)
1798     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1799                          SemaRef.PDiag(NoteID));
1800   else
1801     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1802                                  << Typo << Ctx << DroppedSpecifier
1803                                  << SS.getRange(),
1804                          SemaRef.PDiag(NoteID));
1805 }
1806 
1807 /// Diagnose an empty lookup.
1808 ///
1809 /// \return false if new lookup candidates were found
1810 bool
1811 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1812                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1813                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1814                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1815   DeclarationName Name = R.getLookupName();
1816 
1817   unsigned diagnostic = diag::err_undeclared_var_use;
1818   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1819   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1820       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1821       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1822     diagnostic = diag::err_undeclared_use;
1823     diagnostic_suggest = diag::err_undeclared_use_suggest;
1824   }
1825 
1826   // If the original lookup was an unqualified lookup, fake an
1827   // unqualified lookup.  This is useful when (for example) the
1828   // original lookup would not have found something because it was a
1829   // dependent name.
1830   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1831   while (DC) {
1832     if (isa<CXXRecordDecl>(DC)) {
1833       LookupQualifiedName(R, DC);
1834 
1835       if (!R.empty()) {
1836         // Don't give errors about ambiguities in this lookup.
1837         R.suppressDiagnostics();
1838 
1839         // During a default argument instantiation the CurContext points
1840         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1841         // function parameter list, hence add an explicit check.
1842         bool isDefaultArgument =
1843             !CodeSynthesisContexts.empty() &&
1844             CodeSynthesisContexts.back().Kind ==
1845                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1846         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1847         bool isInstance = CurMethod &&
1848                           CurMethod->isInstance() &&
1849                           DC == CurMethod->getParent() && !isDefaultArgument;
1850 
1851         // Give a code modification hint to insert 'this->'.
1852         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1853         // Actually quite difficult!
1854         if (getLangOpts().MSVCCompat)
1855           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1856         if (isInstance) {
1857           Diag(R.getNameLoc(), diagnostic) << Name
1858             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1859           CheckCXXThisCapture(R.getNameLoc());
1860         } else {
1861           Diag(R.getNameLoc(), diagnostic) << Name;
1862         }
1863 
1864         // Do we really want to note all of these?
1865         for (NamedDecl *D : R)
1866           Diag(D->getLocation(), diag::note_dependent_var_use);
1867 
1868         // Return true if we are inside a default argument instantiation
1869         // and the found name refers to an instance member function, otherwise
1870         // the function calling DiagnoseEmptyLookup will try to create an
1871         // implicit member call and this is wrong for default argument.
1872         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1873           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1874           return true;
1875         }
1876 
1877         // Tell the callee to try to recover.
1878         return false;
1879       }
1880 
1881       R.clear();
1882     }
1883 
1884     // In Microsoft mode, if we are performing lookup from within a friend
1885     // function definition declared at class scope then we must set
1886     // DC to the lexical parent to be able to search into the parent
1887     // class.
1888     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1889         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1890         DC->getLexicalParent()->isRecord())
1891       DC = DC->getLexicalParent();
1892     else
1893       DC = DC->getParent();
1894   }
1895 
1896   // We didn't find anything, so try to correct for a typo.
1897   TypoCorrection Corrected;
1898   if (S && Out) {
1899     SourceLocation TypoLoc = R.getNameLoc();
1900     assert(!ExplicitTemplateArgs &&
1901            "Diagnosing an empty lookup with explicit template args!");
1902     *Out = CorrectTypoDelayed(
1903         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1904         [=](const TypoCorrection &TC) {
1905           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1906                                         diagnostic, diagnostic_suggest);
1907         },
1908         nullptr, CTK_ErrorRecovery);
1909     if (*Out)
1910       return true;
1911   } else if (S && (Corrected =
1912                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1913                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1914     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1915     bool DroppedSpecifier =
1916         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1917     R.setLookupName(Corrected.getCorrection());
1918 
1919     bool AcceptableWithRecovery = false;
1920     bool AcceptableWithoutRecovery = false;
1921     NamedDecl *ND = Corrected.getFoundDecl();
1922     if (ND) {
1923       if (Corrected.isOverloaded()) {
1924         OverloadCandidateSet OCS(R.getNameLoc(),
1925                                  OverloadCandidateSet::CSK_Normal);
1926         OverloadCandidateSet::iterator Best;
1927         for (NamedDecl *CD : Corrected) {
1928           if (FunctionTemplateDecl *FTD =
1929                    dyn_cast<FunctionTemplateDecl>(CD))
1930             AddTemplateOverloadCandidate(
1931                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1932                 Args, OCS);
1933           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1934             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1935               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1936                                    Args, OCS);
1937         }
1938         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1939         case OR_Success:
1940           ND = Best->FoundDecl;
1941           Corrected.setCorrectionDecl(ND);
1942           break;
1943         default:
1944           // FIXME: Arbitrarily pick the first declaration for the note.
1945           Corrected.setCorrectionDecl(ND);
1946           break;
1947         }
1948       }
1949       R.addDecl(ND);
1950       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1951         CXXRecordDecl *Record = nullptr;
1952         if (Corrected.getCorrectionSpecifier()) {
1953           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1954           Record = Ty->getAsCXXRecordDecl();
1955         }
1956         if (!Record)
1957           Record = cast<CXXRecordDecl>(
1958               ND->getDeclContext()->getRedeclContext());
1959         R.setNamingClass(Record);
1960       }
1961 
1962       auto *UnderlyingND = ND->getUnderlyingDecl();
1963       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1964                                isa<FunctionTemplateDecl>(UnderlyingND);
1965       // FIXME: If we ended up with a typo for a type name or
1966       // Objective-C class name, we're in trouble because the parser
1967       // is in the wrong place to recover. Suggest the typo
1968       // correction, but don't make it a fix-it since we're not going
1969       // to recover well anyway.
1970       AcceptableWithoutRecovery =
1971           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1972     } else {
1973       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1974       // because we aren't able to recover.
1975       AcceptableWithoutRecovery = true;
1976     }
1977 
1978     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1979       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1980                             ? diag::note_implicit_param_decl
1981                             : diag::note_previous_decl;
1982       if (SS.isEmpty())
1983         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1984                      PDiag(NoteID), AcceptableWithRecovery);
1985       else
1986         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1987                                   << Name << computeDeclContext(SS, false)
1988                                   << DroppedSpecifier << SS.getRange(),
1989                      PDiag(NoteID), AcceptableWithRecovery);
1990 
1991       // Tell the callee whether to try to recover.
1992       return !AcceptableWithRecovery;
1993     }
1994   }
1995   R.clear();
1996 
1997   // Emit a special diagnostic for failed member lookups.
1998   // FIXME: computing the declaration context might fail here (?)
1999   if (!SS.isEmpty()) {
2000     Diag(R.getNameLoc(), diag::err_no_member)
2001       << Name << computeDeclContext(SS, false)
2002       << SS.getRange();
2003     return true;
2004   }
2005 
2006   // Give up, we can't recover.
2007   Diag(R.getNameLoc(), diagnostic) << Name;
2008   return true;
2009 }
2010 
2011 /// In Microsoft mode, if we are inside a template class whose parent class has
2012 /// dependent base classes, and we can't resolve an unqualified identifier, then
2013 /// assume the identifier is a member of a dependent base class.  We can only
2014 /// recover successfully in static methods, instance methods, and other contexts
2015 /// where 'this' is available.  This doesn't precisely match MSVC's
2016 /// instantiation model, but it's close enough.
2017 static Expr *
2018 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2019                                DeclarationNameInfo &NameInfo,
2020                                SourceLocation TemplateKWLoc,
2021                                const TemplateArgumentListInfo *TemplateArgs) {
2022   // Only try to recover from lookup into dependent bases in static methods or
2023   // contexts where 'this' is available.
2024   QualType ThisType = S.getCurrentThisType();
2025   const CXXRecordDecl *RD = nullptr;
2026   if (!ThisType.isNull())
2027     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2028   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2029     RD = MD->getParent();
2030   if (!RD || !RD->hasAnyDependentBases())
2031     return nullptr;
2032 
2033   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2034   // is available, suggest inserting 'this->' as a fixit.
2035   SourceLocation Loc = NameInfo.getLoc();
2036   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2037   DB << NameInfo.getName() << RD;
2038 
2039   if (!ThisType.isNull()) {
2040     DB << FixItHint::CreateInsertion(Loc, "this->");
2041     return CXXDependentScopeMemberExpr::Create(
2042         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2043         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2044         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2045   }
2046 
2047   // Synthesize a fake NNS that points to the derived class.  This will
2048   // perform name lookup during template instantiation.
2049   CXXScopeSpec SS;
2050   auto *NNS =
2051       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2052   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2053   return DependentScopeDeclRefExpr::Create(
2054       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2055       TemplateArgs);
2056 }
2057 
2058 ExprResult
2059 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2060                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2061                         bool HasTrailingLParen, bool IsAddressOfOperand,
2062                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2063                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2064   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2065          "cannot be direct & operand and have a trailing lparen");
2066   if (SS.isInvalid())
2067     return ExprError();
2068 
2069   TemplateArgumentListInfo TemplateArgsBuffer;
2070 
2071   // Decompose the UnqualifiedId into the following data.
2072   DeclarationNameInfo NameInfo;
2073   const TemplateArgumentListInfo *TemplateArgs;
2074   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2075 
2076   DeclarationName Name = NameInfo.getName();
2077   IdentifierInfo *II = Name.getAsIdentifierInfo();
2078   SourceLocation NameLoc = NameInfo.getLoc();
2079 
2080   if (II && II->isEditorPlaceholder()) {
2081     // FIXME: When typed placeholders are supported we can create a typed
2082     // placeholder expression node.
2083     return ExprError();
2084   }
2085 
2086   // C++ [temp.dep.expr]p3:
2087   //   An id-expression is type-dependent if it contains:
2088   //     -- an identifier that was declared with a dependent type,
2089   //        (note: handled after lookup)
2090   //     -- a template-id that is dependent,
2091   //        (note: handled in BuildTemplateIdExpr)
2092   //     -- a conversion-function-id that specifies a dependent type,
2093   //     -- a nested-name-specifier that contains a class-name that
2094   //        names a dependent type.
2095   // Determine whether this is a member of an unknown specialization;
2096   // we need to handle these differently.
2097   bool DependentID = false;
2098   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2099       Name.getCXXNameType()->isDependentType()) {
2100     DependentID = true;
2101   } else if (SS.isSet()) {
2102     if (DeclContext *DC = computeDeclContext(SS, false)) {
2103       if (RequireCompleteDeclContext(SS, DC))
2104         return ExprError();
2105     } else {
2106       DependentID = true;
2107     }
2108   }
2109 
2110   if (DependentID)
2111     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2112                                       IsAddressOfOperand, TemplateArgs);
2113 
2114   // Perform the required lookup.
2115   LookupResult R(*this, NameInfo,
2116                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2117                      ? LookupObjCImplicitSelfParam
2118                      : LookupOrdinaryName);
2119   if (TemplateKWLoc.isValid() || TemplateArgs) {
2120     // Lookup the template name again to correctly establish the context in
2121     // which it was found. This is really unfortunate as we already did the
2122     // lookup to determine that it was a template name in the first place. If
2123     // this becomes a performance hit, we can work harder to preserve those
2124     // results until we get here but it's likely not worth it.
2125     bool MemberOfUnknownSpecialization;
2126     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2127                            MemberOfUnknownSpecialization, TemplateKWLoc))
2128       return ExprError();
2129 
2130     if (MemberOfUnknownSpecialization ||
2131         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2132       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2133                                         IsAddressOfOperand, TemplateArgs);
2134   } else {
2135     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2136     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2137 
2138     // If the result might be in a dependent base class, this is a dependent
2139     // id-expression.
2140     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2141       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2142                                         IsAddressOfOperand, TemplateArgs);
2143 
2144     // If this reference is in an Objective-C method, then we need to do
2145     // some special Objective-C lookup, too.
2146     if (IvarLookupFollowUp) {
2147       ExprResult E(LookupInObjCMethod(R, S, II, true));
2148       if (E.isInvalid())
2149         return ExprError();
2150 
2151       if (Expr *Ex = E.getAs<Expr>())
2152         return Ex;
2153     }
2154   }
2155 
2156   if (R.isAmbiguous())
2157     return ExprError();
2158 
2159   // This could be an implicitly declared function reference (legal in C90,
2160   // extension in C99, forbidden in C++).
2161   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2162     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2163     if (D) R.addDecl(D);
2164   }
2165 
2166   // Determine whether this name might be a candidate for
2167   // argument-dependent lookup.
2168   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2169 
2170   if (R.empty() && !ADL) {
2171     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2172       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2173                                                    TemplateKWLoc, TemplateArgs))
2174         return E;
2175     }
2176 
2177     // Don't diagnose an empty lookup for inline assembly.
2178     if (IsInlineAsmIdentifier)
2179       return ExprError();
2180 
2181     // If this name wasn't predeclared and if this is not a function
2182     // call, diagnose the problem.
2183     TypoExpr *TE = nullptr;
2184     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2185         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2186     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2187     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2188            "Typo correction callback misconfigured");
2189     if (CCC) {
2190       // Make sure the callback knows what the typo being diagnosed is.
2191       CCC->setTypoName(II);
2192       if (SS.isValid())
2193         CCC->setTypoNNS(SS.getScopeRep());
2194     }
2195     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2196     // a template name, but we happen to have always already looked up the name
2197     // before we get here if it must be a template name.
2198     if (DiagnoseEmptyLookup(S, SS, R,
2199                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2200                             nullptr, None, &TE)) {
2201       if (TE && KeywordReplacement) {
2202         auto &State = getTypoExprState(TE);
2203         auto BestTC = State.Consumer->getNextCorrection();
2204         if (BestTC.isKeyword()) {
2205           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2206           if (State.DiagHandler)
2207             State.DiagHandler(BestTC);
2208           KeywordReplacement->startToken();
2209           KeywordReplacement->setKind(II->getTokenID());
2210           KeywordReplacement->setIdentifierInfo(II);
2211           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2212           // Clean up the state associated with the TypoExpr, since it has
2213           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2214           clearDelayedTypo(TE);
2215           // Signal that a correction to a keyword was performed by returning a
2216           // valid-but-null ExprResult.
2217           return (Expr*)nullptr;
2218         }
2219         State.Consumer->resetCorrectionStream();
2220       }
2221       return TE ? TE : ExprError();
2222     }
2223 
2224     assert(!R.empty() &&
2225            "DiagnoseEmptyLookup returned false but added no results");
2226 
2227     // If we found an Objective-C instance variable, let
2228     // LookupInObjCMethod build the appropriate expression to
2229     // reference the ivar.
2230     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2231       R.clear();
2232       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2233       // In a hopelessly buggy code, Objective-C instance variable
2234       // lookup fails and no expression will be built to reference it.
2235       if (!E.isInvalid() && !E.get())
2236         return ExprError();
2237       return E;
2238     }
2239   }
2240 
2241   // This is guaranteed from this point on.
2242   assert(!R.empty() || ADL);
2243 
2244   // Check whether this might be a C++ implicit instance member access.
2245   // C++ [class.mfct.non-static]p3:
2246   //   When an id-expression that is not part of a class member access
2247   //   syntax and not used to form a pointer to member is used in the
2248   //   body of a non-static member function of class X, if name lookup
2249   //   resolves the name in the id-expression to a non-static non-type
2250   //   member of some class C, the id-expression is transformed into a
2251   //   class member access expression using (*this) as the
2252   //   postfix-expression to the left of the . operator.
2253   //
2254   // But we don't actually need to do this for '&' operands if R
2255   // resolved to a function or overloaded function set, because the
2256   // expression is ill-formed if it actually works out to be a
2257   // non-static member function:
2258   //
2259   // C++ [expr.ref]p4:
2260   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2261   //   [t]he expression can be used only as the left-hand operand of a
2262   //   member function call.
2263   //
2264   // There are other safeguards against such uses, but it's important
2265   // to get this right here so that we don't end up making a
2266   // spuriously dependent expression if we're inside a dependent
2267   // instance method.
2268   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2269     bool MightBeImplicitMember;
2270     if (!IsAddressOfOperand)
2271       MightBeImplicitMember = true;
2272     else if (!SS.isEmpty())
2273       MightBeImplicitMember = false;
2274     else if (R.isOverloadedResult())
2275       MightBeImplicitMember = false;
2276     else if (R.isUnresolvableResult())
2277       MightBeImplicitMember = true;
2278     else
2279       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2280                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2281                               isa<MSPropertyDecl>(R.getFoundDecl());
2282 
2283     if (MightBeImplicitMember)
2284       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2285                                              R, TemplateArgs, S);
2286   }
2287 
2288   if (TemplateArgs || TemplateKWLoc.isValid()) {
2289 
2290     // In C++1y, if this is a variable template id, then check it
2291     // in BuildTemplateIdExpr().
2292     // The single lookup result must be a variable template declaration.
2293     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2294         Id.TemplateId->Kind == TNK_Var_template) {
2295       assert(R.getAsSingle<VarTemplateDecl>() &&
2296              "There should only be one declaration found.");
2297     }
2298 
2299     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2300   }
2301 
2302   return BuildDeclarationNameExpr(SS, R, ADL);
2303 }
2304 
2305 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2306 /// declaration name, generally during template instantiation.
2307 /// There's a large number of things which don't need to be done along
2308 /// this path.
2309 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2310     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2311     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2312   DeclContext *DC = computeDeclContext(SS, false);
2313   if (!DC)
2314     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2315                                      NameInfo, /*TemplateArgs=*/nullptr);
2316 
2317   if (RequireCompleteDeclContext(SS, DC))
2318     return ExprError();
2319 
2320   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2321   LookupQualifiedName(R, DC);
2322 
2323   if (R.isAmbiguous())
2324     return ExprError();
2325 
2326   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2327     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2328                                      NameInfo, /*TemplateArgs=*/nullptr);
2329 
2330   if (R.empty()) {
2331     Diag(NameInfo.getLoc(), diag::err_no_member)
2332       << NameInfo.getName() << DC << SS.getRange();
2333     return ExprError();
2334   }
2335 
2336   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2337     // Diagnose a missing typename if this resolved unambiguously to a type in
2338     // a dependent context.  If we can recover with a type, downgrade this to
2339     // a warning in Microsoft compatibility mode.
2340     unsigned DiagID = diag::err_typename_missing;
2341     if (RecoveryTSI && getLangOpts().MSVCCompat)
2342       DiagID = diag::ext_typename_missing;
2343     SourceLocation Loc = SS.getBeginLoc();
2344     auto D = Diag(Loc, DiagID);
2345     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2346       << SourceRange(Loc, NameInfo.getEndLoc());
2347 
2348     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2349     // context.
2350     if (!RecoveryTSI)
2351       return ExprError();
2352 
2353     // Only issue the fixit if we're prepared to recover.
2354     D << FixItHint::CreateInsertion(Loc, "typename ");
2355 
2356     // Recover by pretending this was an elaborated type.
2357     QualType Ty = Context.getTypeDeclType(TD);
2358     TypeLocBuilder TLB;
2359     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2360 
2361     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2362     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2363     QTL.setElaboratedKeywordLoc(SourceLocation());
2364     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2365 
2366     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2367 
2368     return ExprEmpty();
2369   }
2370 
2371   // Defend against this resolving to an implicit member access. We usually
2372   // won't get here if this might be a legitimate a class member (we end up in
2373   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2374   // a pointer-to-member or in an unevaluated context in C++11.
2375   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2376     return BuildPossibleImplicitMemberExpr(SS,
2377                                            /*TemplateKWLoc=*/SourceLocation(),
2378                                            R, /*TemplateArgs=*/nullptr, S);
2379 
2380   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2381 }
2382 
2383 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2384 /// detected that we're currently inside an ObjC method.  Perform some
2385 /// additional lookup.
2386 ///
2387 /// Ideally, most of this would be done by lookup, but there's
2388 /// actually quite a lot of extra work involved.
2389 ///
2390 /// Returns a null sentinel to indicate trivial success.
2391 ExprResult
2392 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2393                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2394   SourceLocation Loc = Lookup.getNameLoc();
2395   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2396 
2397   // Check for error condition which is already reported.
2398   if (!CurMethod)
2399     return ExprError();
2400 
2401   // There are two cases to handle here.  1) scoped lookup could have failed,
2402   // in which case we should look for an ivar.  2) scoped lookup could have
2403   // found a decl, but that decl is outside the current instance method (i.e.
2404   // a global variable).  In these two cases, we do a lookup for an ivar with
2405   // this name, if the lookup sucedes, we replace it our current decl.
2406 
2407   // If we're in a class method, we don't normally want to look for
2408   // ivars.  But if we don't find anything else, and there's an
2409   // ivar, that's an error.
2410   bool IsClassMethod = CurMethod->isClassMethod();
2411 
2412   bool LookForIvars;
2413   if (Lookup.empty())
2414     LookForIvars = true;
2415   else if (IsClassMethod)
2416     LookForIvars = false;
2417   else
2418     LookForIvars = (Lookup.isSingleResult() &&
2419                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2420   ObjCInterfaceDecl *IFace = nullptr;
2421   if (LookForIvars) {
2422     IFace = CurMethod->getClassInterface();
2423     ObjCInterfaceDecl *ClassDeclared;
2424     ObjCIvarDecl *IV = nullptr;
2425     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2426       // Diagnose using an ivar in a class method.
2427       if (IsClassMethod)
2428         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2429                          << IV->getDeclName());
2430 
2431       // If we're referencing an invalid decl, just return this as a silent
2432       // error node.  The error diagnostic was already emitted on the decl.
2433       if (IV->isInvalidDecl())
2434         return ExprError();
2435 
2436       // Check if referencing a field with __attribute__((deprecated)).
2437       if (DiagnoseUseOfDecl(IV, Loc))
2438         return ExprError();
2439 
2440       // Diagnose the use of an ivar outside of the declaring class.
2441       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2442           !declaresSameEntity(ClassDeclared, IFace) &&
2443           !getLangOpts().DebuggerSupport)
2444         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2445 
2446       // FIXME: This should use a new expr for a direct reference, don't
2447       // turn this into Self->ivar, just return a BareIVarExpr or something.
2448       IdentifierInfo &II = Context.Idents.get("self");
2449       UnqualifiedId SelfName;
2450       SelfName.setIdentifier(&II, SourceLocation());
2451       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2452       CXXScopeSpec SelfScopeSpec;
2453       SourceLocation TemplateKWLoc;
2454       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2455                                               SelfName, false, false);
2456       if (SelfExpr.isInvalid())
2457         return ExprError();
2458 
2459       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2460       if (SelfExpr.isInvalid())
2461         return ExprError();
2462 
2463       MarkAnyDeclReferenced(Loc, IV, true);
2464 
2465       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2466       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2467           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2468         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2469 
2470       ObjCIvarRefExpr *Result = new (Context)
2471           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2472                           IV->getLocation(), SelfExpr.get(), true, true);
2473 
2474       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2475         if (!isUnevaluatedContext() &&
2476             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2477           getCurFunction()->recordUseOfWeak(Result);
2478       }
2479       if (getLangOpts().ObjCAutoRefCount) {
2480         if (CurContext->isClosure())
2481           Diag(Loc, diag::warn_implicitly_retains_self)
2482             << FixItHint::CreateInsertion(Loc, "self->");
2483       }
2484 
2485       return Result;
2486     }
2487   } else if (CurMethod->isInstanceMethod()) {
2488     // We should warn if a local variable hides an ivar.
2489     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2490       ObjCInterfaceDecl *ClassDeclared;
2491       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2492         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2493             declaresSameEntity(IFace, ClassDeclared))
2494           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2495       }
2496     }
2497   } else if (Lookup.isSingleResult() &&
2498              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2499     // If accessing a stand-alone ivar in a class method, this is an error.
2500     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2501       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2502                        << IV->getDeclName());
2503   }
2504 
2505   if (Lookup.empty() && II && AllowBuiltinCreation) {
2506     // FIXME. Consolidate this with similar code in LookupName.
2507     if (unsigned BuiltinID = II->getBuiltinID()) {
2508       if (!(getLangOpts().CPlusPlus &&
2509             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2510         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2511                                            S, Lookup.isForRedeclaration(),
2512                                            Lookup.getNameLoc());
2513         if (D) Lookup.addDecl(D);
2514       }
2515     }
2516   }
2517   // Sentinel value saying that we didn't do anything special.
2518   return ExprResult((Expr *)nullptr);
2519 }
2520 
2521 /// Cast a base object to a member's actual type.
2522 ///
2523 /// Logically this happens in three phases:
2524 ///
2525 /// * First we cast from the base type to the naming class.
2526 ///   The naming class is the class into which we were looking
2527 ///   when we found the member;  it's the qualifier type if a
2528 ///   qualifier was provided, and otherwise it's the base type.
2529 ///
2530 /// * Next we cast from the naming class to the declaring class.
2531 ///   If the member we found was brought into a class's scope by
2532 ///   a using declaration, this is that class;  otherwise it's
2533 ///   the class declaring the member.
2534 ///
2535 /// * Finally we cast from the declaring class to the "true"
2536 ///   declaring class of the member.  This conversion does not
2537 ///   obey access control.
2538 ExprResult
2539 Sema::PerformObjectMemberConversion(Expr *From,
2540                                     NestedNameSpecifier *Qualifier,
2541                                     NamedDecl *FoundDecl,
2542                                     NamedDecl *Member) {
2543   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2544   if (!RD)
2545     return From;
2546 
2547   QualType DestRecordType;
2548   QualType DestType;
2549   QualType FromRecordType;
2550   QualType FromType = From->getType();
2551   bool PointerConversions = false;
2552   if (isa<FieldDecl>(Member)) {
2553     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2554 
2555     if (FromType->getAs<PointerType>()) {
2556       DestType = Context.getPointerType(DestRecordType);
2557       FromRecordType = FromType->getPointeeType();
2558       PointerConversions = true;
2559     } else {
2560       DestType = DestRecordType;
2561       FromRecordType = FromType;
2562     }
2563   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2564     if (Method->isStatic())
2565       return From;
2566 
2567     DestType = Method->getThisType(Context);
2568     DestRecordType = DestType->getPointeeType();
2569 
2570     if (FromType->getAs<PointerType>()) {
2571       FromRecordType = FromType->getPointeeType();
2572       PointerConversions = true;
2573     } else {
2574       FromRecordType = FromType;
2575       DestType = DestRecordType;
2576     }
2577   } else {
2578     // No conversion necessary.
2579     return From;
2580   }
2581 
2582   if (DestType->isDependentType() || FromType->isDependentType())
2583     return From;
2584 
2585   // If the unqualified types are the same, no conversion is necessary.
2586   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2587     return From;
2588 
2589   SourceRange FromRange = From->getSourceRange();
2590   SourceLocation FromLoc = FromRange.getBegin();
2591 
2592   ExprValueKind VK = From->getValueKind();
2593 
2594   // C++ [class.member.lookup]p8:
2595   //   [...] Ambiguities can often be resolved by qualifying a name with its
2596   //   class name.
2597   //
2598   // If the member was a qualified name and the qualified referred to a
2599   // specific base subobject type, we'll cast to that intermediate type
2600   // first and then to the object in which the member is declared. That allows
2601   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2602   //
2603   //   class Base { public: int x; };
2604   //   class Derived1 : public Base { };
2605   //   class Derived2 : public Base { };
2606   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2607   //
2608   //   void VeryDerived::f() {
2609   //     x = 17; // error: ambiguous base subobjects
2610   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2611   //   }
2612   if (Qualifier && Qualifier->getAsType()) {
2613     QualType QType = QualType(Qualifier->getAsType(), 0);
2614     assert(QType->isRecordType() && "lookup done with non-record type");
2615 
2616     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2617 
2618     // In C++98, the qualifier type doesn't actually have to be a base
2619     // type of the object type, in which case we just ignore it.
2620     // Otherwise build the appropriate casts.
2621     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2622       CXXCastPath BasePath;
2623       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2624                                        FromLoc, FromRange, &BasePath))
2625         return ExprError();
2626 
2627       if (PointerConversions)
2628         QType = Context.getPointerType(QType);
2629       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2630                                VK, &BasePath).get();
2631 
2632       FromType = QType;
2633       FromRecordType = QRecordType;
2634 
2635       // If the qualifier type was the same as the destination type,
2636       // we're done.
2637       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2638         return From;
2639     }
2640   }
2641 
2642   bool IgnoreAccess = false;
2643 
2644   // If we actually found the member through a using declaration, cast
2645   // down to the using declaration's type.
2646   //
2647   // Pointer equality is fine here because only one declaration of a
2648   // class ever has member declarations.
2649   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2650     assert(isa<UsingShadowDecl>(FoundDecl));
2651     QualType URecordType = Context.getTypeDeclType(
2652                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2653 
2654     // We only need to do this if the naming-class to declaring-class
2655     // conversion is non-trivial.
2656     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2657       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2658       CXXCastPath BasePath;
2659       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2660                                        FromLoc, FromRange, &BasePath))
2661         return ExprError();
2662 
2663       QualType UType = URecordType;
2664       if (PointerConversions)
2665         UType = Context.getPointerType(UType);
2666       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2667                                VK, &BasePath).get();
2668       FromType = UType;
2669       FromRecordType = URecordType;
2670     }
2671 
2672     // We don't do access control for the conversion from the
2673     // declaring class to the true declaring class.
2674     IgnoreAccess = true;
2675   }
2676 
2677   CXXCastPath BasePath;
2678   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2679                                    FromLoc, FromRange, &BasePath,
2680                                    IgnoreAccess))
2681     return ExprError();
2682 
2683   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2684                            VK, &BasePath);
2685 }
2686 
2687 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2688                                       const LookupResult &R,
2689                                       bool HasTrailingLParen) {
2690   // Only when used directly as the postfix-expression of a call.
2691   if (!HasTrailingLParen)
2692     return false;
2693 
2694   // Never if a scope specifier was provided.
2695   if (SS.isSet())
2696     return false;
2697 
2698   // Only in C++ or ObjC++.
2699   if (!getLangOpts().CPlusPlus)
2700     return false;
2701 
2702   // Turn off ADL when we find certain kinds of declarations during
2703   // normal lookup:
2704   for (NamedDecl *D : R) {
2705     // C++0x [basic.lookup.argdep]p3:
2706     //     -- a declaration of a class member
2707     // Since using decls preserve this property, we check this on the
2708     // original decl.
2709     if (D->isCXXClassMember())
2710       return false;
2711 
2712     // C++0x [basic.lookup.argdep]p3:
2713     //     -- a block-scope function declaration that is not a
2714     //        using-declaration
2715     // NOTE: we also trigger this for function templates (in fact, we
2716     // don't check the decl type at all, since all other decl types
2717     // turn off ADL anyway).
2718     if (isa<UsingShadowDecl>(D))
2719       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2720     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2721       return false;
2722 
2723     // C++0x [basic.lookup.argdep]p3:
2724     //     -- a declaration that is neither a function or a function
2725     //        template
2726     // And also for builtin functions.
2727     if (isa<FunctionDecl>(D)) {
2728       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2729 
2730       // But also builtin functions.
2731       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2732         return false;
2733     } else if (!isa<FunctionTemplateDecl>(D))
2734       return false;
2735   }
2736 
2737   return true;
2738 }
2739 
2740 
2741 /// Diagnoses obvious problems with the use of the given declaration
2742 /// as an expression.  This is only actually called for lookups that
2743 /// were not overloaded, and it doesn't promise that the declaration
2744 /// will in fact be used.
2745 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2746   if (D->isInvalidDecl())
2747     return true;
2748 
2749   if (isa<TypedefNameDecl>(D)) {
2750     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2751     return true;
2752   }
2753 
2754   if (isa<ObjCInterfaceDecl>(D)) {
2755     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2756     return true;
2757   }
2758 
2759   if (isa<NamespaceDecl>(D)) {
2760     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2761     return true;
2762   }
2763 
2764   return false;
2765 }
2766 
2767 // Certain multiversion types should be treated as overloaded even when there is
2768 // only one result.
2769 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2770   assert(R.isSingleResult() && "Expected only a single result");
2771   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2772   return FD &&
2773          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2774 }
2775 
2776 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2777                                           LookupResult &R, bool NeedsADL,
2778                                           bool AcceptInvalidDecl) {
2779   // If this is a single, fully-resolved result and we don't need ADL,
2780   // just build an ordinary singleton decl ref.
2781   if (!NeedsADL && R.isSingleResult() &&
2782       !R.getAsSingle<FunctionTemplateDecl>() &&
2783       !ShouldLookupResultBeMultiVersionOverload(R))
2784     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2785                                     R.getRepresentativeDecl(), nullptr,
2786                                     AcceptInvalidDecl);
2787 
2788   // We only need to check the declaration if there's exactly one
2789   // result, because in the overloaded case the results can only be
2790   // functions and function templates.
2791   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2792       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2793     return ExprError();
2794 
2795   // Otherwise, just build an unresolved lookup expression.  Suppress
2796   // any lookup-related diagnostics; we'll hash these out later, when
2797   // we've picked a target.
2798   R.suppressDiagnostics();
2799 
2800   UnresolvedLookupExpr *ULE
2801     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2802                                    SS.getWithLocInContext(Context),
2803                                    R.getLookupNameInfo(),
2804                                    NeedsADL, R.isOverloadedResult(),
2805                                    R.begin(), R.end());
2806 
2807   return ULE;
2808 }
2809 
2810 static void
2811 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2812                                    ValueDecl *var, DeclContext *DC);
2813 
2814 /// Complete semantic analysis for a reference to the given declaration.
2815 ExprResult Sema::BuildDeclarationNameExpr(
2816     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2817     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2818     bool AcceptInvalidDecl) {
2819   assert(D && "Cannot refer to a NULL declaration");
2820   assert(!isa<FunctionTemplateDecl>(D) &&
2821          "Cannot refer unambiguously to a function template");
2822 
2823   SourceLocation Loc = NameInfo.getLoc();
2824   if (CheckDeclInExpr(*this, Loc, D))
2825     return ExprError();
2826 
2827   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2828     // Specifically diagnose references to class templates that are missing
2829     // a template argument list.
2830     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2831     return ExprError();
2832   }
2833 
2834   // Make sure that we're referring to a value.
2835   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2836   if (!VD) {
2837     Diag(Loc, diag::err_ref_non_value)
2838       << D << SS.getRange();
2839     Diag(D->getLocation(), diag::note_declared_at);
2840     return ExprError();
2841   }
2842 
2843   // Check whether this declaration can be used. Note that we suppress
2844   // this check when we're going to perform argument-dependent lookup
2845   // on this function name, because this might not be the function
2846   // that overload resolution actually selects.
2847   if (DiagnoseUseOfDecl(VD, Loc))
2848     return ExprError();
2849 
2850   // Only create DeclRefExpr's for valid Decl's.
2851   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2852     return ExprError();
2853 
2854   // Handle members of anonymous structs and unions.  If we got here,
2855   // and the reference is to a class member indirect field, then this
2856   // must be the subject of a pointer-to-member expression.
2857   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2858     if (!indirectField->isCXXClassMember())
2859       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2860                                                       indirectField);
2861 
2862   {
2863     QualType type = VD->getType();
2864     if (type.isNull())
2865       return ExprError();
2866     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2867       // C++ [except.spec]p17:
2868       //   An exception-specification is considered to be needed when:
2869       //   - in an expression, the function is the unique lookup result or
2870       //     the selected member of a set of overloaded functions.
2871       ResolveExceptionSpec(Loc, FPT);
2872       type = VD->getType();
2873     }
2874     ExprValueKind valueKind = VK_RValue;
2875 
2876     switch (D->getKind()) {
2877     // Ignore all the non-ValueDecl kinds.
2878 #define ABSTRACT_DECL(kind)
2879 #define VALUE(type, base)
2880 #define DECL(type, base) \
2881     case Decl::type:
2882 #include "clang/AST/DeclNodes.inc"
2883       llvm_unreachable("invalid value decl kind");
2884 
2885     // These shouldn't make it here.
2886     case Decl::ObjCAtDefsField:
2887     case Decl::ObjCIvar:
2888       llvm_unreachable("forming non-member reference to ivar?");
2889 
2890     // Enum constants are always r-values and never references.
2891     // Unresolved using declarations are dependent.
2892     case Decl::EnumConstant:
2893     case Decl::UnresolvedUsingValue:
2894     case Decl::OMPDeclareReduction:
2895       valueKind = VK_RValue;
2896       break;
2897 
2898     // Fields and indirect fields that got here must be for
2899     // pointer-to-member expressions; we just call them l-values for
2900     // internal consistency, because this subexpression doesn't really
2901     // exist in the high-level semantics.
2902     case Decl::Field:
2903     case Decl::IndirectField:
2904       assert(getLangOpts().CPlusPlus &&
2905              "building reference to field in C?");
2906 
2907       // These can't have reference type in well-formed programs, but
2908       // for internal consistency we do this anyway.
2909       type = type.getNonReferenceType();
2910       valueKind = VK_LValue;
2911       break;
2912 
2913     // Non-type template parameters are either l-values or r-values
2914     // depending on the type.
2915     case Decl::NonTypeTemplateParm: {
2916       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2917         type = reftype->getPointeeType();
2918         valueKind = VK_LValue; // even if the parameter is an r-value reference
2919         break;
2920       }
2921 
2922       // For non-references, we need to strip qualifiers just in case
2923       // the template parameter was declared as 'const int' or whatever.
2924       valueKind = VK_RValue;
2925       type = type.getUnqualifiedType();
2926       break;
2927     }
2928 
2929     case Decl::Var:
2930     case Decl::VarTemplateSpecialization:
2931     case Decl::VarTemplatePartialSpecialization:
2932     case Decl::Decomposition:
2933     case Decl::OMPCapturedExpr:
2934       // In C, "extern void blah;" is valid and is an r-value.
2935       if (!getLangOpts().CPlusPlus &&
2936           !type.hasQualifiers() &&
2937           type->isVoidType()) {
2938         valueKind = VK_RValue;
2939         break;
2940       }
2941       LLVM_FALLTHROUGH;
2942 
2943     case Decl::ImplicitParam:
2944     case Decl::ParmVar: {
2945       // These are always l-values.
2946       valueKind = VK_LValue;
2947       type = type.getNonReferenceType();
2948 
2949       // FIXME: Does the addition of const really only apply in
2950       // potentially-evaluated contexts? Since the variable isn't actually
2951       // captured in an unevaluated context, it seems that the answer is no.
2952       if (!isUnevaluatedContext()) {
2953         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2954         if (!CapturedType.isNull())
2955           type = CapturedType;
2956       }
2957 
2958       break;
2959     }
2960 
2961     case Decl::Binding: {
2962       // These are always lvalues.
2963       valueKind = VK_LValue;
2964       type = type.getNonReferenceType();
2965       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2966       // decides how that's supposed to work.
2967       auto *BD = cast<BindingDecl>(VD);
2968       if (BD->getDeclContext()->isFunctionOrMethod() &&
2969           BD->getDeclContext() != CurContext)
2970         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2971       break;
2972     }
2973 
2974     case Decl::Function: {
2975       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2976         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2977           type = Context.BuiltinFnTy;
2978           valueKind = VK_RValue;
2979           break;
2980         }
2981       }
2982 
2983       const FunctionType *fty = type->castAs<FunctionType>();
2984 
2985       // If we're referring to a function with an __unknown_anytype
2986       // result type, make the entire expression __unknown_anytype.
2987       if (fty->getReturnType() == Context.UnknownAnyTy) {
2988         type = Context.UnknownAnyTy;
2989         valueKind = VK_RValue;
2990         break;
2991       }
2992 
2993       // Functions are l-values in C++.
2994       if (getLangOpts().CPlusPlus) {
2995         valueKind = VK_LValue;
2996         break;
2997       }
2998 
2999       // C99 DR 316 says that, if a function type comes from a
3000       // function definition (without a prototype), that type is only
3001       // used for checking compatibility. Therefore, when referencing
3002       // the function, we pretend that we don't have the full function
3003       // type.
3004       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3005           isa<FunctionProtoType>(fty))
3006         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3007                                               fty->getExtInfo());
3008 
3009       // Functions are r-values in C.
3010       valueKind = VK_RValue;
3011       break;
3012     }
3013 
3014     case Decl::CXXDeductionGuide:
3015       llvm_unreachable("building reference to deduction guide");
3016 
3017     case Decl::MSProperty:
3018       valueKind = VK_LValue;
3019       break;
3020 
3021     case Decl::CXXMethod:
3022       // If we're referring to a method with an __unknown_anytype
3023       // result type, make the entire expression __unknown_anytype.
3024       // This should only be possible with a type written directly.
3025       if (const FunctionProtoType *proto
3026             = dyn_cast<FunctionProtoType>(VD->getType()))
3027         if (proto->getReturnType() == Context.UnknownAnyTy) {
3028           type = Context.UnknownAnyTy;
3029           valueKind = VK_RValue;
3030           break;
3031         }
3032 
3033       // C++ methods are l-values if static, r-values if non-static.
3034       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3035         valueKind = VK_LValue;
3036         break;
3037       }
3038       LLVM_FALLTHROUGH;
3039 
3040     case Decl::CXXConversion:
3041     case Decl::CXXDestructor:
3042     case Decl::CXXConstructor:
3043       valueKind = VK_RValue;
3044       break;
3045     }
3046 
3047     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3048                             TemplateArgs);
3049   }
3050 }
3051 
3052 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3053                                     SmallString<32> &Target) {
3054   Target.resize(CharByteWidth * (Source.size() + 1));
3055   char *ResultPtr = &Target[0];
3056   const llvm::UTF8 *ErrorPtr;
3057   bool success =
3058       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3059   (void)success;
3060   assert(success);
3061   Target.resize(ResultPtr - &Target[0]);
3062 }
3063 
3064 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3065                                      PredefinedExpr::IdentKind IK) {
3066   // Pick the current block, lambda, captured statement or function.
3067   Decl *currentDecl = nullptr;
3068   if (const BlockScopeInfo *BSI = getCurBlock())
3069     currentDecl = BSI->TheDecl;
3070   else if (const LambdaScopeInfo *LSI = getCurLambda())
3071     currentDecl = LSI->CallOperator;
3072   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3073     currentDecl = CSI->TheCapturedDecl;
3074   else
3075     currentDecl = getCurFunctionOrMethodDecl();
3076 
3077   if (!currentDecl) {
3078     Diag(Loc, diag::ext_predef_outside_function);
3079     currentDecl = Context.getTranslationUnitDecl();
3080   }
3081 
3082   QualType ResTy;
3083   StringLiteral *SL = nullptr;
3084   if (cast<DeclContext>(currentDecl)->isDependentContext())
3085     ResTy = Context.DependentTy;
3086   else {
3087     // Pre-defined identifiers are of type char[x], where x is the length of
3088     // the string.
3089     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3090     unsigned Length = Str.length();
3091 
3092     llvm::APInt LengthI(32, Length + 1);
3093     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3094       ResTy =
3095           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3096       SmallString<32> RawChars;
3097       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3098                               Str, RawChars);
3099       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3100                                            /*IndexTypeQuals*/ 0);
3101       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3102                                  /*Pascal*/ false, ResTy, Loc);
3103     } else {
3104       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3105       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3106                                            /*IndexTypeQuals*/ 0);
3107       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3108                                  /*Pascal*/ false, ResTy, Loc);
3109     }
3110   }
3111 
3112   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3113 }
3114 
3115 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3116   PredefinedExpr::IdentKind IK;
3117 
3118   switch (Kind) {
3119   default: llvm_unreachable("Unknown simple primary expr!");
3120   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3121   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3122   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3123   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3124   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3125   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3126   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3127   }
3128 
3129   return BuildPredefinedExpr(Loc, IK);
3130 }
3131 
3132 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3133   SmallString<16> CharBuffer;
3134   bool Invalid = false;
3135   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3136   if (Invalid)
3137     return ExprError();
3138 
3139   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3140                             PP, Tok.getKind());
3141   if (Literal.hadError())
3142     return ExprError();
3143 
3144   QualType Ty;
3145   if (Literal.isWide())
3146     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3147   else if (Literal.isUTF8() && getLangOpts().Char8)
3148     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3149   else if (Literal.isUTF16())
3150     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3151   else if (Literal.isUTF32())
3152     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3153   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3154     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3155   else
3156     Ty = Context.CharTy;  // 'x' -> char in C++
3157 
3158   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3159   if (Literal.isWide())
3160     Kind = CharacterLiteral::Wide;
3161   else if (Literal.isUTF16())
3162     Kind = CharacterLiteral::UTF16;
3163   else if (Literal.isUTF32())
3164     Kind = CharacterLiteral::UTF32;
3165   else if (Literal.isUTF8())
3166     Kind = CharacterLiteral::UTF8;
3167 
3168   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3169                                              Tok.getLocation());
3170 
3171   if (Literal.getUDSuffix().empty())
3172     return Lit;
3173 
3174   // We're building a user-defined literal.
3175   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3176   SourceLocation UDSuffixLoc =
3177     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3178 
3179   // Make sure we're allowed user-defined literals here.
3180   if (!UDLScope)
3181     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3182 
3183   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3184   //   operator "" X (ch)
3185   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3186                                         Lit, Tok.getLocation());
3187 }
3188 
3189 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3190   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3191   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3192                                 Context.IntTy, Loc);
3193 }
3194 
3195 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3196                                   QualType Ty, SourceLocation Loc) {
3197   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3198 
3199   using llvm::APFloat;
3200   APFloat Val(Format);
3201 
3202   APFloat::opStatus result = Literal.GetFloatValue(Val);
3203 
3204   // Overflow is always an error, but underflow is only an error if
3205   // we underflowed to zero (APFloat reports denormals as underflow).
3206   if ((result & APFloat::opOverflow) ||
3207       ((result & APFloat::opUnderflow) && Val.isZero())) {
3208     unsigned diagnostic;
3209     SmallString<20> buffer;
3210     if (result & APFloat::opOverflow) {
3211       diagnostic = diag::warn_float_overflow;
3212       APFloat::getLargest(Format).toString(buffer);
3213     } else {
3214       diagnostic = diag::warn_float_underflow;
3215       APFloat::getSmallest(Format).toString(buffer);
3216     }
3217 
3218     S.Diag(Loc, diagnostic)
3219       << Ty
3220       << StringRef(buffer.data(), buffer.size());
3221   }
3222 
3223   bool isExact = (result == APFloat::opOK);
3224   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3225 }
3226 
3227 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3228   assert(E && "Invalid expression");
3229 
3230   if (E->isValueDependent())
3231     return false;
3232 
3233   QualType QT = E->getType();
3234   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3235     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3236     return true;
3237   }
3238 
3239   llvm::APSInt ValueAPS;
3240   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3241 
3242   if (R.isInvalid())
3243     return true;
3244 
3245   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3246   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3247     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3248         << ValueAPS.toString(10) << ValueIsPositive;
3249     return true;
3250   }
3251 
3252   return false;
3253 }
3254 
3255 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3256   // Fast path for a single digit (which is quite common).  A single digit
3257   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3258   if (Tok.getLength() == 1) {
3259     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3260     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3261   }
3262 
3263   SmallString<128> SpellingBuffer;
3264   // NumericLiteralParser wants to overread by one character.  Add padding to
3265   // the buffer in case the token is copied to the buffer.  If getSpelling()
3266   // returns a StringRef to the memory buffer, it should have a null char at
3267   // the EOF, so it is also safe.
3268   SpellingBuffer.resize(Tok.getLength() + 1);
3269 
3270   // Get the spelling of the token, which eliminates trigraphs, etc.
3271   bool Invalid = false;
3272   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3273   if (Invalid)
3274     return ExprError();
3275 
3276   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3277   if (Literal.hadError)
3278     return ExprError();
3279 
3280   if (Literal.hasUDSuffix()) {
3281     // We're building a user-defined literal.
3282     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3283     SourceLocation UDSuffixLoc =
3284       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3285 
3286     // Make sure we're allowed user-defined literals here.
3287     if (!UDLScope)
3288       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3289 
3290     QualType CookedTy;
3291     if (Literal.isFloatingLiteral()) {
3292       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3293       // long double, the literal is treated as a call of the form
3294       //   operator "" X (f L)
3295       CookedTy = Context.LongDoubleTy;
3296     } else {
3297       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3298       // unsigned long long, the literal is treated as a call of the form
3299       //   operator "" X (n ULL)
3300       CookedTy = Context.UnsignedLongLongTy;
3301     }
3302 
3303     DeclarationName OpName =
3304       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3305     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3306     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3307 
3308     SourceLocation TokLoc = Tok.getLocation();
3309 
3310     // Perform literal operator lookup to determine if we're building a raw
3311     // literal or a cooked one.
3312     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3313     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3314                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3315                                   /*AllowStringTemplate*/ false,
3316                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3317     case LOLR_ErrorNoDiagnostic:
3318       // Lookup failure for imaginary constants isn't fatal, there's still the
3319       // GNU extension producing _Complex types.
3320       break;
3321     case LOLR_Error:
3322       return ExprError();
3323     case LOLR_Cooked: {
3324       Expr *Lit;
3325       if (Literal.isFloatingLiteral()) {
3326         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3327       } else {
3328         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3329         if (Literal.GetIntegerValue(ResultVal))
3330           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3331               << /* Unsigned */ 1;
3332         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3333                                      Tok.getLocation());
3334       }
3335       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3336     }
3337 
3338     case LOLR_Raw: {
3339       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3340       // literal is treated as a call of the form
3341       //   operator "" X ("n")
3342       unsigned Length = Literal.getUDSuffixOffset();
3343       QualType StrTy = Context.getConstantArrayType(
3344           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3345           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3346       Expr *Lit = StringLiteral::Create(
3347           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3348           /*Pascal*/false, StrTy, &TokLoc, 1);
3349       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3350     }
3351 
3352     case LOLR_Template: {
3353       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3354       // template), L is treated as a call fo the form
3355       //   operator "" X <'c1', 'c2', ... 'ck'>()
3356       // where n is the source character sequence c1 c2 ... ck.
3357       TemplateArgumentListInfo ExplicitArgs;
3358       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3359       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3360       llvm::APSInt Value(CharBits, CharIsUnsigned);
3361       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3362         Value = TokSpelling[I];
3363         TemplateArgument Arg(Context, Value, Context.CharTy);
3364         TemplateArgumentLocInfo ArgInfo;
3365         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3366       }
3367       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3368                                       &ExplicitArgs);
3369     }
3370     case LOLR_StringTemplate:
3371       llvm_unreachable("unexpected literal operator lookup result");
3372     }
3373   }
3374 
3375   Expr *Res;
3376 
3377   if (Literal.isFixedPointLiteral()) {
3378     QualType Ty;
3379 
3380     if (Literal.isAccum) {
3381       if (Literal.isHalf) {
3382         Ty = Context.ShortAccumTy;
3383       } else if (Literal.isLong) {
3384         Ty = Context.LongAccumTy;
3385       } else {
3386         Ty = Context.AccumTy;
3387       }
3388     } else if (Literal.isFract) {
3389       if (Literal.isHalf) {
3390         Ty = Context.ShortFractTy;
3391       } else if (Literal.isLong) {
3392         Ty = Context.LongFractTy;
3393       } else {
3394         Ty = Context.FractTy;
3395       }
3396     }
3397 
3398     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3399 
3400     bool isSigned = !Literal.isUnsigned;
3401     unsigned scale = Context.getFixedPointScale(Ty);
3402     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3403 
3404     llvm::APInt Val(bit_width, 0, isSigned);
3405     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3406     bool ValIsZero = Val.isNullValue() && !Overflowed;
3407 
3408     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3409     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3410       // Clause 6.4.4 - The value of a constant shall be in the range of
3411       // representable values for its type, with exception for constants of a
3412       // fract type with a value of exactly 1; such a constant shall denote
3413       // the maximal value for the type.
3414       --Val;
3415     else if (Val.ugt(MaxVal) || Overflowed)
3416       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3417 
3418     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3419                                               Tok.getLocation(), scale);
3420   } else if (Literal.isFloatingLiteral()) {
3421     QualType Ty;
3422     if (Literal.isHalf){
3423       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3424         Ty = Context.HalfTy;
3425       else {
3426         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3427         return ExprError();
3428       }
3429     } else if (Literal.isFloat)
3430       Ty = Context.FloatTy;
3431     else if (Literal.isLong)
3432       Ty = Context.LongDoubleTy;
3433     else if (Literal.isFloat16)
3434       Ty = Context.Float16Ty;
3435     else if (Literal.isFloat128)
3436       Ty = Context.Float128Ty;
3437     else
3438       Ty = Context.DoubleTy;
3439 
3440     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3441 
3442     if (Ty == Context.DoubleTy) {
3443       if (getLangOpts().SinglePrecisionConstants) {
3444         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3445         if (BTy->getKind() != BuiltinType::Float) {
3446           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3447         }
3448       } else if (getLangOpts().OpenCL &&
3449                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3450         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3451         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3452         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3453       }
3454     }
3455   } else if (!Literal.isIntegerLiteral()) {
3456     return ExprError();
3457   } else {
3458     QualType Ty;
3459 
3460     // 'long long' is a C99 or C++11 feature.
3461     if (!getLangOpts().C99 && Literal.isLongLong) {
3462       if (getLangOpts().CPlusPlus)
3463         Diag(Tok.getLocation(),
3464              getLangOpts().CPlusPlus11 ?
3465              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3466       else
3467         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3468     }
3469 
3470     // Get the value in the widest-possible width.
3471     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3472     llvm::APInt ResultVal(MaxWidth, 0);
3473 
3474     if (Literal.GetIntegerValue(ResultVal)) {
3475       // If this value didn't fit into uintmax_t, error and force to ull.
3476       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3477           << /* Unsigned */ 1;
3478       Ty = Context.UnsignedLongLongTy;
3479       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3480              "long long is not intmax_t?");
3481     } else {
3482       // If this value fits into a ULL, try to figure out what else it fits into
3483       // according to the rules of C99 6.4.4.1p5.
3484 
3485       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3486       // be an unsigned int.
3487       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3488 
3489       // Check from smallest to largest, picking the smallest type we can.
3490       unsigned Width = 0;
3491 
3492       // Microsoft specific integer suffixes are explicitly sized.
3493       if (Literal.MicrosoftInteger) {
3494         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3495           Width = 8;
3496           Ty = Context.CharTy;
3497         } else {
3498           Width = Literal.MicrosoftInteger;
3499           Ty = Context.getIntTypeForBitwidth(Width,
3500                                              /*Signed=*/!Literal.isUnsigned);
3501         }
3502       }
3503 
3504       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3505         // Are int/unsigned possibilities?
3506         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3507 
3508         // Does it fit in a unsigned int?
3509         if (ResultVal.isIntN(IntSize)) {
3510           // Does it fit in a signed int?
3511           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3512             Ty = Context.IntTy;
3513           else if (AllowUnsigned)
3514             Ty = Context.UnsignedIntTy;
3515           Width = IntSize;
3516         }
3517       }
3518 
3519       // Are long/unsigned long possibilities?
3520       if (Ty.isNull() && !Literal.isLongLong) {
3521         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3522 
3523         // Does it fit in a unsigned long?
3524         if (ResultVal.isIntN(LongSize)) {
3525           // Does it fit in a signed long?
3526           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3527             Ty = Context.LongTy;
3528           else if (AllowUnsigned)
3529             Ty = Context.UnsignedLongTy;
3530           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3531           // is compatible.
3532           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3533             const unsigned LongLongSize =
3534                 Context.getTargetInfo().getLongLongWidth();
3535             Diag(Tok.getLocation(),
3536                  getLangOpts().CPlusPlus
3537                      ? Literal.isLong
3538                            ? diag::warn_old_implicitly_unsigned_long_cxx
3539                            : /*C++98 UB*/ diag::
3540                                  ext_old_implicitly_unsigned_long_cxx
3541                      : diag::warn_old_implicitly_unsigned_long)
3542                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3543                                             : /*will be ill-formed*/ 1);
3544             Ty = Context.UnsignedLongTy;
3545           }
3546           Width = LongSize;
3547         }
3548       }
3549 
3550       // Check long long if needed.
3551       if (Ty.isNull()) {
3552         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3553 
3554         // Does it fit in a unsigned long long?
3555         if (ResultVal.isIntN(LongLongSize)) {
3556           // Does it fit in a signed long long?
3557           // To be compatible with MSVC, hex integer literals ending with the
3558           // LL or i64 suffix are always signed in Microsoft mode.
3559           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3560               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3561             Ty = Context.LongLongTy;
3562           else if (AllowUnsigned)
3563             Ty = Context.UnsignedLongLongTy;
3564           Width = LongLongSize;
3565         }
3566       }
3567 
3568       // If we still couldn't decide a type, we probably have something that
3569       // does not fit in a signed long long, but has no U suffix.
3570       if (Ty.isNull()) {
3571         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3572         Ty = Context.UnsignedLongLongTy;
3573         Width = Context.getTargetInfo().getLongLongWidth();
3574       }
3575 
3576       if (ResultVal.getBitWidth() != Width)
3577         ResultVal = ResultVal.trunc(Width);
3578     }
3579     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3580   }
3581 
3582   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3583   if (Literal.isImaginary) {
3584     Res = new (Context) ImaginaryLiteral(Res,
3585                                         Context.getComplexType(Res->getType()));
3586 
3587     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3588   }
3589   return Res;
3590 }
3591 
3592 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3593   assert(E && "ActOnParenExpr() missing expr");
3594   return new (Context) ParenExpr(L, R, E);
3595 }
3596 
3597 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3598                                          SourceLocation Loc,
3599                                          SourceRange ArgRange) {
3600   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3601   // scalar or vector data type argument..."
3602   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3603   // type (C99 6.2.5p18) or void.
3604   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3605     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3606       << T << ArgRange;
3607     return true;
3608   }
3609 
3610   assert((T->isVoidType() || !T->isIncompleteType()) &&
3611          "Scalar types should always be complete");
3612   return false;
3613 }
3614 
3615 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3616                                            SourceLocation Loc,
3617                                            SourceRange ArgRange,
3618                                            UnaryExprOrTypeTrait TraitKind) {
3619   // Invalid types must be hard errors for SFINAE in C++.
3620   if (S.LangOpts.CPlusPlus)
3621     return true;
3622 
3623   // C99 6.5.3.4p1:
3624   if (T->isFunctionType() &&
3625       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3626        TraitKind == UETT_PreferredAlignOf)) {
3627     // sizeof(function)/alignof(function) is allowed as an extension.
3628     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3629       << TraitKind << ArgRange;
3630     return false;
3631   }
3632 
3633   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3634   // this is an error (OpenCL v1.1 s6.3.k)
3635   if (T->isVoidType()) {
3636     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3637                                         : diag::ext_sizeof_alignof_void_type;
3638     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3639     return false;
3640   }
3641 
3642   return true;
3643 }
3644 
3645 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3646                                              SourceLocation Loc,
3647                                              SourceRange ArgRange,
3648                                              UnaryExprOrTypeTrait TraitKind) {
3649   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3650   // runtime doesn't allow it.
3651   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3652     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3653       << T << (TraitKind == UETT_SizeOf)
3654       << ArgRange;
3655     return true;
3656   }
3657 
3658   return false;
3659 }
3660 
3661 /// Check whether E is a pointer from a decayed array type (the decayed
3662 /// pointer type is equal to T) and emit a warning if it is.
3663 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3664                                      Expr *E) {
3665   // Don't warn if the operation changed the type.
3666   if (T != E->getType())
3667     return;
3668 
3669   // Now look for array decays.
3670   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3671   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3672     return;
3673 
3674   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3675                                              << ICE->getType()
3676                                              << ICE->getSubExpr()->getType();
3677 }
3678 
3679 /// Check the constraints on expression operands to unary type expression
3680 /// and type traits.
3681 ///
3682 /// Completes any types necessary and validates the constraints on the operand
3683 /// expression. The logic mostly mirrors the type-based overload, but may modify
3684 /// the expression as it completes the type for that expression through template
3685 /// instantiation, etc.
3686 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3687                                             UnaryExprOrTypeTrait ExprKind) {
3688   QualType ExprTy = E->getType();
3689   assert(!ExprTy->isReferenceType());
3690 
3691   if (ExprKind == UETT_VecStep)
3692     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3693                                         E->getSourceRange());
3694 
3695   // Whitelist some types as extensions
3696   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3697                                       E->getSourceRange(), ExprKind))
3698     return false;
3699 
3700   // 'alignof' applied to an expression only requires the base element type of
3701   // the expression to be complete. 'sizeof' requires the expression's type to
3702   // be complete (and will attempt to complete it if it's an array of unknown
3703   // bound).
3704   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3705     if (RequireCompleteType(E->getExprLoc(),
3706                             Context.getBaseElementType(E->getType()),
3707                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3708                             E->getSourceRange()))
3709       return true;
3710   } else {
3711     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3712                                 ExprKind, E->getSourceRange()))
3713       return true;
3714   }
3715 
3716   // Completing the expression's type may have changed it.
3717   ExprTy = E->getType();
3718   assert(!ExprTy->isReferenceType());
3719 
3720   if (ExprTy->isFunctionType()) {
3721     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3722       << ExprKind << E->getSourceRange();
3723     return true;
3724   }
3725 
3726   // The operand for sizeof and alignof is in an unevaluated expression context,
3727   // so side effects could result in unintended consequences.
3728   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3729        ExprKind == UETT_PreferredAlignOf) &&
3730       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3731     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3732 
3733   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3734                                        E->getSourceRange(), ExprKind))
3735     return true;
3736 
3737   if (ExprKind == UETT_SizeOf) {
3738     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3739       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3740         QualType OType = PVD->getOriginalType();
3741         QualType Type = PVD->getType();
3742         if (Type->isPointerType() && OType->isArrayType()) {
3743           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3744             << Type << OType;
3745           Diag(PVD->getLocation(), diag::note_declared_at);
3746         }
3747       }
3748     }
3749 
3750     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3751     // decays into a pointer and returns an unintended result. This is most
3752     // likely a typo for "sizeof(array) op x".
3753     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3754       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3755                                BO->getLHS());
3756       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3757                                BO->getRHS());
3758     }
3759   }
3760 
3761   return false;
3762 }
3763 
3764 /// Check the constraints on operands to unary expression and type
3765 /// traits.
3766 ///
3767 /// This will complete any types necessary, and validate the various constraints
3768 /// on those operands.
3769 ///
3770 /// The UsualUnaryConversions() function is *not* called by this routine.
3771 /// C99 6.3.2.1p[2-4] all state:
3772 ///   Except when it is the operand of the sizeof operator ...
3773 ///
3774 /// C++ [expr.sizeof]p4
3775 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3776 ///   standard conversions are not applied to the operand of sizeof.
3777 ///
3778 /// This policy is followed for all of the unary trait expressions.
3779 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3780                                             SourceLocation OpLoc,
3781                                             SourceRange ExprRange,
3782                                             UnaryExprOrTypeTrait ExprKind) {
3783   if (ExprType->isDependentType())
3784     return false;
3785 
3786   // C++ [expr.sizeof]p2:
3787   //     When applied to a reference or a reference type, the result
3788   //     is the size of the referenced type.
3789   // C++11 [expr.alignof]p3:
3790   //     When alignof is applied to a reference type, the result
3791   //     shall be the alignment of the referenced type.
3792   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3793     ExprType = Ref->getPointeeType();
3794 
3795   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3796   //   When alignof or _Alignof is applied to an array type, the result
3797   //   is the alignment of the element type.
3798   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3799       ExprKind == UETT_OpenMPRequiredSimdAlign)
3800     ExprType = Context.getBaseElementType(ExprType);
3801 
3802   if (ExprKind == UETT_VecStep)
3803     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3804 
3805   // Whitelist some types as extensions
3806   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3807                                       ExprKind))
3808     return false;
3809 
3810   if (RequireCompleteType(OpLoc, ExprType,
3811                           diag::err_sizeof_alignof_incomplete_type,
3812                           ExprKind, ExprRange))
3813     return true;
3814 
3815   if (ExprType->isFunctionType()) {
3816     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3817       << ExprKind << ExprRange;
3818     return true;
3819   }
3820 
3821   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3822                                        ExprKind))
3823     return true;
3824 
3825   return false;
3826 }
3827 
3828 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3829   E = E->IgnoreParens();
3830 
3831   // Cannot know anything else if the expression is dependent.
3832   if (E->isTypeDependent())
3833     return false;
3834 
3835   if (E->getObjectKind() == OK_BitField) {
3836     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3837        << 1 << E->getSourceRange();
3838     return true;
3839   }
3840 
3841   ValueDecl *D = nullptr;
3842   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3843     D = DRE->getDecl();
3844   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3845     D = ME->getMemberDecl();
3846   }
3847 
3848   // If it's a field, require the containing struct to have a
3849   // complete definition so that we can compute the layout.
3850   //
3851   // This can happen in C++11 onwards, either by naming the member
3852   // in a way that is not transformed into a member access expression
3853   // (in an unevaluated operand, for instance), or by naming the member
3854   // in a trailing-return-type.
3855   //
3856   // For the record, since __alignof__ on expressions is a GCC
3857   // extension, GCC seems to permit this but always gives the
3858   // nonsensical answer 0.
3859   //
3860   // We don't really need the layout here --- we could instead just
3861   // directly check for all the appropriate alignment-lowing
3862   // attributes --- but that would require duplicating a lot of
3863   // logic that just isn't worth duplicating for such a marginal
3864   // use-case.
3865   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3866     // Fast path this check, since we at least know the record has a
3867     // definition if we can find a member of it.
3868     if (!FD->getParent()->isCompleteDefinition()) {
3869       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3870         << E->getSourceRange();
3871       return true;
3872     }
3873 
3874     // Otherwise, if it's a field, and the field doesn't have
3875     // reference type, then it must have a complete type (or be a
3876     // flexible array member, which we explicitly want to
3877     // white-list anyway), which makes the following checks trivial.
3878     if (!FD->getType()->isReferenceType())
3879       return false;
3880   }
3881 
3882   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3883 }
3884 
3885 bool Sema::CheckVecStepExpr(Expr *E) {
3886   E = E->IgnoreParens();
3887 
3888   // Cannot know anything else if the expression is dependent.
3889   if (E->isTypeDependent())
3890     return false;
3891 
3892   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3893 }
3894 
3895 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3896                                         CapturingScopeInfo *CSI) {
3897   assert(T->isVariablyModifiedType());
3898   assert(CSI != nullptr);
3899 
3900   // We're going to walk down into the type and look for VLA expressions.
3901   do {
3902     const Type *Ty = T.getTypePtr();
3903     switch (Ty->getTypeClass()) {
3904 #define TYPE(Class, Base)
3905 #define ABSTRACT_TYPE(Class, Base)
3906 #define NON_CANONICAL_TYPE(Class, Base)
3907 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3908 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3909 #include "clang/AST/TypeNodes.def"
3910       T = QualType();
3911       break;
3912     // These types are never variably-modified.
3913     case Type::Builtin:
3914     case Type::Complex:
3915     case Type::Vector:
3916     case Type::ExtVector:
3917     case Type::Record:
3918     case Type::Enum:
3919     case Type::Elaborated:
3920     case Type::TemplateSpecialization:
3921     case Type::ObjCObject:
3922     case Type::ObjCInterface:
3923     case Type::ObjCObjectPointer:
3924     case Type::ObjCTypeParam:
3925     case Type::Pipe:
3926       llvm_unreachable("type class is never variably-modified!");
3927     case Type::Adjusted:
3928       T = cast<AdjustedType>(Ty)->getOriginalType();
3929       break;
3930     case Type::Decayed:
3931       T = cast<DecayedType>(Ty)->getPointeeType();
3932       break;
3933     case Type::Pointer:
3934       T = cast<PointerType>(Ty)->getPointeeType();
3935       break;
3936     case Type::BlockPointer:
3937       T = cast<BlockPointerType>(Ty)->getPointeeType();
3938       break;
3939     case Type::LValueReference:
3940     case Type::RValueReference:
3941       T = cast<ReferenceType>(Ty)->getPointeeType();
3942       break;
3943     case Type::MemberPointer:
3944       T = cast<MemberPointerType>(Ty)->getPointeeType();
3945       break;
3946     case Type::ConstantArray:
3947     case Type::IncompleteArray:
3948       // Losing element qualification here is fine.
3949       T = cast<ArrayType>(Ty)->getElementType();
3950       break;
3951     case Type::VariableArray: {
3952       // Losing element qualification here is fine.
3953       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3954 
3955       // Unknown size indication requires no size computation.
3956       // Otherwise, evaluate and record it.
3957       if (auto Size = VAT->getSizeExpr()) {
3958         if (!CSI->isVLATypeCaptured(VAT)) {
3959           RecordDecl *CapRecord = nullptr;
3960           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3961             CapRecord = LSI->Lambda;
3962           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3963             CapRecord = CRSI->TheRecordDecl;
3964           }
3965           if (CapRecord) {
3966             auto ExprLoc = Size->getExprLoc();
3967             auto SizeType = Context.getSizeType();
3968             // Build the non-static data member.
3969             auto Field =
3970                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3971                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3972                                   /*BW*/ nullptr, /*Mutable*/ false,
3973                                   /*InitStyle*/ ICIS_NoInit);
3974             Field->setImplicit(true);
3975             Field->setAccess(AS_private);
3976             Field->setCapturedVLAType(VAT);
3977             CapRecord->addDecl(Field);
3978 
3979             CSI->addVLATypeCapture(ExprLoc, SizeType);
3980           }
3981         }
3982       }
3983       T = VAT->getElementType();
3984       break;
3985     }
3986     case Type::FunctionProto:
3987     case Type::FunctionNoProto:
3988       T = cast<FunctionType>(Ty)->getReturnType();
3989       break;
3990     case Type::Paren:
3991     case Type::TypeOf:
3992     case Type::UnaryTransform:
3993     case Type::Attributed:
3994     case Type::SubstTemplateTypeParm:
3995     case Type::PackExpansion:
3996       // Keep walking after single level desugaring.
3997       T = T.getSingleStepDesugaredType(Context);
3998       break;
3999     case Type::Typedef:
4000       T = cast<TypedefType>(Ty)->desugar();
4001       break;
4002     case Type::Decltype:
4003       T = cast<DecltypeType>(Ty)->desugar();
4004       break;
4005     case Type::Auto:
4006     case Type::DeducedTemplateSpecialization:
4007       T = cast<DeducedType>(Ty)->getDeducedType();
4008       break;
4009     case Type::TypeOfExpr:
4010       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4011       break;
4012     case Type::Atomic:
4013       T = cast<AtomicType>(Ty)->getValueType();
4014       break;
4015     }
4016   } while (!T.isNull() && T->isVariablyModifiedType());
4017 }
4018 
4019 /// Build a sizeof or alignof expression given a type operand.
4020 ExprResult
4021 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4022                                      SourceLocation OpLoc,
4023                                      UnaryExprOrTypeTrait ExprKind,
4024                                      SourceRange R) {
4025   if (!TInfo)
4026     return ExprError();
4027 
4028   QualType T = TInfo->getType();
4029 
4030   if (!T->isDependentType() &&
4031       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4032     return ExprError();
4033 
4034   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4035     if (auto *TT = T->getAs<TypedefType>()) {
4036       for (auto I = FunctionScopes.rbegin(),
4037                 E = std::prev(FunctionScopes.rend());
4038            I != E; ++I) {
4039         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4040         if (CSI == nullptr)
4041           break;
4042         DeclContext *DC = nullptr;
4043         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4044           DC = LSI->CallOperator;
4045         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4046           DC = CRSI->TheCapturedDecl;
4047         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4048           DC = BSI->TheDecl;
4049         if (DC) {
4050           if (DC->containsDecl(TT->getDecl()))
4051             break;
4052           captureVariablyModifiedType(Context, T, CSI);
4053         }
4054       }
4055     }
4056   }
4057 
4058   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4059   return new (Context) UnaryExprOrTypeTraitExpr(
4060       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4061 }
4062 
4063 /// Build a sizeof or alignof expression given an expression
4064 /// operand.
4065 ExprResult
4066 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4067                                      UnaryExprOrTypeTrait ExprKind) {
4068   ExprResult PE = CheckPlaceholderExpr(E);
4069   if (PE.isInvalid())
4070     return ExprError();
4071 
4072   E = PE.get();
4073 
4074   // Verify that the operand is valid.
4075   bool isInvalid = false;
4076   if (E->isTypeDependent()) {
4077     // Delay type-checking for type-dependent expressions.
4078   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4079     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4080   } else if (ExprKind == UETT_VecStep) {
4081     isInvalid = CheckVecStepExpr(E);
4082   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4083       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4084       isInvalid = true;
4085   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4086     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4087     isInvalid = true;
4088   } else {
4089     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4090   }
4091 
4092   if (isInvalid)
4093     return ExprError();
4094 
4095   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4096     PE = TransformToPotentiallyEvaluated(E);
4097     if (PE.isInvalid()) return ExprError();
4098     E = PE.get();
4099   }
4100 
4101   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4102   return new (Context) UnaryExprOrTypeTraitExpr(
4103       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4104 }
4105 
4106 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4107 /// expr and the same for @c alignof and @c __alignof
4108 /// Note that the ArgRange is invalid if isType is false.
4109 ExprResult
4110 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4111                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4112                                     void *TyOrEx, SourceRange ArgRange) {
4113   // If error parsing type, ignore.
4114   if (!TyOrEx) return ExprError();
4115 
4116   if (IsType) {
4117     TypeSourceInfo *TInfo;
4118     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4119     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4120   }
4121 
4122   Expr *ArgEx = (Expr *)TyOrEx;
4123   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4124   return Result;
4125 }
4126 
4127 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4128                                      bool IsReal) {
4129   if (V.get()->isTypeDependent())
4130     return S.Context.DependentTy;
4131 
4132   // _Real and _Imag are only l-values for normal l-values.
4133   if (V.get()->getObjectKind() != OK_Ordinary) {
4134     V = S.DefaultLvalueConversion(V.get());
4135     if (V.isInvalid())
4136       return QualType();
4137   }
4138 
4139   // These operators return the element type of a complex type.
4140   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4141     return CT->getElementType();
4142 
4143   // Otherwise they pass through real integer and floating point types here.
4144   if (V.get()->getType()->isArithmeticType())
4145     return V.get()->getType();
4146 
4147   // Test for placeholders.
4148   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4149   if (PR.isInvalid()) return QualType();
4150   if (PR.get() != V.get()) {
4151     V = PR;
4152     return CheckRealImagOperand(S, V, Loc, IsReal);
4153   }
4154 
4155   // Reject anything else.
4156   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4157     << (IsReal ? "__real" : "__imag");
4158   return QualType();
4159 }
4160 
4161 
4162 
4163 ExprResult
4164 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4165                           tok::TokenKind Kind, Expr *Input) {
4166   UnaryOperatorKind Opc;
4167   switch (Kind) {
4168   default: llvm_unreachable("Unknown unary op!");
4169   case tok::plusplus:   Opc = UO_PostInc; break;
4170   case tok::minusminus: Opc = UO_PostDec; break;
4171   }
4172 
4173   // Since this might is a postfix expression, get rid of ParenListExprs.
4174   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4175   if (Result.isInvalid()) return ExprError();
4176   Input = Result.get();
4177 
4178   return BuildUnaryOp(S, OpLoc, Opc, Input);
4179 }
4180 
4181 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4182 ///
4183 /// \return true on error
4184 static bool checkArithmeticOnObjCPointer(Sema &S,
4185                                          SourceLocation opLoc,
4186                                          Expr *op) {
4187   assert(op->getType()->isObjCObjectPointerType());
4188   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4189       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4190     return false;
4191 
4192   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4193     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4194     << op->getSourceRange();
4195   return true;
4196 }
4197 
4198 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4199   auto *BaseNoParens = Base->IgnoreParens();
4200   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4201     return MSProp->getPropertyDecl()->getType()->isArrayType();
4202   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4203 }
4204 
4205 ExprResult
4206 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4207                               Expr *idx, SourceLocation rbLoc) {
4208   if (base && !base->getType().isNull() &&
4209       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4210     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4211                                     /*Length=*/nullptr, rbLoc);
4212 
4213   // Since this might be a postfix expression, get rid of ParenListExprs.
4214   if (isa<ParenListExpr>(base)) {
4215     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4216     if (result.isInvalid()) return ExprError();
4217     base = result.get();
4218   }
4219 
4220   // Handle any non-overload placeholder types in the base and index
4221   // expressions.  We can't handle overloads here because the other
4222   // operand might be an overloadable type, in which case the overload
4223   // resolution for the operator overload should get the first crack
4224   // at the overload.
4225   bool IsMSPropertySubscript = false;
4226   if (base->getType()->isNonOverloadPlaceholderType()) {
4227     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4228     if (!IsMSPropertySubscript) {
4229       ExprResult result = CheckPlaceholderExpr(base);
4230       if (result.isInvalid())
4231         return ExprError();
4232       base = result.get();
4233     }
4234   }
4235   if (idx->getType()->isNonOverloadPlaceholderType()) {
4236     ExprResult result = CheckPlaceholderExpr(idx);
4237     if (result.isInvalid()) return ExprError();
4238     idx = result.get();
4239   }
4240 
4241   // Build an unanalyzed expression if either operand is type-dependent.
4242   if (getLangOpts().CPlusPlus &&
4243       (base->isTypeDependent() || idx->isTypeDependent())) {
4244     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4245                                             VK_LValue, OK_Ordinary, rbLoc);
4246   }
4247 
4248   // MSDN, property (C++)
4249   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4250   // This attribute can also be used in the declaration of an empty array in a
4251   // class or structure definition. For example:
4252   // __declspec(property(get=GetX, put=PutX)) int x[];
4253   // The above statement indicates that x[] can be used with one or more array
4254   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4255   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4256   if (IsMSPropertySubscript) {
4257     // Build MS property subscript expression if base is MS property reference
4258     // or MS property subscript.
4259     return new (Context) MSPropertySubscriptExpr(
4260         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4261   }
4262 
4263   // Use C++ overloaded-operator rules if either operand has record
4264   // type.  The spec says to do this if either type is *overloadable*,
4265   // but enum types can't declare subscript operators or conversion
4266   // operators, so there's nothing interesting for overload resolution
4267   // to do if there aren't any record types involved.
4268   //
4269   // ObjC pointers have their own subscripting logic that is not tied
4270   // to overload resolution and so should not take this path.
4271   if (getLangOpts().CPlusPlus &&
4272       (base->getType()->isRecordType() ||
4273        (!base->getType()->isObjCObjectPointerType() &&
4274         idx->getType()->isRecordType()))) {
4275     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4276   }
4277 
4278   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4279 }
4280 
4281 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4282                                           Expr *LowerBound,
4283                                           SourceLocation ColonLoc, Expr *Length,
4284                                           SourceLocation RBLoc) {
4285   if (Base->getType()->isPlaceholderType() &&
4286       !Base->getType()->isSpecificPlaceholderType(
4287           BuiltinType::OMPArraySection)) {
4288     ExprResult Result = CheckPlaceholderExpr(Base);
4289     if (Result.isInvalid())
4290       return ExprError();
4291     Base = Result.get();
4292   }
4293   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4294     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4295     if (Result.isInvalid())
4296       return ExprError();
4297     Result = DefaultLvalueConversion(Result.get());
4298     if (Result.isInvalid())
4299       return ExprError();
4300     LowerBound = Result.get();
4301   }
4302   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4303     ExprResult Result = CheckPlaceholderExpr(Length);
4304     if (Result.isInvalid())
4305       return ExprError();
4306     Result = DefaultLvalueConversion(Result.get());
4307     if (Result.isInvalid())
4308       return ExprError();
4309     Length = Result.get();
4310   }
4311 
4312   // Build an unanalyzed expression if either operand is type-dependent.
4313   if (Base->isTypeDependent() ||
4314       (LowerBound &&
4315        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4316       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4317     return new (Context)
4318         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4319                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4320   }
4321 
4322   // Perform default conversions.
4323   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4324   QualType ResultTy;
4325   if (OriginalTy->isAnyPointerType()) {
4326     ResultTy = OriginalTy->getPointeeType();
4327   } else if (OriginalTy->isArrayType()) {
4328     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4329   } else {
4330     return ExprError(
4331         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4332         << Base->getSourceRange());
4333   }
4334   // C99 6.5.2.1p1
4335   if (LowerBound) {
4336     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4337                                                       LowerBound);
4338     if (Res.isInvalid())
4339       return ExprError(Diag(LowerBound->getExprLoc(),
4340                             diag::err_omp_typecheck_section_not_integer)
4341                        << 0 << LowerBound->getSourceRange());
4342     LowerBound = Res.get();
4343 
4344     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4345         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4346       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4347           << 0 << LowerBound->getSourceRange();
4348   }
4349   if (Length) {
4350     auto Res =
4351         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4352     if (Res.isInvalid())
4353       return ExprError(Diag(Length->getExprLoc(),
4354                             diag::err_omp_typecheck_section_not_integer)
4355                        << 1 << Length->getSourceRange());
4356     Length = Res.get();
4357 
4358     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4359         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4360       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4361           << 1 << Length->getSourceRange();
4362   }
4363 
4364   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4365   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4366   // type. Note that functions are not objects, and that (in C99 parlance)
4367   // incomplete types are not object types.
4368   if (ResultTy->isFunctionType()) {
4369     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4370         << ResultTy << Base->getSourceRange();
4371     return ExprError();
4372   }
4373 
4374   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4375                           diag::err_omp_section_incomplete_type, Base))
4376     return ExprError();
4377 
4378   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4379     llvm::APSInt LowerBoundValue;
4380     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4381       // OpenMP 4.5, [2.4 Array Sections]
4382       // The array section must be a subset of the original array.
4383       if (LowerBoundValue.isNegative()) {
4384         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4385             << LowerBound->getSourceRange();
4386         return ExprError();
4387       }
4388     }
4389   }
4390 
4391   if (Length) {
4392     llvm::APSInt LengthValue;
4393     if (Length->EvaluateAsInt(LengthValue, Context)) {
4394       // OpenMP 4.5, [2.4 Array Sections]
4395       // The length must evaluate to non-negative integers.
4396       if (LengthValue.isNegative()) {
4397         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4398             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4399             << Length->getSourceRange();
4400         return ExprError();
4401       }
4402     }
4403   } else if (ColonLoc.isValid() &&
4404              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4405                                       !OriginalTy->isVariableArrayType()))) {
4406     // OpenMP 4.5, [2.4 Array Sections]
4407     // When the size of the array dimension is not known, the length must be
4408     // specified explicitly.
4409     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4410         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4411     return ExprError();
4412   }
4413 
4414   if (!Base->getType()->isSpecificPlaceholderType(
4415           BuiltinType::OMPArraySection)) {
4416     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4417     if (Result.isInvalid())
4418       return ExprError();
4419     Base = Result.get();
4420   }
4421   return new (Context)
4422       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4423                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4424 }
4425 
4426 ExprResult
4427 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4428                                       Expr *Idx, SourceLocation RLoc) {
4429   Expr *LHSExp = Base;
4430   Expr *RHSExp = Idx;
4431 
4432   ExprValueKind VK = VK_LValue;
4433   ExprObjectKind OK = OK_Ordinary;
4434 
4435   // Per C++ core issue 1213, the result is an xvalue if either operand is
4436   // a non-lvalue array, and an lvalue otherwise.
4437   if (getLangOpts().CPlusPlus11) {
4438     for (auto *Op : {LHSExp, RHSExp}) {
4439       Op = Op->IgnoreImplicit();
4440       if (Op->getType()->isArrayType() && !Op->isLValue())
4441         VK = VK_XValue;
4442     }
4443   }
4444 
4445   // Perform default conversions.
4446   if (!LHSExp->getType()->getAs<VectorType>()) {
4447     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4448     if (Result.isInvalid())
4449       return ExprError();
4450     LHSExp = Result.get();
4451   }
4452   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4453   if (Result.isInvalid())
4454     return ExprError();
4455   RHSExp = Result.get();
4456 
4457   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4458 
4459   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4460   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4461   // in the subscript position. As a result, we need to derive the array base
4462   // and index from the expression types.
4463   Expr *BaseExpr, *IndexExpr;
4464   QualType ResultType;
4465   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4466     BaseExpr = LHSExp;
4467     IndexExpr = RHSExp;
4468     ResultType = Context.DependentTy;
4469   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4470     BaseExpr = LHSExp;
4471     IndexExpr = RHSExp;
4472     ResultType = PTy->getPointeeType();
4473   } else if (const ObjCObjectPointerType *PTy =
4474                LHSTy->getAs<ObjCObjectPointerType>()) {
4475     BaseExpr = LHSExp;
4476     IndexExpr = RHSExp;
4477 
4478     // Use custom logic if this should be the pseudo-object subscript
4479     // expression.
4480     if (!LangOpts.isSubscriptPointerArithmetic())
4481       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4482                                           nullptr);
4483 
4484     ResultType = PTy->getPointeeType();
4485   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4486      // Handle the uncommon case of "123[Ptr]".
4487     BaseExpr = RHSExp;
4488     IndexExpr = LHSExp;
4489     ResultType = PTy->getPointeeType();
4490   } else if (const ObjCObjectPointerType *PTy =
4491                RHSTy->getAs<ObjCObjectPointerType>()) {
4492      // Handle the uncommon case of "123[Ptr]".
4493     BaseExpr = RHSExp;
4494     IndexExpr = LHSExp;
4495     ResultType = PTy->getPointeeType();
4496     if (!LangOpts.isSubscriptPointerArithmetic()) {
4497       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4498         << ResultType << BaseExpr->getSourceRange();
4499       return ExprError();
4500     }
4501   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4502     BaseExpr = LHSExp;    // vectors: V[123]
4503     IndexExpr = RHSExp;
4504     // We apply C++ DR1213 to vector subscripting too.
4505     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4506       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4507       if (Materialized.isInvalid())
4508         return ExprError();
4509       LHSExp = Materialized.get();
4510     }
4511     VK = LHSExp->getValueKind();
4512     if (VK != VK_RValue)
4513       OK = OK_VectorComponent;
4514 
4515     ResultType = VTy->getElementType();
4516     QualType BaseType = BaseExpr->getType();
4517     Qualifiers BaseQuals = BaseType.getQualifiers();
4518     Qualifiers MemberQuals = ResultType.getQualifiers();
4519     Qualifiers Combined = BaseQuals + MemberQuals;
4520     if (Combined != MemberQuals)
4521       ResultType = Context.getQualifiedType(ResultType, Combined);
4522   } else if (LHSTy->isArrayType()) {
4523     // If we see an array that wasn't promoted by
4524     // DefaultFunctionArrayLvalueConversion, it must be an array that
4525     // wasn't promoted because of the C90 rule that doesn't
4526     // allow promoting non-lvalue arrays.  Warn, then
4527     // force the promotion here.
4528     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4529         << LHSExp->getSourceRange();
4530     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4531                                CK_ArrayToPointerDecay).get();
4532     LHSTy = LHSExp->getType();
4533 
4534     BaseExpr = LHSExp;
4535     IndexExpr = RHSExp;
4536     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4537   } else if (RHSTy->isArrayType()) {
4538     // Same as previous, except for 123[f().a] case
4539     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4540         << RHSExp->getSourceRange();
4541     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4542                                CK_ArrayToPointerDecay).get();
4543     RHSTy = RHSExp->getType();
4544 
4545     BaseExpr = RHSExp;
4546     IndexExpr = LHSExp;
4547     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4548   } else {
4549     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4550        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4551   }
4552   // C99 6.5.2.1p1
4553   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4554     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4555                      << IndexExpr->getSourceRange());
4556 
4557   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4558        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4559          && !IndexExpr->isTypeDependent())
4560     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4561 
4562   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4563   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4564   // type. Note that Functions are not objects, and that (in C99 parlance)
4565   // incomplete types are not object types.
4566   if (ResultType->isFunctionType()) {
4567     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4568         << ResultType << BaseExpr->getSourceRange();
4569     return ExprError();
4570   }
4571 
4572   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4573     // GNU extension: subscripting on pointer to void
4574     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4575       << BaseExpr->getSourceRange();
4576 
4577     // C forbids expressions of unqualified void type from being l-values.
4578     // See IsCForbiddenLValueType.
4579     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4580   } else if (!ResultType->isDependentType() &&
4581       RequireCompleteType(LLoc, ResultType,
4582                           diag::err_subscript_incomplete_type, BaseExpr))
4583     return ExprError();
4584 
4585   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4586          !ResultType.isCForbiddenLValueType());
4587 
4588   return new (Context)
4589       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4590 }
4591 
4592 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4593                                   ParmVarDecl *Param) {
4594   if (Param->hasUnparsedDefaultArg()) {
4595     Diag(CallLoc,
4596          diag::err_use_of_default_argument_to_function_declared_later) <<
4597       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4598     Diag(UnparsedDefaultArgLocs[Param],
4599          diag::note_default_argument_declared_here);
4600     return true;
4601   }
4602 
4603   if (Param->hasUninstantiatedDefaultArg()) {
4604     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4605 
4606     EnterExpressionEvaluationContext EvalContext(
4607         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4608 
4609     // Instantiate the expression.
4610     //
4611     // FIXME: Pass in a correct Pattern argument, otherwise
4612     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4613     //
4614     // template<typename T>
4615     // struct A {
4616     //   static int FooImpl();
4617     //
4618     //   template<typename Tp>
4619     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4620     //   // template argument list [[T], [Tp]], should be [[Tp]].
4621     //   friend A<Tp> Foo(int a);
4622     // };
4623     //
4624     // template<typename T>
4625     // A<T> Foo(int a = A<T>::FooImpl());
4626     MultiLevelTemplateArgumentList MutiLevelArgList
4627       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4628 
4629     InstantiatingTemplate Inst(*this, CallLoc, Param,
4630                                MutiLevelArgList.getInnermost());
4631     if (Inst.isInvalid())
4632       return true;
4633     if (Inst.isAlreadyInstantiating()) {
4634       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4635       Param->setInvalidDecl();
4636       return true;
4637     }
4638 
4639     ExprResult Result;
4640     {
4641       // C++ [dcl.fct.default]p5:
4642       //   The names in the [default argument] expression are bound, and
4643       //   the semantic constraints are checked, at the point where the
4644       //   default argument expression appears.
4645       ContextRAII SavedContext(*this, FD);
4646       LocalInstantiationScope Local(*this);
4647       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4648                                 /*DirectInit*/false);
4649     }
4650     if (Result.isInvalid())
4651       return true;
4652 
4653     // Check the expression as an initializer for the parameter.
4654     InitializedEntity Entity
4655       = InitializedEntity::InitializeParameter(Context, Param);
4656     InitializationKind Kind = InitializationKind::CreateCopy(
4657         Param->getLocation(),
4658         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4659     Expr *ResultE = Result.getAs<Expr>();
4660 
4661     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4662     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4663     if (Result.isInvalid())
4664       return true;
4665 
4666     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4667                                  Param->getOuterLocStart());
4668     if (Result.isInvalid())
4669       return true;
4670 
4671     // Remember the instantiated default argument.
4672     Param->setDefaultArg(Result.getAs<Expr>());
4673     if (ASTMutationListener *L = getASTMutationListener()) {
4674       L->DefaultArgumentInstantiated(Param);
4675     }
4676   }
4677 
4678   // If the default argument expression is not set yet, we are building it now.
4679   if (!Param->hasInit()) {
4680     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4681     Param->setInvalidDecl();
4682     return true;
4683   }
4684 
4685   // If the default expression creates temporaries, we need to
4686   // push them to the current stack of expression temporaries so they'll
4687   // be properly destroyed.
4688   // FIXME: We should really be rebuilding the default argument with new
4689   // bound temporaries; see the comment in PR5810.
4690   // We don't need to do that with block decls, though, because
4691   // blocks in default argument expression can never capture anything.
4692   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4693     // Set the "needs cleanups" bit regardless of whether there are
4694     // any explicit objects.
4695     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4696 
4697     // Append all the objects to the cleanup list.  Right now, this
4698     // should always be a no-op, because blocks in default argument
4699     // expressions should never be able to capture anything.
4700     assert(!Init->getNumObjects() &&
4701            "default argument expression has capturing blocks?");
4702   }
4703 
4704   // We already type-checked the argument, so we know it works.
4705   // Just mark all of the declarations in this potentially-evaluated expression
4706   // as being "referenced".
4707   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4708                                    /*SkipLocalVariables=*/true);
4709   return false;
4710 }
4711 
4712 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4713                                         FunctionDecl *FD, ParmVarDecl *Param) {
4714   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4715     return ExprError();
4716   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4717 }
4718 
4719 Sema::VariadicCallType
4720 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4721                           Expr *Fn) {
4722   if (Proto && Proto->isVariadic()) {
4723     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4724       return VariadicConstructor;
4725     else if (Fn && Fn->getType()->isBlockPointerType())
4726       return VariadicBlock;
4727     else if (FDecl) {
4728       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4729         if (Method->isInstance())
4730           return VariadicMethod;
4731     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4732       return VariadicMethod;
4733     return VariadicFunction;
4734   }
4735   return VariadicDoesNotApply;
4736 }
4737 
4738 namespace {
4739 class FunctionCallCCC : public FunctionCallFilterCCC {
4740 public:
4741   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4742                   unsigned NumArgs, MemberExpr *ME)
4743       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4744         FunctionName(FuncName) {}
4745 
4746   bool ValidateCandidate(const TypoCorrection &candidate) override {
4747     if (!candidate.getCorrectionSpecifier() ||
4748         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4749       return false;
4750     }
4751 
4752     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4753   }
4754 
4755 private:
4756   const IdentifierInfo *const FunctionName;
4757 };
4758 }
4759 
4760 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4761                                                FunctionDecl *FDecl,
4762                                                ArrayRef<Expr *> Args) {
4763   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4764   DeclarationName FuncName = FDecl->getDeclName();
4765   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4766 
4767   if (TypoCorrection Corrected = S.CorrectTypo(
4768           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4769           S.getScopeForContext(S.CurContext), nullptr,
4770           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4771                                              Args.size(), ME),
4772           Sema::CTK_ErrorRecovery)) {
4773     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4774       if (Corrected.isOverloaded()) {
4775         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4776         OverloadCandidateSet::iterator Best;
4777         for (NamedDecl *CD : Corrected) {
4778           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4779             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4780                                    OCS);
4781         }
4782         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4783         case OR_Success:
4784           ND = Best->FoundDecl;
4785           Corrected.setCorrectionDecl(ND);
4786           break;
4787         default:
4788           break;
4789         }
4790       }
4791       ND = ND->getUnderlyingDecl();
4792       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4793         return Corrected;
4794     }
4795   }
4796   return TypoCorrection();
4797 }
4798 
4799 /// ConvertArgumentsForCall - Converts the arguments specified in
4800 /// Args/NumArgs to the parameter types of the function FDecl with
4801 /// function prototype Proto. Call is the call expression itself, and
4802 /// Fn is the function expression. For a C++ member function, this
4803 /// routine does not attempt to convert the object argument. Returns
4804 /// true if the call is ill-formed.
4805 bool
4806 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4807                               FunctionDecl *FDecl,
4808                               const FunctionProtoType *Proto,
4809                               ArrayRef<Expr *> Args,
4810                               SourceLocation RParenLoc,
4811                               bool IsExecConfig) {
4812   // Bail out early if calling a builtin with custom typechecking.
4813   if (FDecl)
4814     if (unsigned ID = FDecl->getBuiltinID())
4815       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4816         return false;
4817 
4818   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4819   // assignment, to the types of the corresponding parameter, ...
4820   unsigned NumParams = Proto->getNumParams();
4821   bool Invalid = false;
4822   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4823   unsigned FnKind = Fn->getType()->isBlockPointerType()
4824                        ? 1 /* block */
4825                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4826                                        : 0 /* function */);
4827 
4828   // If too few arguments are available (and we don't have default
4829   // arguments for the remaining parameters), don't make the call.
4830   if (Args.size() < NumParams) {
4831     if (Args.size() < MinArgs) {
4832       TypoCorrection TC;
4833       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4834         unsigned diag_id =
4835             MinArgs == NumParams && !Proto->isVariadic()
4836                 ? diag::err_typecheck_call_too_few_args_suggest
4837                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4838         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4839                                         << static_cast<unsigned>(Args.size())
4840                                         << TC.getCorrectionRange());
4841       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4842         Diag(RParenLoc,
4843              MinArgs == NumParams && !Proto->isVariadic()
4844                  ? diag::err_typecheck_call_too_few_args_one
4845                  : diag::err_typecheck_call_too_few_args_at_least_one)
4846             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4847       else
4848         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4849                             ? diag::err_typecheck_call_too_few_args
4850                             : diag::err_typecheck_call_too_few_args_at_least)
4851             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4852             << Fn->getSourceRange();
4853 
4854       // Emit the location of the prototype.
4855       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4856         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4857 
4858       return true;
4859     }
4860     Call->setNumArgs(Context, NumParams);
4861   }
4862 
4863   // If too many are passed and not variadic, error on the extras and drop
4864   // them.
4865   if (Args.size() > NumParams) {
4866     if (!Proto->isVariadic()) {
4867       TypoCorrection TC;
4868       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4869         unsigned diag_id =
4870             MinArgs == NumParams && !Proto->isVariadic()
4871                 ? diag::err_typecheck_call_too_many_args_suggest
4872                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4873         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4874                                         << static_cast<unsigned>(Args.size())
4875                                         << TC.getCorrectionRange());
4876       } else if (NumParams == 1 && FDecl &&
4877                  FDecl->getParamDecl(0)->getDeclName())
4878         Diag(Args[NumParams]->getBeginLoc(),
4879              MinArgs == NumParams
4880                  ? diag::err_typecheck_call_too_many_args_one
4881                  : diag::err_typecheck_call_too_many_args_at_most_one)
4882             << FnKind << FDecl->getParamDecl(0)
4883             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4884             << SourceRange(Args[NumParams]->getBeginLoc(),
4885                            Args.back()->getEndLoc());
4886       else
4887         Diag(Args[NumParams]->getBeginLoc(),
4888              MinArgs == NumParams
4889                  ? diag::err_typecheck_call_too_many_args
4890                  : diag::err_typecheck_call_too_many_args_at_most)
4891             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4892             << Fn->getSourceRange()
4893             << SourceRange(Args[NumParams]->getBeginLoc(),
4894                            Args.back()->getEndLoc());
4895 
4896       // Emit the location of the prototype.
4897       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4898         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
4899 
4900       // This deletes the extra arguments.
4901       Call->setNumArgs(Context, NumParams);
4902       return true;
4903     }
4904   }
4905   SmallVector<Expr *, 8> AllArgs;
4906   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4907 
4908   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
4909                                    AllArgs, CallType);
4910   if (Invalid)
4911     return true;
4912   unsigned TotalNumArgs = AllArgs.size();
4913   for (unsigned i = 0; i < TotalNumArgs; ++i)
4914     Call->setArg(i, AllArgs[i]);
4915 
4916   return false;
4917 }
4918 
4919 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4920                                   const FunctionProtoType *Proto,
4921                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4922                                   SmallVectorImpl<Expr *> &AllArgs,
4923                                   VariadicCallType CallType, bool AllowExplicit,
4924                                   bool IsListInitialization) {
4925   unsigned NumParams = Proto->getNumParams();
4926   bool Invalid = false;
4927   size_t ArgIx = 0;
4928   // Continue to check argument types (even if we have too few/many args).
4929   for (unsigned i = FirstParam; i < NumParams; i++) {
4930     QualType ProtoArgType = Proto->getParamType(i);
4931 
4932     Expr *Arg;
4933     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4934     if (ArgIx < Args.size()) {
4935       Arg = Args[ArgIx++];
4936 
4937       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
4938                               diag::err_call_incomplete_argument, Arg))
4939         return true;
4940 
4941       // Strip the unbridged-cast placeholder expression off, if applicable.
4942       bool CFAudited = false;
4943       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4944           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4945           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4946         Arg = stripARCUnbridgedCast(Arg);
4947       else if (getLangOpts().ObjCAutoRefCount &&
4948                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4949                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4950         CFAudited = true;
4951 
4952       if (Proto->getExtParameterInfo(i).isNoEscape())
4953         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4954           BE->getBlockDecl()->setDoesNotEscape();
4955 
4956       InitializedEntity Entity =
4957           Param ? InitializedEntity::InitializeParameter(Context, Param,
4958                                                          ProtoArgType)
4959                 : InitializedEntity::InitializeParameter(
4960                       Context, ProtoArgType, Proto->isParamConsumed(i));
4961 
4962       // Remember that parameter belongs to a CF audited API.
4963       if (CFAudited)
4964         Entity.setParameterCFAudited();
4965 
4966       ExprResult ArgE = PerformCopyInitialization(
4967           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4968       if (ArgE.isInvalid())
4969         return true;
4970 
4971       Arg = ArgE.getAs<Expr>();
4972     } else {
4973       assert(Param && "can't use default arguments without a known callee");
4974 
4975       ExprResult ArgExpr =
4976         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4977       if (ArgExpr.isInvalid())
4978         return true;
4979 
4980       Arg = ArgExpr.getAs<Expr>();
4981     }
4982 
4983     // Check for array bounds violations for each argument to the call. This
4984     // check only triggers warnings when the argument isn't a more complex Expr
4985     // with its own checking, such as a BinaryOperator.
4986     CheckArrayAccess(Arg);
4987 
4988     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4989     CheckStaticArrayArgument(CallLoc, Param, Arg);
4990 
4991     AllArgs.push_back(Arg);
4992   }
4993 
4994   // If this is a variadic call, handle args passed through "...".
4995   if (CallType != VariadicDoesNotApply) {
4996     // Assume that extern "C" functions with variadic arguments that
4997     // return __unknown_anytype aren't *really* variadic.
4998     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4999         FDecl->isExternC()) {
5000       for (Expr *A : Args.slice(ArgIx)) {
5001         QualType paramType; // ignored
5002         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5003         Invalid |= arg.isInvalid();
5004         AllArgs.push_back(arg.get());
5005       }
5006 
5007     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5008     } else {
5009       for (Expr *A : Args.slice(ArgIx)) {
5010         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5011         Invalid |= Arg.isInvalid();
5012         AllArgs.push_back(Arg.get());
5013       }
5014     }
5015 
5016     // Check for array bounds violations.
5017     for (Expr *A : Args.slice(ArgIx))
5018       CheckArrayAccess(A);
5019   }
5020   return Invalid;
5021 }
5022 
5023 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5024   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5025   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5026     TL = DTL.getOriginalLoc();
5027   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5028     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5029       << ATL.getLocalSourceRange();
5030 }
5031 
5032 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5033 /// array parameter, check that it is non-null, and that if it is formed by
5034 /// array-to-pointer decay, the underlying array is sufficiently large.
5035 ///
5036 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5037 /// array type derivation, then for each call to the function, the value of the
5038 /// corresponding actual argument shall provide access to the first element of
5039 /// an array with at least as many elements as specified by the size expression.
5040 void
5041 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5042                                ParmVarDecl *Param,
5043                                const Expr *ArgExpr) {
5044   // Static array parameters are not supported in C++.
5045   if (!Param || getLangOpts().CPlusPlus)
5046     return;
5047 
5048   QualType OrigTy = Param->getOriginalType();
5049 
5050   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5051   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5052     return;
5053 
5054   if (ArgExpr->isNullPointerConstant(Context,
5055                                      Expr::NPC_NeverValueDependent)) {
5056     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5057     DiagnoseCalleeStaticArrayParam(*this, Param);
5058     return;
5059   }
5060 
5061   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5062   if (!CAT)
5063     return;
5064 
5065   const ConstantArrayType *ArgCAT =
5066     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5067   if (!ArgCAT)
5068     return;
5069 
5070   if (ArgCAT->getSize().ult(CAT->getSize())) {
5071     Diag(CallLoc, diag::warn_static_array_too_small)
5072       << ArgExpr->getSourceRange()
5073       << (unsigned) ArgCAT->getSize().getZExtValue()
5074       << (unsigned) CAT->getSize().getZExtValue();
5075     DiagnoseCalleeStaticArrayParam(*this, Param);
5076   }
5077 }
5078 
5079 /// Given a function expression of unknown-any type, try to rebuild it
5080 /// to have a function type.
5081 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5082 
5083 /// Is the given type a placeholder that we need to lower out
5084 /// immediately during argument processing?
5085 static bool isPlaceholderToRemoveAsArg(QualType type) {
5086   // Placeholders are never sugared.
5087   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5088   if (!placeholder) return false;
5089 
5090   switch (placeholder->getKind()) {
5091   // Ignore all the non-placeholder types.
5092 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5093   case BuiltinType::Id:
5094 #include "clang/Basic/OpenCLImageTypes.def"
5095 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5096   case BuiltinType::Id:
5097 #include "clang/Basic/OpenCLExtensionTypes.def"
5098 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5099 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5100 #include "clang/AST/BuiltinTypes.def"
5101     return false;
5102 
5103   // We cannot lower out overload sets; they might validly be resolved
5104   // by the call machinery.
5105   case BuiltinType::Overload:
5106     return false;
5107 
5108   // Unbridged casts in ARC can be handled in some call positions and
5109   // should be left in place.
5110   case BuiltinType::ARCUnbridgedCast:
5111     return false;
5112 
5113   // Pseudo-objects should be converted as soon as possible.
5114   case BuiltinType::PseudoObject:
5115     return true;
5116 
5117   // The debugger mode could theoretically but currently does not try
5118   // to resolve unknown-typed arguments based on known parameter types.
5119   case BuiltinType::UnknownAny:
5120     return true;
5121 
5122   // These are always invalid as call arguments and should be reported.
5123   case BuiltinType::BoundMember:
5124   case BuiltinType::BuiltinFn:
5125   case BuiltinType::OMPArraySection:
5126     return true;
5127 
5128   }
5129   llvm_unreachable("bad builtin type kind");
5130 }
5131 
5132 /// Check an argument list for placeholders that we won't try to
5133 /// handle later.
5134 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5135   // Apply this processing to all the arguments at once instead of
5136   // dying at the first failure.
5137   bool hasInvalid = false;
5138   for (size_t i = 0, e = args.size(); i != e; i++) {
5139     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5140       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5141       if (result.isInvalid()) hasInvalid = true;
5142       else args[i] = result.get();
5143     } else if (hasInvalid) {
5144       (void)S.CorrectDelayedTyposInExpr(args[i]);
5145     }
5146   }
5147   return hasInvalid;
5148 }
5149 
5150 /// If a builtin function has a pointer argument with no explicit address
5151 /// space, then it should be able to accept a pointer to any address
5152 /// space as input.  In order to do this, we need to replace the
5153 /// standard builtin declaration with one that uses the same address space
5154 /// as the call.
5155 ///
5156 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5157 ///                  it does not contain any pointer arguments without
5158 ///                  an address space qualifer.  Otherwise the rewritten
5159 ///                  FunctionDecl is returned.
5160 /// TODO: Handle pointer return types.
5161 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5162                                                 const FunctionDecl *FDecl,
5163                                                 MultiExprArg ArgExprs) {
5164 
5165   QualType DeclType = FDecl->getType();
5166   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5167 
5168   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5169       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5170     return nullptr;
5171 
5172   bool NeedsNewDecl = false;
5173   unsigned i = 0;
5174   SmallVector<QualType, 8> OverloadParams;
5175 
5176   for (QualType ParamType : FT->param_types()) {
5177 
5178     // Convert array arguments to pointer to simplify type lookup.
5179     ExprResult ArgRes =
5180         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5181     if (ArgRes.isInvalid())
5182       return nullptr;
5183     Expr *Arg = ArgRes.get();
5184     QualType ArgType = Arg->getType();
5185     if (!ParamType->isPointerType() ||
5186         ParamType.getQualifiers().hasAddressSpace() ||
5187         !ArgType->isPointerType() ||
5188         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5189       OverloadParams.push_back(ParamType);
5190       continue;
5191     }
5192 
5193     QualType PointeeType = ParamType->getPointeeType();
5194     if (PointeeType.getQualifiers().hasAddressSpace())
5195       continue;
5196 
5197     NeedsNewDecl = true;
5198     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5199 
5200     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5201     OverloadParams.push_back(Context.getPointerType(PointeeType));
5202   }
5203 
5204   if (!NeedsNewDecl)
5205     return nullptr;
5206 
5207   FunctionProtoType::ExtProtoInfo EPI;
5208   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5209                                                 OverloadParams, EPI);
5210   DeclContext *Parent = Context.getTranslationUnitDecl();
5211   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5212                                                     FDecl->getLocation(),
5213                                                     FDecl->getLocation(),
5214                                                     FDecl->getIdentifier(),
5215                                                     OverloadTy,
5216                                                     /*TInfo=*/nullptr,
5217                                                     SC_Extern, false,
5218                                                     /*hasPrototype=*/true);
5219   SmallVector<ParmVarDecl*, 16> Params;
5220   FT = cast<FunctionProtoType>(OverloadTy);
5221   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5222     QualType ParamType = FT->getParamType(i);
5223     ParmVarDecl *Parm =
5224         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5225                                 SourceLocation(), nullptr, ParamType,
5226                                 /*TInfo=*/nullptr, SC_None, nullptr);
5227     Parm->setScopeInfo(0, i);
5228     Params.push_back(Parm);
5229   }
5230   OverloadDecl->setParams(Params);
5231   return OverloadDecl;
5232 }
5233 
5234 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5235                                     FunctionDecl *Callee,
5236                                     MultiExprArg ArgExprs) {
5237   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5238   // similar attributes) really don't like it when functions are called with an
5239   // invalid number of args.
5240   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5241                          /*PartialOverloading=*/false) &&
5242       !Callee->isVariadic())
5243     return;
5244   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5245     return;
5246 
5247   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5248     S.Diag(Fn->getBeginLoc(),
5249            isa<CXXMethodDecl>(Callee)
5250                ? diag::err_ovl_no_viable_member_function_in_call
5251                : diag::err_ovl_no_viable_function_in_call)
5252         << Callee << Callee->getSourceRange();
5253     S.Diag(Callee->getLocation(),
5254            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5255         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5256     return;
5257   }
5258 }
5259 
5260 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5261     const UnresolvedMemberExpr *const UME, Sema &S) {
5262 
5263   const auto GetFunctionLevelDCIfCXXClass =
5264       [](Sema &S) -> const CXXRecordDecl * {
5265     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5266     if (!DC || !DC->getParent())
5267       return nullptr;
5268 
5269     // If the call to some member function was made from within a member
5270     // function body 'M' return return 'M's parent.
5271     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5272       return MD->getParent()->getCanonicalDecl();
5273     // else the call was made from within a default member initializer of a
5274     // class, so return the class.
5275     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5276       return RD->getCanonicalDecl();
5277     return nullptr;
5278   };
5279   // If our DeclContext is neither a member function nor a class (in the
5280   // case of a lambda in a default member initializer), we can't have an
5281   // enclosing 'this'.
5282 
5283   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5284   if (!CurParentClass)
5285     return false;
5286 
5287   // The naming class for implicit member functions call is the class in which
5288   // name lookup starts.
5289   const CXXRecordDecl *const NamingClass =
5290       UME->getNamingClass()->getCanonicalDecl();
5291   assert(NamingClass && "Must have naming class even for implicit access");
5292 
5293   // If the unresolved member functions were found in a 'naming class' that is
5294   // related (either the same or derived from) to the class that contains the
5295   // member function that itself contained the implicit member access.
5296 
5297   return CurParentClass == NamingClass ||
5298          CurParentClass->isDerivedFrom(NamingClass);
5299 }
5300 
5301 static void
5302 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5303     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5304 
5305   if (!UME)
5306     return;
5307 
5308   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5309   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5310   // already been captured, or if this is an implicit member function call (if
5311   // it isn't, an attempt to capture 'this' should already have been made).
5312   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5313       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5314     return;
5315 
5316   // Check if the naming class in which the unresolved members were found is
5317   // related (same as or is a base of) to the enclosing class.
5318 
5319   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5320     return;
5321 
5322 
5323   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5324   // If the enclosing function is not dependent, then this lambda is
5325   // capture ready, so if we can capture this, do so.
5326   if (!EnclosingFunctionCtx->isDependentContext()) {
5327     // If the current lambda and all enclosing lambdas can capture 'this' -
5328     // then go ahead and capture 'this' (since our unresolved overload set
5329     // contains at least one non-static member function).
5330     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5331       S.CheckCXXThisCapture(CallLoc);
5332   } else if (S.CurContext->isDependentContext()) {
5333     // ... since this is an implicit member reference, that might potentially
5334     // involve a 'this' capture, mark 'this' for potential capture in
5335     // enclosing lambdas.
5336     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5337       CurLSI->addPotentialThisCapture(CallLoc);
5338   }
5339 }
5340 
5341 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5342 /// This provides the location of the left/right parens and a list of comma
5343 /// locations.
5344 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5345                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5346                                Expr *ExecConfig, bool IsExecConfig) {
5347   // Since this might be a postfix expression, get rid of ParenListExprs.
5348   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5349   if (Result.isInvalid()) return ExprError();
5350   Fn = Result.get();
5351 
5352   if (checkArgsForPlaceholders(*this, ArgExprs))
5353     return ExprError();
5354 
5355   if (getLangOpts().CPlusPlus) {
5356     // If this is a pseudo-destructor expression, build the call immediately.
5357     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5358       if (!ArgExprs.empty()) {
5359         // Pseudo-destructor calls should not have any arguments.
5360         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5361             << FixItHint::CreateRemoval(
5362                    SourceRange(ArgExprs.front()->getBeginLoc(),
5363                                ArgExprs.back()->getEndLoc()));
5364       }
5365 
5366       return new (Context)
5367           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5368     }
5369     if (Fn->getType() == Context.PseudoObjectTy) {
5370       ExprResult result = CheckPlaceholderExpr(Fn);
5371       if (result.isInvalid()) return ExprError();
5372       Fn = result.get();
5373     }
5374 
5375     // Determine whether this is a dependent call inside a C++ template,
5376     // in which case we won't do any semantic analysis now.
5377     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5378       if (ExecConfig) {
5379         return new (Context) CUDAKernelCallExpr(
5380             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5381             Context.DependentTy, VK_RValue, RParenLoc);
5382       } else {
5383 
5384         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5385             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5386             Fn->getBeginLoc());
5387 
5388         return new (Context) CallExpr(
5389             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5390       }
5391     }
5392 
5393     // Determine whether this is a call to an object (C++ [over.call.object]).
5394     if (Fn->getType()->isRecordType())
5395       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5396                                           RParenLoc);
5397 
5398     if (Fn->getType() == Context.UnknownAnyTy) {
5399       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5400       if (result.isInvalid()) return ExprError();
5401       Fn = result.get();
5402     }
5403 
5404     if (Fn->getType() == Context.BoundMemberTy) {
5405       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5406                                        RParenLoc);
5407     }
5408   }
5409 
5410   // Check for overloaded calls.  This can happen even in C due to extensions.
5411   if (Fn->getType() == Context.OverloadTy) {
5412     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5413 
5414     // We aren't supposed to apply this logic if there's an '&' involved.
5415     if (!find.HasFormOfMemberPointer) {
5416       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5417         return new (Context) CallExpr(
5418             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5419       OverloadExpr *ovl = find.Expression;
5420       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5421         return BuildOverloadedCallExpr(
5422             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5423             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5424       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5425                                        RParenLoc);
5426     }
5427   }
5428 
5429   // If we're directly calling a function, get the appropriate declaration.
5430   if (Fn->getType() == Context.UnknownAnyTy) {
5431     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5432     if (result.isInvalid()) return ExprError();
5433     Fn = result.get();
5434   }
5435 
5436   Expr *NakedFn = Fn->IgnoreParens();
5437 
5438   bool CallingNDeclIndirectly = false;
5439   NamedDecl *NDecl = nullptr;
5440   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5441     if (UnOp->getOpcode() == UO_AddrOf) {
5442       CallingNDeclIndirectly = true;
5443       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5444     }
5445   }
5446 
5447   if (isa<DeclRefExpr>(NakedFn)) {
5448     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5449 
5450     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5451     if (FDecl && FDecl->getBuiltinID()) {
5452       // Rewrite the function decl for this builtin by replacing parameters
5453       // with no explicit address space with the address space of the arguments
5454       // in ArgExprs.
5455       if ((FDecl =
5456                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5457         NDecl = FDecl;
5458         Fn = DeclRefExpr::Create(
5459             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5460             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5461       }
5462     }
5463   } else if (isa<MemberExpr>(NakedFn))
5464     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5465 
5466   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5467     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5468                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5469       return ExprError();
5470 
5471     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5472       return ExprError();
5473 
5474     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5475   }
5476 
5477   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5478                                ExecConfig, IsExecConfig);
5479 }
5480 
5481 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5482 ///
5483 /// __builtin_astype( value, dst type )
5484 ///
5485 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5486                                  SourceLocation BuiltinLoc,
5487                                  SourceLocation RParenLoc) {
5488   ExprValueKind VK = VK_RValue;
5489   ExprObjectKind OK = OK_Ordinary;
5490   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5491   QualType SrcTy = E->getType();
5492   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5493     return ExprError(Diag(BuiltinLoc,
5494                           diag::err_invalid_astype_of_different_size)
5495                      << DstTy
5496                      << SrcTy
5497                      << E->getSourceRange());
5498   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5499 }
5500 
5501 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5502 /// provided arguments.
5503 ///
5504 /// __builtin_convertvector( value, dst type )
5505 ///
5506 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5507                                         SourceLocation BuiltinLoc,
5508                                         SourceLocation RParenLoc) {
5509   TypeSourceInfo *TInfo;
5510   GetTypeFromParser(ParsedDestTy, &TInfo);
5511   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5512 }
5513 
5514 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5515 /// i.e. an expression not of \p OverloadTy.  The expression should
5516 /// unary-convert to an expression of function-pointer or
5517 /// block-pointer type.
5518 ///
5519 /// \param NDecl the declaration being called, if available
5520 ExprResult
5521 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5522                             SourceLocation LParenLoc,
5523                             ArrayRef<Expr *> Args,
5524                             SourceLocation RParenLoc,
5525                             Expr *Config, bool IsExecConfig) {
5526   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5527   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5528 
5529   // Functions with 'interrupt' attribute cannot be called directly.
5530   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5531     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5532     return ExprError();
5533   }
5534 
5535   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5536   // so there's some risk when calling out to non-interrupt handler functions
5537   // that the callee might not preserve them. This is easy to diagnose here,
5538   // but can be very challenging to debug.
5539   if (auto *Caller = getCurFunctionDecl())
5540     if (Caller->hasAttr<ARMInterruptAttr>()) {
5541       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5542       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5543         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5544     }
5545 
5546   // Promote the function operand.
5547   // We special-case function promotion here because we only allow promoting
5548   // builtin functions to function pointers in the callee of a call.
5549   ExprResult Result;
5550   if (BuiltinID &&
5551       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5552     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5553                                CK_BuiltinFnToFnPtr).get();
5554   } else {
5555     Result = CallExprUnaryConversions(Fn);
5556   }
5557   if (Result.isInvalid())
5558     return ExprError();
5559   Fn = Result.get();
5560 
5561   // Make the call expr early, before semantic checks.  This guarantees cleanup
5562   // of arguments and function on error.
5563   CallExpr *TheCall;
5564   if (Config)
5565     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5566                                                cast<CallExpr>(Config), Args,
5567                                                Context.BoolTy, VK_RValue,
5568                                                RParenLoc);
5569   else
5570     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5571                                      VK_RValue, RParenLoc);
5572 
5573   if (!getLangOpts().CPlusPlus) {
5574     // C cannot always handle TypoExpr nodes in builtin calls and direct
5575     // function calls as their argument checking don't necessarily handle
5576     // dependent types properly, so make sure any TypoExprs have been
5577     // dealt with.
5578     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5579     if (!Result.isUsable()) return ExprError();
5580     TheCall = dyn_cast<CallExpr>(Result.get());
5581     if (!TheCall) return Result;
5582     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5583   }
5584 
5585   // Bail out early if calling a builtin with custom typechecking.
5586   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5587     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5588 
5589  retry:
5590   const FunctionType *FuncT;
5591   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5592     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5593     // have type pointer to function".
5594     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5595     if (!FuncT)
5596       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5597                          << Fn->getType() << Fn->getSourceRange());
5598   } else if (const BlockPointerType *BPT =
5599                Fn->getType()->getAs<BlockPointerType>()) {
5600     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5601   } else {
5602     // Handle calls to expressions of unknown-any type.
5603     if (Fn->getType() == Context.UnknownAnyTy) {
5604       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5605       if (rewrite.isInvalid()) return ExprError();
5606       Fn = rewrite.get();
5607       TheCall->setCallee(Fn);
5608       goto retry;
5609     }
5610 
5611     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5612       << Fn->getType() << Fn->getSourceRange());
5613   }
5614 
5615   if (getLangOpts().CUDA) {
5616     if (Config) {
5617       // CUDA: Kernel calls must be to global functions
5618       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5619         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5620             << FDecl << Fn->getSourceRange());
5621 
5622       // CUDA: Kernel function must have 'void' return type
5623       if (!FuncT->getReturnType()->isVoidType())
5624         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5625             << Fn->getType() << Fn->getSourceRange());
5626     } else {
5627       // CUDA: Calls to global functions must be configured
5628       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5629         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5630             << FDecl << Fn->getSourceRange());
5631     }
5632   }
5633 
5634   // Check for a valid return type
5635   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5636                           FDecl))
5637     return ExprError();
5638 
5639   // We know the result type of the call, set it.
5640   TheCall->setType(FuncT->getCallResultType(Context));
5641   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5642 
5643   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5644   if (Proto) {
5645     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5646                                 IsExecConfig))
5647       return ExprError();
5648   } else {
5649     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5650 
5651     if (FDecl) {
5652       // Check if we have too few/too many template arguments, based
5653       // on our knowledge of the function definition.
5654       const FunctionDecl *Def = nullptr;
5655       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5656         Proto = Def->getType()->getAs<FunctionProtoType>();
5657        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5658           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5659           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5660       }
5661 
5662       // If the function we're calling isn't a function prototype, but we have
5663       // a function prototype from a prior declaratiom, use that prototype.
5664       if (!FDecl->hasPrototype())
5665         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5666     }
5667 
5668     // Promote the arguments (C99 6.5.2.2p6).
5669     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5670       Expr *Arg = Args[i];
5671 
5672       if (Proto && i < Proto->getNumParams()) {
5673         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5674             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5675         ExprResult ArgE =
5676             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5677         if (ArgE.isInvalid())
5678           return true;
5679 
5680         Arg = ArgE.getAs<Expr>();
5681 
5682       } else {
5683         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5684 
5685         if (ArgE.isInvalid())
5686           return true;
5687 
5688         Arg = ArgE.getAs<Expr>();
5689       }
5690 
5691       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5692                               diag::err_call_incomplete_argument, Arg))
5693         return ExprError();
5694 
5695       TheCall->setArg(i, Arg);
5696     }
5697   }
5698 
5699   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5700     if (!Method->isStatic())
5701       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5702         << Fn->getSourceRange());
5703 
5704   // Check for sentinels
5705   if (NDecl)
5706     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5707 
5708   // Do special checking on direct calls to functions.
5709   if (FDecl) {
5710     if (CheckFunctionCall(FDecl, TheCall, Proto))
5711       return ExprError();
5712 
5713     if (BuiltinID)
5714       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5715   } else if (NDecl) {
5716     if (CheckPointerCall(NDecl, TheCall, Proto))
5717       return ExprError();
5718   } else {
5719     if (CheckOtherCall(TheCall, Proto))
5720       return ExprError();
5721   }
5722 
5723   return MaybeBindToTemporary(TheCall);
5724 }
5725 
5726 ExprResult
5727 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5728                            SourceLocation RParenLoc, Expr *InitExpr) {
5729   assert(Ty && "ActOnCompoundLiteral(): missing type");
5730   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5731 
5732   TypeSourceInfo *TInfo;
5733   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5734   if (!TInfo)
5735     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5736 
5737   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5738 }
5739 
5740 ExprResult
5741 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5742                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5743   QualType literalType = TInfo->getType();
5744 
5745   if (literalType->isArrayType()) {
5746     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5747           diag::err_illegal_decl_array_incomplete_type,
5748           SourceRange(LParenLoc,
5749                       LiteralExpr->getSourceRange().getEnd())))
5750       return ExprError();
5751     if (literalType->isVariableArrayType())
5752       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5753         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5754   } else if (!literalType->isDependentType() &&
5755              RequireCompleteType(LParenLoc, literalType,
5756                diag::err_typecheck_decl_incomplete_type,
5757                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5758     return ExprError();
5759 
5760   InitializedEntity Entity
5761     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5762   InitializationKind Kind
5763     = InitializationKind::CreateCStyleCast(LParenLoc,
5764                                            SourceRange(LParenLoc, RParenLoc),
5765                                            /*InitList=*/true);
5766   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5767   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5768                                       &literalType);
5769   if (Result.isInvalid())
5770     return ExprError();
5771   LiteralExpr = Result.get();
5772 
5773   bool isFileScope = !CurContext->isFunctionOrMethod();
5774 
5775   // In C, compound literals are l-values for some reason.
5776   // For GCC compatibility, in C++, file-scope array compound literals with
5777   // constant initializers are also l-values, and compound literals are
5778   // otherwise prvalues.
5779   //
5780   // (GCC also treats C++ list-initialized file-scope array prvalues with
5781   // constant initializers as l-values, but that's non-conforming, so we don't
5782   // follow it there.)
5783   //
5784   // FIXME: It would be better to handle the lvalue cases as materializing and
5785   // lifetime-extending a temporary object, but our materialized temporaries
5786   // representation only supports lifetime extension from a variable, not "out
5787   // of thin air".
5788   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5789   // is bound to the result of applying array-to-pointer decay to the compound
5790   // literal.
5791   // FIXME: GCC supports compound literals of reference type, which should
5792   // obviously have a value kind derived from the kind of reference involved.
5793   ExprValueKind VK =
5794       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5795           ? VK_RValue
5796           : VK_LValue;
5797 
5798   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5799                                               VK, LiteralExpr, isFileScope);
5800   if (isFileScope) {
5801     if (!LiteralExpr->isTypeDependent() &&
5802         !LiteralExpr->isValueDependent() &&
5803         !literalType->isDependentType()) // C99 6.5.2.5p3
5804       if (CheckForConstantInitializer(LiteralExpr, literalType))
5805         return ExprError();
5806     E = new (Context) ConstantExpr(E);
5807   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
5808              literalType.getAddressSpace() != LangAS::Default) {
5809     // Embedded-C extensions to C99 6.5.2.5:
5810     //   "If the compound literal occurs inside the body of a function, the
5811     //   type name shall not be qualified by an address-space qualifier."
5812     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
5813       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
5814     return ExprError();
5815   }
5816 
5817   return MaybeBindToTemporary(E);
5818 }
5819 
5820 ExprResult
5821 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5822                     SourceLocation RBraceLoc) {
5823   // Immediately handle non-overload placeholders.  Overloads can be
5824   // resolved contextually, but everything else here can't.
5825   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5826     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5827       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5828 
5829       // Ignore failures; dropping the entire initializer list because
5830       // of one failure would be terrible for indexing/etc.
5831       if (result.isInvalid()) continue;
5832 
5833       InitArgList[I] = result.get();
5834     }
5835   }
5836 
5837   // Semantic analysis for initializers is done by ActOnDeclarator() and
5838   // CheckInitializer() - it requires knowledge of the object being initialized.
5839 
5840   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5841                                                RBraceLoc);
5842   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5843   return E;
5844 }
5845 
5846 /// Do an explicit extend of the given block pointer if we're in ARC.
5847 void Sema::maybeExtendBlockObject(ExprResult &E) {
5848   assert(E.get()->getType()->isBlockPointerType());
5849   assert(E.get()->isRValue());
5850 
5851   // Only do this in an r-value context.
5852   if (!getLangOpts().ObjCAutoRefCount) return;
5853 
5854   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5855                                CK_ARCExtendBlockObject, E.get(),
5856                                /*base path*/ nullptr, VK_RValue);
5857   Cleanup.setExprNeedsCleanups(true);
5858 }
5859 
5860 /// Prepare a conversion of the given expression to an ObjC object
5861 /// pointer type.
5862 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5863   QualType type = E.get()->getType();
5864   if (type->isObjCObjectPointerType()) {
5865     return CK_BitCast;
5866   } else if (type->isBlockPointerType()) {
5867     maybeExtendBlockObject(E);
5868     return CK_BlockPointerToObjCPointerCast;
5869   } else {
5870     assert(type->isPointerType());
5871     return CK_CPointerToObjCPointerCast;
5872   }
5873 }
5874 
5875 /// Prepares for a scalar cast, performing all the necessary stages
5876 /// except the final cast and returning the kind required.
5877 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5878   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5879   // Also, callers should have filtered out the invalid cases with
5880   // pointers.  Everything else should be possible.
5881 
5882   QualType SrcTy = Src.get()->getType();
5883   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5884     return CK_NoOp;
5885 
5886   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5887   case Type::STK_MemberPointer:
5888     llvm_unreachable("member pointer type in C");
5889 
5890   case Type::STK_CPointer:
5891   case Type::STK_BlockPointer:
5892   case Type::STK_ObjCObjectPointer:
5893     switch (DestTy->getScalarTypeKind()) {
5894     case Type::STK_CPointer: {
5895       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5896       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5897       if (SrcAS != DestAS)
5898         return CK_AddressSpaceConversion;
5899       if (Context.hasCvrSimilarType(SrcTy, DestTy))
5900         return CK_NoOp;
5901       return CK_BitCast;
5902     }
5903     case Type::STK_BlockPointer:
5904       return (SrcKind == Type::STK_BlockPointer
5905                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5906     case Type::STK_ObjCObjectPointer:
5907       if (SrcKind == Type::STK_ObjCObjectPointer)
5908         return CK_BitCast;
5909       if (SrcKind == Type::STK_CPointer)
5910         return CK_CPointerToObjCPointerCast;
5911       maybeExtendBlockObject(Src);
5912       return CK_BlockPointerToObjCPointerCast;
5913     case Type::STK_Bool:
5914       return CK_PointerToBoolean;
5915     case Type::STK_Integral:
5916       return CK_PointerToIntegral;
5917     case Type::STK_Floating:
5918     case Type::STK_FloatingComplex:
5919     case Type::STK_IntegralComplex:
5920     case Type::STK_MemberPointer:
5921     case Type::STK_FixedPoint:
5922       llvm_unreachable("illegal cast from pointer");
5923     }
5924     llvm_unreachable("Should have returned before this");
5925 
5926   case Type::STK_FixedPoint:
5927     switch (DestTy->getScalarTypeKind()) {
5928     case Type::STK_FixedPoint:
5929       return CK_FixedPointCast;
5930     case Type::STK_Bool:
5931       return CK_FixedPointToBoolean;
5932     case Type::STK_Integral:
5933     case Type::STK_Floating:
5934     case Type::STK_IntegralComplex:
5935     case Type::STK_FloatingComplex:
5936       Diag(Src.get()->getExprLoc(),
5937            diag::err_unimplemented_conversion_with_fixed_point_type)
5938           << DestTy;
5939       return CK_IntegralCast;
5940     case Type::STK_CPointer:
5941     case Type::STK_ObjCObjectPointer:
5942     case Type::STK_BlockPointer:
5943     case Type::STK_MemberPointer:
5944       llvm_unreachable("illegal cast to pointer type");
5945     }
5946     llvm_unreachable("Should have returned before this");
5947 
5948   case Type::STK_Bool: // casting from bool is like casting from an integer
5949   case Type::STK_Integral:
5950     switch (DestTy->getScalarTypeKind()) {
5951     case Type::STK_CPointer:
5952     case Type::STK_ObjCObjectPointer:
5953     case Type::STK_BlockPointer:
5954       if (Src.get()->isNullPointerConstant(Context,
5955                                            Expr::NPC_ValueDependentIsNull))
5956         return CK_NullToPointer;
5957       return CK_IntegralToPointer;
5958     case Type::STK_Bool:
5959       return CK_IntegralToBoolean;
5960     case Type::STK_Integral:
5961       return CK_IntegralCast;
5962     case Type::STK_Floating:
5963       return CK_IntegralToFloating;
5964     case Type::STK_IntegralComplex:
5965       Src = ImpCastExprToType(Src.get(),
5966                       DestTy->castAs<ComplexType>()->getElementType(),
5967                       CK_IntegralCast);
5968       return CK_IntegralRealToComplex;
5969     case Type::STK_FloatingComplex:
5970       Src = ImpCastExprToType(Src.get(),
5971                       DestTy->castAs<ComplexType>()->getElementType(),
5972                       CK_IntegralToFloating);
5973       return CK_FloatingRealToComplex;
5974     case Type::STK_MemberPointer:
5975       llvm_unreachable("member pointer type in C");
5976     case Type::STK_FixedPoint:
5977       Diag(Src.get()->getExprLoc(),
5978            diag::err_unimplemented_conversion_with_fixed_point_type)
5979           << SrcTy;
5980       return CK_IntegralCast;
5981     }
5982     llvm_unreachable("Should have returned before this");
5983 
5984   case Type::STK_Floating:
5985     switch (DestTy->getScalarTypeKind()) {
5986     case Type::STK_Floating:
5987       return CK_FloatingCast;
5988     case Type::STK_Bool:
5989       return CK_FloatingToBoolean;
5990     case Type::STK_Integral:
5991       return CK_FloatingToIntegral;
5992     case Type::STK_FloatingComplex:
5993       Src = ImpCastExprToType(Src.get(),
5994                               DestTy->castAs<ComplexType>()->getElementType(),
5995                               CK_FloatingCast);
5996       return CK_FloatingRealToComplex;
5997     case Type::STK_IntegralComplex:
5998       Src = ImpCastExprToType(Src.get(),
5999                               DestTy->castAs<ComplexType>()->getElementType(),
6000                               CK_FloatingToIntegral);
6001       return CK_IntegralRealToComplex;
6002     case Type::STK_CPointer:
6003     case Type::STK_ObjCObjectPointer:
6004     case Type::STK_BlockPointer:
6005       llvm_unreachable("valid float->pointer cast?");
6006     case Type::STK_MemberPointer:
6007       llvm_unreachable("member pointer type in C");
6008     case Type::STK_FixedPoint:
6009       Diag(Src.get()->getExprLoc(),
6010            diag::err_unimplemented_conversion_with_fixed_point_type)
6011           << SrcTy;
6012       return CK_IntegralCast;
6013     }
6014     llvm_unreachable("Should have returned before this");
6015 
6016   case Type::STK_FloatingComplex:
6017     switch (DestTy->getScalarTypeKind()) {
6018     case Type::STK_FloatingComplex:
6019       return CK_FloatingComplexCast;
6020     case Type::STK_IntegralComplex:
6021       return CK_FloatingComplexToIntegralComplex;
6022     case Type::STK_Floating: {
6023       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6024       if (Context.hasSameType(ET, DestTy))
6025         return CK_FloatingComplexToReal;
6026       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6027       return CK_FloatingCast;
6028     }
6029     case Type::STK_Bool:
6030       return CK_FloatingComplexToBoolean;
6031     case Type::STK_Integral:
6032       Src = ImpCastExprToType(Src.get(),
6033                               SrcTy->castAs<ComplexType>()->getElementType(),
6034                               CK_FloatingComplexToReal);
6035       return CK_FloatingToIntegral;
6036     case Type::STK_CPointer:
6037     case Type::STK_ObjCObjectPointer:
6038     case Type::STK_BlockPointer:
6039       llvm_unreachable("valid complex float->pointer cast?");
6040     case Type::STK_MemberPointer:
6041       llvm_unreachable("member pointer type in C");
6042     case Type::STK_FixedPoint:
6043       Diag(Src.get()->getExprLoc(),
6044            diag::err_unimplemented_conversion_with_fixed_point_type)
6045           << SrcTy;
6046       return CK_IntegralCast;
6047     }
6048     llvm_unreachable("Should have returned before this");
6049 
6050   case Type::STK_IntegralComplex:
6051     switch (DestTy->getScalarTypeKind()) {
6052     case Type::STK_FloatingComplex:
6053       return CK_IntegralComplexToFloatingComplex;
6054     case Type::STK_IntegralComplex:
6055       return CK_IntegralComplexCast;
6056     case Type::STK_Integral: {
6057       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6058       if (Context.hasSameType(ET, DestTy))
6059         return CK_IntegralComplexToReal;
6060       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6061       return CK_IntegralCast;
6062     }
6063     case Type::STK_Bool:
6064       return CK_IntegralComplexToBoolean;
6065     case Type::STK_Floating:
6066       Src = ImpCastExprToType(Src.get(),
6067                               SrcTy->castAs<ComplexType>()->getElementType(),
6068                               CK_IntegralComplexToReal);
6069       return CK_IntegralToFloating;
6070     case Type::STK_CPointer:
6071     case Type::STK_ObjCObjectPointer:
6072     case Type::STK_BlockPointer:
6073       llvm_unreachable("valid complex int->pointer cast?");
6074     case Type::STK_MemberPointer:
6075       llvm_unreachable("member pointer type in C");
6076     case Type::STK_FixedPoint:
6077       Diag(Src.get()->getExprLoc(),
6078            diag::err_unimplemented_conversion_with_fixed_point_type)
6079           << SrcTy;
6080       return CK_IntegralCast;
6081     }
6082     llvm_unreachable("Should have returned before this");
6083   }
6084 
6085   llvm_unreachable("Unhandled scalar cast");
6086 }
6087 
6088 static bool breakDownVectorType(QualType type, uint64_t &len,
6089                                 QualType &eltType) {
6090   // Vectors are simple.
6091   if (const VectorType *vecType = type->getAs<VectorType>()) {
6092     len = vecType->getNumElements();
6093     eltType = vecType->getElementType();
6094     assert(eltType->isScalarType());
6095     return true;
6096   }
6097 
6098   // We allow lax conversion to and from non-vector types, but only if
6099   // they're real types (i.e. non-complex, non-pointer scalar types).
6100   if (!type->isRealType()) return false;
6101 
6102   len = 1;
6103   eltType = type;
6104   return true;
6105 }
6106 
6107 /// Are the two types lax-compatible vector types?  That is, given
6108 /// that one of them is a vector, do they have equal storage sizes,
6109 /// where the storage size is the number of elements times the element
6110 /// size?
6111 ///
6112 /// This will also return false if either of the types is neither a
6113 /// vector nor a real type.
6114 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6115   assert(destTy->isVectorType() || srcTy->isVectorType());
6116 
6117   // Disallow lax conversions between scalars and ExtVectors (these
6118   // conversions are allowed for other vector types because common headers
6119   // depend on them).  Most scalar OP ExtVector cases are handled by the
6120   // splat path anyway, which does what we want (convert, not bitcast).
6121   // What this rules out for ExtVectors is crazy things like char4*float.
6122   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6123   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6124 
6125   uint64_t srcLen, destLen;
6126   QualType srcEltTy, destEltTy;
6127   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6128   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6129 
6130   // ASTContext::getTypeSize will return the size rounded up to a
6131   // power of 2, so instead of using that, we need to use the raw
6132   // element size multiplied by the element count.
6133   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6134   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6135 
6136   return (srcLen * srcEltSize == destLen * destEltSize);
6137 }
6138 
6139 /// Is this a legal conversion between two types, one of which is
6140 /// known to be a vector type?
6141 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6142   assert(destTy->isVectorType() || srcTy->isVectorType());
6143 
6144   if (!Context.getLangOpts().LaxVectorConversions)
6145     return false;
6146   return areLaxCompatibleVectorTypes(srcTy, destTy);
6147 }
6148 
6149 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6150                            CastKind &Kind) {
6151   assert(VectorTy->isVectorType() && "Not a vector type!");
6152 
6153   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6154     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6155       return Diag(R.getBegin(),
6156                   Ty->isVectorType() ?
6157                   diag::err_invalid_conversion_between_vectors :
6158                   diag::err_invalid_conversion_between_vector_and_integer)
6159         << VectorTy << Ty << R;
6160   } else
6161     return Diag(R.getBegin(),
6162                 diag::err_invalid_conversion_between_vector_and_scalar)
6163       << VectorTy << Ty << R;
6164 
6165   Kind = CK_BitCast;
6166   return false;
6167 }
6168 
6169 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6170   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6171 
6172   if (DestElemTy == SplattedExpr->getType())
6173     return SplattedExpr;
6174 
6175   assert(DestElemTy->isFloatingType() ||
6176          DestElemTy->isIntegralOrEnumerationType());
6177 
6178   CastKind CK;
6179   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6180     // OpenCL requires that we convert `true` boolean expressions to -1, but
6181     // only when splatting vectors.
6182     if (DestElemTy->isFloatingType()) {
6183       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6184       // in two steps: boolean to signed integral, then to floating.
6185       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6186                                                  CK_BooleanToSignedIntegral);
6187       SplattedExpr = CastExprRes.get();
6188       CK = CK_IntegralToFloating;
6189     } else {
6190       CK = CK_BooleanToSignedIntegral;
6191     }
6192   } else {
6193     ExprResult CastExprRes = SplattedExpr;
6194     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6195     if (CastExprRes.isInvalid())
6196       return ExprError();
6197     SplattedExpr = CastExprRes.get();
6198   }
6199   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6200 }
6201 
6202 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6203                                     Expr *CastExpr, CastKind &Kind) {
6204   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6205 
6206   QualType SrcTy = CastExpr->getType();
6207 
6208   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6209   // an ExtVectorType.
6210   // In OpenCL, casts between vectors of different types are not allowed.
6211   // (See OpenCL 6.2).
6212   if (SrcTy->isVectorType()) {
6213     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6214         (getLangOpts().OpenCL &&
6215          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6216       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6217         << DestTy << SrcTy << R;
6218       return ExprError();
6219     }
6220     Kind = CK_BitCast;
6221     return CastExpr;
6222   }
6223 
6224   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6225   // conversion will take place first from scalar to elt type, and then
6226   // splat from elt type to vector.
6227   if (SrcTy->isPointerType())
6228     return Diag(R.getBegin(),
6229                 diag::err_invalid_conversion_between_vector_and_scalar)
6230       << DestTy << SrcTy << R;
6231 
6232   Kind = CK_VectorSplat;
6233   return prepareVectorSplat(DestTy, CastExpr);
6234 }
6235 
6236 ExprResult
6237 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6238                     Declarator &D, ParsedType &Ty,
6239                     SourceLocation RParenLoc, Expr *CastExpr) {
6240   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6241          "ActOnCastExpr(): missing type or expr");
6242 
6243   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6244   if (D.isInvalidType())
6245     return ExprError();
6246 
6247   if (getLangOpts().CPlusPlus) {
6248     // Check that there are no default arguments (C++ only).
6249     CheckExtraCXXDefaultArguments(D);
6250   } else {
6251     // Make sure any TypoExprs have been dealt with.
6252     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6253     if (!Res.isUsable())
6254       return ExprError();
6255     CastExpr = Res.get();
6256   }
6257 
6258   checkUnusedDeclAttributes(D);
6259 
6260   QualType castType = castTInfo->getType();
6261   Ty = CreateParsedType(castType, castTInfo);
6262 
6263   bool isVectorLiteral = false;
6264 
6265   // Check for an altivec or OpenCL literal,
6266   // i.e. all the elements are integer constants.
6267   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6268   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6269   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6270        && castType->isVectorType() && (PE || PLE)) {
6271     if (PLE && PLE->getNumExprs() == 0) {
6272       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6273       return ExprError();
6274     }
6275     if (PE || PLE->getNumExprs() == 1) {
6276       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6277       if (!E->getType()->isVectorType())
6278         isVectorLiteral = true;
6279     }
6280     else
6281       isVectorLiteral = true;
6282   }
6283 
6284   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6285   // then handle it as such.
6286   if (isVectorLiteral)
6287     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6288 
6289   // If the Expr being casted is a ParenListExpr, handle it specially.
6290   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6291   // sequence of BinOp comma operators.
6292   if (isa<ParenListExpr>(CastExpr)) {
6293     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6294     if (Result.isInvalid()) return ExprError();
6295     CastExpr = Result.get();
6296   }
6297 
6298   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6299       !getSourceManager().isInSystemMacro(LParenLoc))
6300     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6301 
6302   CheckTollFreeBridgeCast(castType, CastExpr);
6303 
6304   CheckObjCBridgeRelatedCast(castType, CastExpr);
6305 
6306   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6307 
6308   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6309 }
6310 
6311 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6312                                     SourceLocation RParenLoc, Expr *E,
6313                                     TypeSourceInfo *TInfo) {
6314   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6315          "Expected paren or paren list expression");
6316 
6317   Expr **exprs;
6318   unsigned numExprs;
6319   Expr *subExpr;
6320   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6321   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6322     LiteralLParenLoc = PE->getLParenLoc();
6323     LiteralRParenLoc = PE->getRParenLoc();
6324     exprs = PE->getExprs();
6325     numExprs = PE->getNumExprs();
6326   } else { // isa<ParenExpr> by assertion at function entrance
6327     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6328     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6329     subExpr = cast<ParenExpr>(E)->getSubExpr();
6330     exprs = &subExpr;
6331     numExprs = 1;
6332   }
6333 
6334   QualType Ty = TInfo->getType();
6335   assert(Ty->isVectorType() && "Expected vector type");
6336 
6337   SmallVector<Expr *, 8> initExprs;
6338   const VectorType *VTy = Ty->getAs<VectorType>();
6339   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6340 
6341   // '(...)' form of vector initialization in AltiVec: the number of
6342   // initializers must be one or must match the size of the vector.
6343   // If a single value is specified in the initializer then it will be
6344   // replicated to all the components of the vector
6345   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6346     // The number of initializers must be one or must match the size of the
6347     // vector. If a single value is specified in the initializer then it will
6348     // be replicated to all the components of the vector
6349     if (numExprs == 1) {
6350       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6351       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6352       if (Literal.isInvalid())
6353         return ExprError();
6354       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6355                                   PrepareScalarCast(Literal, ElemTy));
6356       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6357     }
6358     else if (numExprs < numElems) {
6359       Diag(E->getExprLoc(),
6360            diag::err_incorrect_number_of_vector_initializers);
6361       return ExprError();
6362     }
6363     else
6364       initExprs.append(exprs, exprs + numExprs);
6365   }
6366   else {
6367     // For OpenCL, when the number of initializers is a single value,
6368     // it will be replicated to all components of the vector.
6369     if (getLangOpts().OpenCL &&
6370         VTy->getVectorKind() == VectorType::GenericVector &&
6371         numExprs == 1) {
6372         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6373         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6374         if (Literal.isInvalid())
6375           return ExprError();
6376         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6377                                     PrepareScalarCast(Literal, ElemTy));
6378         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6379     }
6380 
6381     initExprs.append(exprs, exprs + numExprs);
6382   }
6383   // FIXME: This means that pretty-printing the final AST will produce curly
6384   // braces instead of the original commas.
6385   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6386                                                    initExprs, LiteralRParenLoc);
6387   initE->setType(Ty);
6388   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6389 }
6390 
6391 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6392 /// the ParenListExpr into a sequence of comma binary operators.
6393 ExprResult
6394 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6395   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6396   if (!E)
6397     return OrigExpr;
6398 
6399   ExprResult Result(E->getExpr(0));
6400 
6401   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6402     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6403                         E->getExpr(i));
6404 
6405   if (Result.isInvalid()) return ExprError();
6406 
6407   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6408 }
6409 
6410 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6411                                     SourceLocation R,
6412                                     MultiExprArg Val) {
6413   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6414   return expr;
6415 }
6416 
6417 /// Emit a specialized diagnostic when one expression is a null pointer
6418 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6419 /// emitted.
6420 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6421                                       SourceLocation QuestionLoc) {
6422   Expr *NullExpr = LHSExpr;
6423   Expr *NonPointerExpr = RHSExpr;
6424   Expr::NullPointerConstantKind NullKind =
6425       NullExpr->isNullPointerConstant(Context,
6426                                       Expr::NPC_ValueDependentIsNotNull);
6427 
6428   if (NullKind == Expr::NPCK_NotNull) {
6429     NullExpr = RHSExpr;
6430     NonPointerExpr = LHSExpr;
6431     NullKind =
6432         NullExpr->isNullPointerConstant(Context,
6433                                         Expr::NPC_ValueDependentIsNotNull);
6434   }
6435 
6436   if (NullKind == Expr::NPCK_NotNull)
6437     return false;
6438 
6439   if (NullKind == Expr::NPCK_ZeroExpression)
6440     return false;
6441 
6442   if (NullKind == Expr::NPCK_ZeroLiteral) {
6443     // In this case, check to make sure that we got here from a "NULL"
6444     // string in the source code.
6445     NullExpr = NullExpr->IgnoreParenImpCasts();
6446     SourceLocation loc = NullExpr->getExprLoc();
6447     if (!findMacroSpelling(loc, "NULL"))
6448       return false;
6449   }
6450 
6451   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6452   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6453       << NonPointerExpr->getType() << DiagType
6454       << NonPointerExpr->getSourceRange();
6455   return true;
6456 }
6457 
6458 /// Return false if the condition expression is valid, true otherwise.
6459 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6460   QualType CondTy = Cond->getType();
6461 
6462   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6463   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6464     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6465       << CondTy << Cond->getSourceRange();
6466     return true;
6467   }
6468 
6469   // C99 6.5.15p2
6470   if (CondTy->isScalarType()) return false;
6471 
6472   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6473     << CondTy << Cond->getSourceRange();
6474   return true;
6475 }
6476 
6477 /// Handle when one or both operands are void type.
6478 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6479                                          ExprResult &RHS) {
6480     Expr *LHSExpr = LHS.get();
6481     Expr *RHSExpr = RHS.get();
6482 
6483     if (!LHSExpr->getType()->isVoidType())
6484       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6485           << RHSExpr->getSourceRange();
6486     if (!RHSExpr->getType()->isVoidType())
6487       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6488           << LHSExpr->getSourceRange();
6489     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6490     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6491     return S.Context.VoidTy;
6492 }
6493 
6494 /// Return false if the NullExpr can be promoted to PointerTy,
6495 /// true otherwise.
6496 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6497                                         QualType PointerTy) {
6498   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6499       !NullExpr.get()->isNullPointerConstant(S.Context,
6500                                             Expr::NPC_ValueDependentIsNull))
6501     return true;
6502 
6503   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6504   return false;
6505 }
6506 
6507 /// Checks compatibility between two pointers and return the resulting
6508 /// type.
6509 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6510                                                      ExprResult &RHS,
6511                                                      SourceLocation Loc) {
6512   QualType LHSTy = LHS.get()->getType();
6513   QualType RHSTy = RHS.get()->getType();
6514 
6515   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6516     // Two identical pointers types are always compatible.
6517     return LHSTy;
6518   }
6519 
6520   QualType lhptee, rhptee;
6521 
6522   // Get the pointee types.
6523   bool IsBlockPointer = false;
6524   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6525     lhptee = LHSBTy->getPointeeType();
6526     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6527     IsBlockPointer = true;
6528   } else {
6529     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6530     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6531   }
6532 
6533   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6534   // differently qualified versions of compatible types, the result type is
6535   // a pointer to an appropriately qualified version of the composite
6536   // type.
6537 
6538   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6539   // clause doesn't make sense for our extensions. E.g. address space 2 should
6540   // be incompatible with address space 3: they may live on different devices or
6541   // anything.
6542   Qualifiers lhQual = lhptee.getQualifiers();
6543   Qualifiers rhQual = rhptee.getQualifiers();
6544 
6545   LangAS ResultAddrSpace = LangAS::Default;
6546   LangAS LAddrSpace = lhQual.getAddressSpace();
6547   LangAS RAddrSpace = rhQual.getAddressSpace();
6548 
6549   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6550   // spaces is disallowed.
6551   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6552     ResultAddrSpace = LAddrSpace;
6553   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6554     ResultAddrSpace = RAddrSpace;
6555   else {
6556     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6557         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6558         << RHS.get()->getSourceRange();
6559     return QualType();
6560   }
6561 
6562   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6563   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6564   lhQual.removeCVRQualifiers();
6565   rhQual.removeCVRQualifiers();
6566 
6567   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6568   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6569   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6570   // qual types are compatible iff
6571   //  * corresponded types are compatible
6572   //  * CVR qualifiers are equal
6573   //  * address spaces are equal
6574   // Thus for conditional operator we merge CVR and address space unqualified
6575   // pointees and if there is a composite type we return a pointer to it with
6576   // merged qualifiers.
6577   LHSCastKind =
6578       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6579   RHSCastKind =
6580       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6581   lhQual.removeAddressSpace();
6582   rhQual.removeAddressSpace();
6583 
6584   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6585   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6586 
6587   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6588 
6589   if (CompositeTy.isNull()) {
6590     // In this situation, we assume void* type. No especially good
6591     // reason, but this is what gcc does, and we do have to pick
6592     // to get a consistent AST.
6593     QualType incompatTy;
6594     incompatTy = S.Context.getPointerType(
6595         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6596     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6597     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6598 
6599     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6600     // for casts between types with incompatible address space qualifiers.
6601     // For the following code the compiler produces casts between global and
6602     // local address spaces of the corresponded innermost pointees:
6603     // local int *global *a;
6604     // global int *global *b;
6605     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6606     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6607         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6608         << RHS.get()->getSourceRange();
6609 
6610     return incompatTy;
6611   }
6612 
6613   // The pointer types are compatible.
6614   // In case of OpenCL ResultTy should have the address space qualifier
6615   // which is a superset of address spaces of both the 2nd and the 3rd
6616   // operands of the conditional operator.
6617   QualType ResultTy = [&, ResultAddrSpace]() {
6618     if (S.getLangOpts().OpenCL) {
6619       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6620       CompositeQuals.setAddressSpace(ResultAddrSpace);
6621       return S.Context
6622           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6623           .withCVRQualifiers(MergedCVRQual);
6624     }
6625     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6626   }();
6627   if (IsBlockPointer)
6628     ResultTy = S.Context.getBlockPointerType(ResultTy);
6629   else
6630     ResultTy = S.Context.getPointerType(ResultTy);
6631 
6632   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6633   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6634   return ResultTy;
6635 }
6636 
6637 /// Return the resulting type when the operands are both block pointers.
6638 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6639                                                           ExprResult &LHS,
6640                                                           ExprResult &RHS,
6641                                                           SourceLocation Loc) {
6642   QualType LHSTy = LHS.get()->getType();
6643   QualType RHSTy = RHS.get()->getType();
6644 
6645   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6646     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6647       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6648       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6649       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6650       return destType;
6651     }
6652     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6653       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6654       << RHS.get()->getSourceRange();
6655     return QualType();
6656   }
6657 
6658   // We have 2 block pointer types.
6659   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6660 }
6661 
6662 /// Return the resulting type when the operands are both pointers.
6663 static QualType
6664 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6665                                             ExprResult &RHS,
6666                                             SourceLocation Loc) {
6667   // get the pointer types
6668   QualType LHSTy = LHS.get()->getType();
6669   QualType RHSTy = RHS.get()->getType();
6670 
6671   // get the "pointed to" types
6672   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6673   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6674 
6675   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6676   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6677     // Figure out necessary qualifiers (C99 6.5.15p6)
6678     QualType destPointee
6679       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6680     QualType destType = S.Context.getPointerType(destPointee);
6681     // Add qualifiers if necessary.
6682     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6683     // Promote to void*.
6684     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6685     return destType;
6686   }
6687   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6688     QualType destPointee
6689       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6690     QualType destType = S.Context.getPointerType(destPointee);
6691     // Add qualifiers if necessary.
6692     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6693     // Promote to void*.
6694     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6695     return destType;
6696   }
6697 
6698   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6699 }
6700 
6701 /// Return false if the first expression is not an integer and the second
6702 /// expression is not a pointer, true otherwise.
6703 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6704                                         Expr* PointerExpr, SourceLocation Loc,
6705                                         bool IsIntFirstExpr) {
6706   if (!PointerExpr->getType()->isPointerType() ||
6707       !Int.get()->getType()->isIntegerType())
6708     return false;
6709 
6710   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6711   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6712 
6713   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6714     << Expr1->getType() << Expr2->getType()
6715     << Expr1->getSourceRange() << Expr2->getSourceRange();
6716   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6717                             CK_IntegralToPointer);
6718   return true;
6719 }
6720 
6721 /// Simple conversion between integer and floating point types.
6722 ///
6723 /// Used when handling the OpenCL conditional operator where the
6724 /// condition is a vector while the other operands are scalar.
6725 ///
6726 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6727 /// types are either integer or floating type. Between the two
6728 /// operands, the type with the higher rank is defined as the "result
6729 /// type". The other operand needs to be promoted to the same type. No
6730 /// other type promotion is allowed. We cannot use
6731 /// UsualArithmeticConversions() for this purpose, since it always
6732 /// promotes promotable types.
6733 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6734                                             ExprResult &RHS,
6735                                             SourceLocation QuestionLoc) {
6736   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6737   if (LHS.isInvalid())
6738     return QualType();
6739   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6740   if (RHS.isInvalid())
6741     return QualType();
6742 
6743   // For conversion purposes, we ignore any qualifiers.
6744   // For example, "const float" and "float" are equivalent.
6745   QualType LHSType =
6746     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6747   QualType RHSType =
6748     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6749 
6750   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6751     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6752       << LHSType << LHS.get()->getSourceRange();
6753     return QualType();
6754   }
6755 
6756   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6757     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6758       << RHSType << RHS.get()->getSourceRange();
6759     return QualType();
6760   }
6761 
6762   // If both types are identical, no conversion is needed.
6763   if (LHSType == RHSType)
6764     return LHSType;
6765 
6766   // Now handle "real" floating types (i.e. float, double, long double).
6767   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6768     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6769                                  /*IsCompAssign = */ false);
6770 
6771   // Finally, we have two differing integer types.
6772   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6773   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6774 }
6775 
6776 /// Convert scalar operands to a vector that matches the
6777 ///        condition in length.
6778 ///
6779 /// Used when handling the OpenCL conditional operator where the
6780 /// condition is a vector while the other operands are scalar.
6781 ///
6782 /// We first compute the "result type" for the scalar operands
6783 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6784 /// into a vector of that type where the length matches the condition
6785 /// vector type. s6.11.6 requires that the element types of the result
6786 /// and the condition must have the same number of bits.
6787 static QualType
6788 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6789                               QualType CondTy, SourceLocation QuestionLoc) {
6790   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6791   if (ResTy.isNull()) return QualType();
6792 
6793   const VectorType *CV = CondTy->getAs<VectorType>();
6794   assert(CV);
6795 
6796   // Determine the vector result type
6797   unsigned NumElements = CV->getNumElements();
6798   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6799 
6800   // Ensure that all types have the same number of bits
6801   if (S.Context.getTypeSize(CV->getElementType())
6802       != S.Context.getTypeSize(ResTy)) {
6803     // Since VectorTy is created internally, it does not pretty print
6804     // with an OpenCL name. Instead, we just print a description.
6805     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6806     SmallString<64> Str;
6807     llvm::raw_svector_ostream OS(Str);
6808     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6809     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6810       << CondTy << OS.str();
6811     return QualType();
6812   }
6813 
6814   // Convert operands to the vector result type
6815   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6816   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6817 
6818   return VectorTy;
6819 }
6820 
6821 /// Return false if this is a valid OpenCL condition vector
6822 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6823                                        SourceLocation QuestionLoc) {
6824   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6825   // integral type.
6826   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6827   assert(CondTy);
6828   QualType EleTy = CondTy->getElementType();
6829   if (EleTy->isIntegerType()) return false;
6830 
6831   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6832     << Cond->getType() << Cond->getSourceRange();
6833   return true;
6834 }
6835 
6836 /// Return false if the vector condition type and the vector
6837 ///        result type are compatible.
6838 ///
6839 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6840 /// number of elements, and their element types have the same number
6841 /// of bits.
6842 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6843                               SourceLocation QuestionLoc) {
6844   const VectorType *CV = CondTy->getAs<VectorType>();
6845   const VectorType *RV = VecResTy->getAs<VectorType>();
6846   assert(CV && RV);
6847 
6848   if (CV->getNumElements() != RV->getNumElements()) {
6849     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6850       << CondTy << VecResTy;
6851     return true;
6852   }
6853 
6854   QualType CVE = CV->getElementType();
6855   QualType RVE = RV->getElementType();
6856 
6857   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6858     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6859       << CondTy << VecResTy;
6860     return true;
6861   }
6862 
6863   return false;
6864 }
6865 
6866 /// Return the resulting type for the conditional operator in
6867 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6868 ///        s6.3.i) when the condition is a vector type.
6869 static QualType
6870 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6871                              ExprResult &LHS, ExprResult &RHS,
6872                              SourceLocation QuestionLoc) {
6873   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6874   if (Cond.isInvalid())
6875     return QualType();
6876   QualType CondTy = Cond.get()->getType();
6877 
6878   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6879     return QualType();
6880 
6881   // If either operand is a vector then find the vector type of the
6882   // result as specified in OpenCL v1.1 s6.3.i.
6883   if (LHS.get()->getType()->isVectorType() ||
6884       RHS.get()->getType()->isVectorType()) {
6885     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6886                                               /*isCompAssign*/false,
6887                                               /*AllowBothBool*/true,
6888                                               /*AllowBoolConversions*/false);
6889     if (VecResTy.isNull()) return QualType();
6890     // The result type must match the condition type as specified in
6891     // OpenCL v1.1 s6.11.6.
6892     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6893       return QualType();
6894     return VecResTy;
6895   }
6896 
6897   // Both operands are scalar.
6898   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6899 }
6900 
6901 /// Return true if the Expr is block type
6902 static bool checkBlockType(Sema &S, const Expr *E) {
6903   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6904     QualType Ty = CE->getCallee()->getType();
6905     if (Ty->isBlockPointerType()) {
6906       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6907       return true;
6908     }
6909   }
6910   return false;
6911 }
6912 
6913 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6914 /// In that case, LHS = cond.
6915 /// C99 6.5.15
6916 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6917                                         ExprResult &RHS, ExprValueKind &VK,
6918                                         ExprObjectKind &OK,
6919                                         SourceLocation QuestionLoc) {
6920 
6921   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6922   if (!LHSResult.isUsable()) return QualType();
6923   LHS = LHSResult;
6924 
6925   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6926   if (!RHSResult.isUsable()) return QualType();
6927   RHS = RHSResult;
6928 
6929   // C++ is sufficiently different to merit its own checker.
6930   if (getLangOpts().CPlusPlus)
6931     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6932 
6933   VK = VK_RValue;
6934   OK = OK_Ordinary;
6935 
6936   // The OpenCL operator with a vector condition is sufficiently
6937   // different to merit its own checker.
6938   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6939     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6940 
6941   // First, check the condition.
6942   Cond = UsualUnaryConversions(Cond.get());
6943   if (Cond.isInvalid())
6944     return QualType();
6945   if (checkCondition(*this, Cond.get(), QuestionLoc))
6946     return QualType();
6947 
6948   // Now check the two expressions.
6949   if (LHS.get()->getType()->isVectorType() ||
6950       RHS.get()->getType()->isVectorType())
6951     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6952                                /*AllowBothBool*/true,
6953                                /*AllowBoolConversions*/false);
6954 
6955   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6956   if (LHS.isInvalid() || RHS.isInvalid())
6957     return QualType();
6958 
6959   QualType LHSTy = LHS.get()->getType();
6960   QualType RHSTy = RHS.get()->getType();
6961 
6962   // Diagnose attempts to convert between __float128 and long double where
6963   // such conversions currently can't be handled.
6964   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6965     Diag(QuestionLoc,
6966          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6967       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6968     return QualType();
6969   }
6970 
6971   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6972   // selection operator (?:).
6973   if (getLangOpts().OpenCL &&
6974       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6975     return QualType();
6976   }
6977 
6978   // If both operands have arithmetic type, do the usual arithmetic conversions
6979   // to find a common type: C99 6.5.15p3,5.
6980   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6981     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6982     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6983 
6984     return ResTy;
6985   }
6986 
6987   // If both operands are the same structure or union type, the result is that
6988   // type.
6989   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6990     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6991       if (LHSRT->getDecl() == RHSRT->getDecl())
6992         // "If both the operands have structure or union type, the result has
6993         // that type."  This implies that CV qualifiers are dropped.
6994         return LHSTy.getUnqualifiedType();
6995     // FIXME: Type of conditional expression must be complete in C mode.
6996   }
6997 
6998   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6999   // The following || allows only one side to be void (a GCC-ism).
7000   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7001     return checkConditionalVoidType(*this, LHS, RHS);
7002   }
7003 
7004   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7005   // the type of the other operand."
7006   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7007   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7008 
7009   // All objective-c pointer type analysis is done here.
7010   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7011                                                         QuestionLoc);
7012   if (LHS.isInvalid() || RHS.isInvalid())
7013     return QualType();
7014   if (!compositeType.isNull())
7015     return compositeType;
7016 
7017 
7018   // Handle block pointer types.
7019   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7020     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7021                                                      QuestionLoc);
7022 
7023   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7024   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7025     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7026                                                        QuestionLoc);
7027 
7028   // GCC compatibility: soften pointer/integer mismatch.  Note that
7029   // null pointers have been filtered out by this point.
7030   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7031       /*isIntFirstExpr=*/true))
7032     return RHSTy;
7033   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7034       /*isIntFirstExpr=*/false))
7035     return LHSTy;
7036 
7037   // Emit a better diagnostic if one of the expressions is a null pointer
7038   // constant and the other is not a pointer type. In this case, the user most
7039   // likely forgot to take the address of the other expression.
7040   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7041     return QualType();
7042 
7043   // Otherwise, the operands are not compatible.
7044   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7045     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7046     << RHS.get()->getSourceRange();
7047   return QualType();
7048 }
7049 
7050 /// FindCompositeObjCPointerType - Helper method to find composite type of
7051 /// two objective-c pointer types of the two input expressions.
7052 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7053                                             SourceLocation QuestionLoc) {
7054   QualType LHSTy = LHS.get()->getType();
7055   QualType RHSTy = RHS.get()->getType();
7056 
7057   // Handle things like Class and struct objc_class*.  Here we case the result
7058   // to the pseudo-builtin, because that will be implicitly cast back to the
7059   // redefinition type if an attempt is made to access its fields.
7060   if (LHSTy->isObjCClassType() &&
7061       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7062     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7063     return LHSTy;
7064   }
7065   if (RHSTy->isObjCClassType() &&
7066       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7067     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7068     return RHSTy;
7069   }
7070   // And the same for struct objc_object* / id
7071   if (LHSTy->isObjCIdType() &&
7072       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7073     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7074     return LHSTy;
7075   }
7076   if (RHSTy->isObjCIdType() &&
7077       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7078     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7079     return RHSTy;
7080   }
7081   // And the same for struct objc_selector* / SEL
7082   if (Context.isObjCSelType(LHSTy) &&
7083       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7084     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7085     return LHSTy;
7086   }
7087   if (Context.isObjCSelType(RHSTy) &&
7088       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7089     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7090     return RHSTy;
7091   }
7092   // Check constraints for Objective-C object pointers types.
7093   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7094 
7095     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7096       // Two identical object pointer types are always compatible.
7097       return LHSTy;
7098     }
7099     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7100     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7101     QualType compositeType = LHSTy;
7102 
7103     // If both operands are interfaces and either operand can be
7104     // assigned to the other, use that type as the composite
7105     // type. This allows
7106     //   xxx ? (A*) a : (B*) b
7107     // where B is a subclass of A.
7108     //
7109     // Additionally, as for assignment, if either type is 'id'
7110     // allow silent coercion. Finally, if the types are
7111     // incompatible then make sure to use 'id' as the composite
7112     // type so the result is acceptable for sending messages to.
7113 
7114     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7115     // It could return the composite type.
7116     if (!(compositeType =
7117           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7118       // Nothing more to do.
7119     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7120       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7121     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7122       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7123     } else if ((LHSTy->isObjCQualifiedIdType() ||
7124                 RHSTy->isObjCQualifiedIdType()) &&
7125                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7126       // Need to handle "id<xx>" explicitly.
7127       // GCC allows qualified id and any Objective-C type to devolve to
7128       // id. Currently localizing to here until clear this should be
7129       // part of ObjCQualifiedIdTypesAreCompatible.
7130       compositeType = Context.getObjCIdType();
7131     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7132       compositeType = Context.getObjCIdType();
7133     } else {
7134       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7135       << LHSTy << RHSTy
7136       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7137       QualType incompatTy = Context.getObjCIdType();
7138       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7139       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7140       return incompatTy;
7141     }
7142     // The object pointer types are compatible.
7143     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7144     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7145     return compositeType;
7146   }
7147   // Check Objective-C object pointer types and 'void *'
7148   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7149     if (getLangOpts().ObjCAutoRefCount) {
7150       // ARC forbids the implicit conversion of object pointers to 'void *',
7151       // so these types are not compatible.
7152       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7153           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7154       LHS = RHS = true;
7155       return QualType();
7156     }
7157     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7158     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7159     QualType destPointee
7160     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7161     QualType destType = Context.getPointerType(destPointee);
7162     // Add qualifiers if necessary.
7163     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7164     // Promote to void*.
7165     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7166     return destType;
7167   }
7168   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7169     if (getLangOpts().ObjCAutoRefCount) {
7170       // ARC forbids the implicit conversion of object pointers to 'void *',
7171       // so these types are not compatible.
7172       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7173           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7174       LHS = RHS = true;
7175       return QualType();
7176     }
7177     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7178     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7179     QualType destPointee
7180     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7181     QualType destType = Context.getPointerType(destPointee);
7182     // Add qualifiers if necessary.
7183     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7184     // Promote to void*.
7185     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7186     return destType;
7187   }
7188   return QualType();
7189 }
7190 
7191 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7192 /// ParenRange in parentheses.
7193 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7194                                const PartialDiagnostic &Note,
7195                                SourceRange ParenRange) {
7196   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7197   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7198       EndLoc.isValid()) {
7199     Self.Diag(Loc, Note)
7200       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7201       << FixItHint::CreateInsertion(EndLoc, ")");
7202   } else {
7203     // We can't display the parentheses, so just show the bare note.
7204     Self.Diag(Loc, Note) << ParenRange;
7205   }
7206 }
7207 
7208 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7209   return BinaryOperator::isAdditiveOp(Opc) ||
7210          BinaryOperator::isMultiplicativeOp(Opc) ||
7211          BinaryOperator::isShiftOp(Opc);
7212 }
7213 
7214 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7215 /// expression, either using a built-in or overloaded operator,
7216 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7217 /// expression.
7218 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7219                                    Expr **RHSExprs) {
7220   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7221   E = E->IgnoreImpCasts();
7222   E = E->IgnoreConversionOperator();
7223   E = E->IgnoreImpCasts();
7224   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7225     E = MTE->GetTemporaryExpr();
7226     E = E->IgnoreImpCasts();
7227   }
7228 
7229   // Built-in binary operator.
7230   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7231     if (IsArithmeticOp(OP->getOpcode())) {
7232       *Opcode = OP->getOpcode();
7233       *RHSExprs = OP->getRHS();
7234       return true;
7235     }
7236   }
7237 
7238   // Overloaded operator.
7239   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7240     if (Call->getNumArgs() != 2)
7241       return false;
7242 
7243     // Make sure this is really a binary operator that is safe to pass into
7244     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7245     OverloadedOperatorKind OO = Call->getOperator();
7246     if (OO < OO_Plus || OO > OO_Arrow ||
7247         OO == OO_PlusPlus || OO == OO_MinusMinus)
7248       return false;
7249 
7250     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7251     if (IsArithmeticOp(OpKind)) {
7252       *Opcode = OpKind;
7253       *RHSExprs = Call->getArg(1);
7254       return true;
7255     }
7256   }
7257 
7258   return false;
7259 }
7260 
7261 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7262 /// or is a logical expression such as (x==y) which has int type, but is
7263 /// commonly interpreted as boolean.
7264 static bool ExprLooksBoolean(Expr *E) {
7265   E = E->IgnoreParenImpCasts();
7266 
7267   if (E->getType()->isBooleanType())
7268     return true;
7269   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7270     return OP->isComparisonOp() || OP->isLogicalOp();
7271   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7272     return OP->getOpcode() == UO_LNot;
7273   if (E->getType()->isPointerType())
7274     return true;
7275   // FIXME: What about overloaded operator calls returning "unspecified boolean
7276   // type"s (commonly pointer-to-members)?
7277 
7278   return false;
7279 }
7280 
7281 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7282 /// and binary operator are mixed in a way that suggests the programmer assumed
7283 /// the conditional operator has higher precedence, for example:
7284 /// "int x = a + someBinaryCondition ? 1 : 2".
7285 static void DiagnoseConditionalPrecedence(Sema &Self,
7286                                           SourceLocation OpLoc,
7287                                           Expr *Condition,
7288                                           Expr *LHSExpr,
7289                                           Expr *RHSExpr) {
7290   BinaryOperatorKind CondOpcode;
7291   Expr *CondRHS;
7292 
7293   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7294     return;
7295   if (!ExprLooksBoolean(CondRHS))
7296     return;
7297 
7298   // The condition is an arithmetic binary expression, with a right-
7299   // hand side that looks boolean, so warn.
7300 
7301   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7302       << Condition->getSourceRange()
7303       << BinaryOperator::getOpcodeStr(CondOpcode);
7304 
7305   SuggestParentheses(
7306       Self, OpLoc,
7307       Self.PDiag(diag::note_precedence_silence)
7308           << BinaryOperator::getOpcodeStr(CondOpcode),
7309       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7310 
7311   SuggestParentheses(Self, OpLoc,
7312                      Self.PDiag(diag::note_precedence_conditional_first),
7313                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7314 }
7315 
7316 /// Compute the nullability of a conditional expression.
7317 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7318                                               QualType LHSTy, QualType RHSTy,
7319                                               ASTContext &Ctx) {
7320   if (!ResTy->isAnyPointerType())
7321     return ResTy;
7322 
7323   auto GetNullability = [&Ctx](QualType Ty) {
7324     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7325     if (Kind)
7326       return *Kind;
7327     return NullabilityKind::Unspecified;
7328   };
7329 
7330   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7331   NullabilityKind MergedKind;
7332 
7333   // Compute nullability of a binary conditional expression.
7334   if (IsBin) {
7335     if (LHSKind == NullabilityKind::NonNull)
7336       MergedKind = NullabilityKind::NonNull;
7337     else
7338       MergedKind = RHSKind;
7339   // Compute nullability of a normal conditional expression.
7340   } else {
7341     if (LHSKind == NullabilityKind::Nullable ||
7342         RHSKind == NullabilityKind::Nullable)
7343       MergedKind = NullabilityKind::Nullable;
7344     else if (LHSKind == NullabilityKind::NonNull)
7345       MergedKind = RHSKind;
7346     else if (RHSKind == NullabilityKind::NonNull)
7347       MergedKind = LHSKind;
7348     else
7349       MergedKind = NullabilityKind::Unspecified;
7350   }
7351 
7352   // Return if ResTy already has the correct nullability.
7353   if (GetNullability(ResTy) == MergedKind)
7354     return ResTy;
7355 
7356   // Strip all nullability from ResTy.
7357   while (ResTy->getNullability(Ctx))
7358     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7359 
7360   // Create a new AttributedType with the new nullability kind.
7361   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7362   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7363 }
7364 
7365 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7366 /// in the case of a the GNU conditional expr extension.
7367 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7368                                     SourceLocation ColonLoc,
7369                                     Expr *CondExpr, Expr *LHSExpr,
7370                                     Expr *RHSExpr) {
7371   if (!getLangOpts().CPlusPlus) {
7372     // C cannot handle TypoExpr nodes in the condition because it
7373     // doesn't handle dependent types properly, so make sure any TypoExprs have
7374     // been dealt with before checking the operands.
7375     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7376     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7377     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7378 
7379     if (!CondResult.isUsable())
7380       return ExprError();
7381 
7382     if (LHSExpr) {
7383       if (!LHSResult.isUsable())
7384         return ExprError();
7385     }
7386 
7387     if (!RHSResult.isUsable())
7388       return ExprError();
7389 
7390     CondExpr = CondResult.get();
7391     LHSExpr = LHSResult.get();
7392     RHSExpr = RHSResult.get();
7393   }
7394 
7395   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7396   // was the condition.
7397   OpaqueValueExpr *opaqueValue = nullptr;
7398   Expr *commonExpr = nullptr;
7399   if (!LHSExpr) {
7400     commonExpr = CondExpr;
7401     // Lower out placeholder types first.  This is important so that we don't
7402     // try to capture a placeholder. This happens in few cases in C++; such
7403     // as Objective-C++'s dictionary subscripting syntax.
7404     if (commonExpr->hasPlaceholderType()) {
7405       ExprResult result = CheckPlaceholderExpr(commonExpr);
7406       if (!result.isUsable()) return ExprError();
7407       commonExpr = result.get();
7408     }
7409     // We usually want to apply unary conversions *before* saving, except
7410     // in the special case of a C++ l-value conditional.
7411     if (!(getLangOpts().CPlusPlus
7412           && !commonExpr->isTypeDependent()
7413           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7414           && commonExpr->isGLValue()
7415           && commonExpr->isOrdinaryOrBitFieldObject()
7416           && RHSExpr->isOrdinaryOrBitFieldObject()
7417           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7418       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7419       if (commonRes.isInvalid())
7420         return ExprError();
7421       commonExpr = commonRes.get();
7422     }
7423 
7424     // If the common expression is a class or array prvalue, materialize it
7425     // so that we can safely refer to it multiple times.
7426     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7427                                    commonExpr->getType()->isArrayType())) {
7428       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7429       if (MatExpr.isInvalid())
7430         return ExprError();
7431       commonExpr = MatExpr.get();
7432     }
7433 
7434     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7435                                                 commonExpr->getType(),
7436                                                 commonExpr->getValueKind(),
7437                                                 commonExpr->getObjectKind(),
7438                                                 commonExpr);
7439     LHSExpr = CondExpr = opaqueValue;
7440   }
7441 
7442   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7443   ExprValueKind VK = VK_RValue;
7444   ExprObjectKind OK = OK_Ordinary;
7445   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7446   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7447                                              VK, OK, QuestionLoc);
7448   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7449       RHS.isInvalid())
7450     return ExprError();
7451 
7452   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7453                                 RHS.get());
7454 
7455   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7456 
7457   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7458                                          Context);
7459 
7460   if (!commonExpr)
7461     return new (Context)
7462         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7463                             RHS.get(), result, VK, OK);
7464 
7465   return new (Context) BinaryConditionalOperator(
7466       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7467       ColonLoc, result, VK, OK);
7468 }
7469 
7470 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7471 // being closely modeled after the C99 spec:-). The odd characteristic of this
7472 // routine is it effectively iqnores the qualifiers on the top level pointee.
7473 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7474 // FIXME: add a couple examples in this comment.
7475 static Sema::AssignConvertType
7476 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7477   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7478   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7479 
7480   // get the "pointed to" type (ignoring qualifiers at the top level)
7481   const Type *lhptee, *rhptee;
7482   Qualifiers lhq, rhq;
7483   std::tie(lhptee, lhq) =
7484       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7485   std::tie(rhptee, rhq) =
7486       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7487 
7488   Sema::AssignConvertType ConvTy = Sema::Compatible;
7489 
7490   // C99 6.5.16.1p1: This following citation is common to constraints
7491   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7492   // qualifiers of the type *pointed to* by the right;
7493 
7494   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7495   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7496       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7497     // Ignore lifetime for further calculation.
7498     lhq.removeObjCLifetime();
7499     rhq.removeObjCLifetime();
7500   }
7501 
7502   if (!lhq.compatiblyIncludes(rhq)) {
7503     // Treat address-space mismatches as fatal.  TODO: address subspaces
7504     if (!lhq.isAddressSpaceSupersetOf(rhq))
7505       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7506 
7507     // It's okay to add or remove GC or lifetime qualifiers when converting to
7508     // and from void*.
7509     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7510                         .compatiblyIncludes(
7511                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7512              && (lhptee->isVoidType() || rhptee->isVoidType()))
7513       ; // keep old
7514 
7515     // Treat lifetime mismatches as fatal.
7516     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7517       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7518 
7519     // For GCC/MS compatibility, other qualifier mismatches are treated
7520     // as still compatible in C.
7521     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7522   }
7523 
7524   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7525   // incomplete type and the other is a pointer to a qualified or unqualified
7526   // version of void...
7527   if (lhptee->isVoidType()) {
7528     if (rhptee->isIncompleteOrObjectType())
7529       return ConvTy;
7530 
7531     // As an extension, we allow cast to/from void* to function pointer.
7532     assert(rhptee->isFunctionType());
7533     return Sema::FunctionVoidPointer;
7534   }
7535 
7536   if (rhptee->isVoidType()) {
7537     if (lhptee->isIncompleteOrObjectType())
7538       return ConvTy;
7539 
7540     // As an extension, we allow cast to/from void* to function pointer.
7541     assert(lhptee->isFunctionType());
7542     return Sema::FunctionVoidPointer;
7543   }
7544 
7545   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7546   // unqualified versions of compatible types, ...
7547   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7548   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7549     // Check if the pointee types are compatible ignoring the sign.
7550     // We explicitly check for char so that we catch "char" vs
7551     // "unsigned char" on systems where "char" is unsigned.
7552     if (lhptee->isCharType())
7553       ltrans = S.Context.UnsignedCharTy;
7554     else if (lhptee->hasSignedIntegerRepresentation())
7555       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7556 
7557     if (rhptee->isCharType())
7558       rtrans = S.Context.UnsignedCharTy;
7559     else if (rhptee->hasSignedIntegerRepresentation())
7560       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7561 
7562     if (ltrans == rtrans) {
7563       // Types are compatible ignoring the sign. Qualifier incompatibility
7564       // takes priority over sign incompatibility because the sign
7565       // warning can be disabled.
7566       if (ConvTy != Sema::Compatible)
7567         return ConvTy;
7568 
7569       return Sema::IncompatiblePointerSign;
7570     }
7571 
7572     // If we are a multi-level pointer, it's possible that our issue is simply
7573     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7574     // the eventual target type is the same and the pointers have the same
7575     // level of indirection, this must be the issue.
7576     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7577       do {
7578         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7579         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7580       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7581 
7582       if (lhptee == rhptee)
7583         return Sema::IncompatibleNestedPointerQualifiers;
7584     }
7585 
7586     // General pointer incompatibility takes priority over qualifiers.
7587     return Sema::IncompatiblePointer;
7588   }
7589   if (!S.getLangOpts().CPlusPlus &&
7590       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7591     return Sema::IncompatiblePointer;
7592   return ConvTy;
7593 }
7594 
7595 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7596 /// block pointer types are compatible or whether a block and normal pointer
7597 /// are compatible. It is more restrict than comparing two function pointer
7598 // types.
7599 static Sema::AssignConvertType
7600 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7601                                     QualType RHSType) {
7602   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7603   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7604 
7605   QualType lhptee, rhptee;
7606 
7607   // get the "pointed to" type (ignoring qualifiers at the top level)
7608   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7609   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7610 
7611   // In C++, the types have to match exactly.
7612   if (S.getLangOpts().CPlusPlus)
7613     return Sema::IncompatibleBlockPointer;
7614 
7615   Sema::AssignConvertType ConvTy = Sema::Compatible;
7616 
7617   // For blocks we enforce that qualifiers are identical.
7618   Qualifiers LQuals = lhptee.getLocalQualifiers();
7619   Qualifiers RQuals = rhptee.getLocalQualifiers();
7620   if (S.getLangOpts().OpenCL) {
7621     LQuals.removeAddressSpace();
7622     RQuals.removeAddressSpace();
7623   }
7624   if (LQuals != RQuals)
7625     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7626 
7627   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7628   // assignment.
7629   // The current behavior is similar to C++ lambdas. A block might be
7630   // assigned to a variable iff its return type and parameters are compatible
7631   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7632   // an assignment. Presumably it should behave in way that a function pointer
7633   // assignment does in C, so for each parameter and return type:
7634   //  * CVR and address space of LHS should be a superset of CVR and address
7635   //  space of RHS.
7636   //  * unqualified types should be compatible.
7637   if (S.getLangOpts().OpenCL) {
7638     if (!S.Context.typesAreBlockPointerCompatible(
7639             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7640             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7641       return Sema::IncompatibleBlockPointer;
7642   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7643     return Sema::IncompatibleBlockPointer;
7644 
7645   return ConvTy;
7646 }
7647 
7648 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7649 /// for assignment compatibility.
7650 static Sema::AssignConvertType
7651 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7652                                    QualType RHSType) {
7653   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7654   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7655 
7656   if (LHSType->isObjCBuiltinType()) {
7657     // Class is not compatible with ObjC object pointers.
7658     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7659         !RHSType->isObjCQualifiedClassType())
7660       return Sema::IncompatiblePointer;
7661     return Sema::Compatible;
7662   }
7663   if (RHSType->isObjCBuiltinType()) {
7664     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7665         !LHSType->isObjCQualifiedClassType())
7666       return Sema::IncompatiblePointer;
7667     return Sema::Compatible;
7668   }
7669   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7670   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7671 
7672   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7673       // make an exception for id<P>
7674       !LHSType->isObjCQualifiedIdType())
7675     return Sema::CompatiblePointerDiscardsQualifiers;
7676 
7677   if (S.Context.typesAreCompatible(LHSType, RHSType))
7678     return Sema::Compatible;
7679   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7680     return Sema::IncompatibleObjCQualifiedId;
7681   return Sema::IncompatiblePointer;
7682 }
7683 
7684 Sema::AssignConvertType
7685 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7686                                  QualType LHSType, QualType RHSType) {
7687   // Fake up an opaque expression.  We don't actually care about what
7688   // cast operations are required, so if CheckAssignmentConstraints
7689   // adds casts to this they'll be wasted, but fortunately that doesn't
7690   // usually happen on valid code.
7691   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7692   ExprResult RHSPtr = &RHSExpr;
7693   CastKind K;
7694 
7695   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7696 }
7697 
7698 /// This helper function returns true if QT is a vector type that has element
7699 /// type ElementType.
7700 static bool isVector(QualType QT, QualType ElementType) {
7701   if (const VectorType *VT = QT->getAs<VectorType>())
7702     return VT->getElementType() == ElementType;
7703   return false;
7704 }
7705 
7706 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7707 /// has code to accommodate several GCC extensions when type checking
7708 /// pointers. Here are some objectionable examples that GCC considers warnings:
7709 ///
7710 ///  int a, *pint;
7711 ///  short *pshort;
7712 ///  struct foo *pfoo;
7713 ///
7714 ///  pint = pshort; // warning: assignment from incompatible pointer type
7715 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7716 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7717 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7718 ///
7719 /// As a result, the code for dealing with pointers is more complex than the
7720 /// C99 spec dictates.
7721 ///
7722 /// Sets 'Kind' for any result kind except Incompatible.
7723 Sema::AssignConvertType
7724 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7725                                  CastKind &Kind, bool ConvertRHS) {
7726   QualType RHSType = RHS.get()->getType();
7727   QualType OrigLHSType = LHSType;
7728 
7729   // Get canonical types.  We're not formatting these types, just comparing
7730   // them.
7731   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7732   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7733 
7734   // Common case: no conversion required.
7735   if (LHSType == RHSType) {
7736     Kind = CK_NoOp;
7737     return Compatible;
7738   }
7739 
7740   // If we have an atomic type, try a non-atomic assignment, then just add an
7741   // atomic qualification step.
7742   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7743     Sema::AssignConvertType result =
7744       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7745     if (result != Compatible)
7746       return result;
7747     if (Kind != CK_NoOp && ConvertRHS)
7748       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7749     Kind = CK_NonAtomicToAtomic;
7750     return Compatible;
7751   }
7752 
7753   // If the left-hand side is a reference type, then we are in a
7754   // (rare!) case where we've allowed the use of references in C,
7755   // e.g., as a parameter type in a built-in function. In this case,
7756   // just make sure that the type referenced is compatible with the
7757   // right-hand side type. The caller is responsible for adjusting
7758   // LHSType so that the resulting expression does not have reference
7759   // type.
7760   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7761     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7762       Kind = CK_LValueBitCast;
7763       return Compatible;
7764     }
7765     return Incompatible;
7766   }
7767 
7768   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7769   // to the same ExtVector type.
7770   if (LHSType->isExtVectorType()) {
7771     if (RHSType->isExtVectorType())
7772       return Incompatible;
7773     if (RHSType->isArithmeticType()) {
7774       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7775       if (ConvertRHS)
7776         RHS = prepareVectorSplat(LHSType, RHS.get());
7777       Kind = CK_VectorSplat;
7778       return Compatible;
7779     }
7780   }
7781 
7782   // Conversions to or from vector type.
7783   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7784     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7785       // Allow assignments of an AltiVec vector type to an equivalent GCC
7786       // vector type and vice versa
7787       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7788         Kind = CK_BitCast;
7789         return Compatible;
7790       }
7791 
7792       // If we are allowing lax vector conversions, and LHS and RHS are both
7793       // vectors, the total size only needs to be the same. This is a bitcast;
7794       // no bits are changed but the result type is different.
7795       if (isLaxVectorConversion(RHSType, LHSType)) {
7796         Kind = CK_BitCast;
7797         return IncompatibleVectors;
7798       }
7799     }
7800 
7801     // When the RHS comes from another lax conversion (e.g. binops between
7802     // scalars and vectors) the result is canonicalized as a vector. When the
7803     // LHS is also a vector, the lax is allowed by the condition above. Handle
7804     // the case where LHS is a scalar.
7805     if (LHSType->isScalarType()) {
7806       const VectorType *VecType = RHSType->getAs<VectorType>();
7807       if (VecType && VecType->getNumElements() == 1 &&
7808           isLaxVectorConversion(RHSType, LHSType)) {
7809         ExprResult *VecExpr = &RHS;
7810         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7811         Kind = CK_BitCast;
7812         return Compatible;
7813       }
7814     }
7815 
7816     return Incompatible;
7817   }
7818 
7819   // Diagnose attempts to convert between __float128 and long double where
7820   // such conversions currently can't be handled.
7821   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7822     return Incompatible;
7823 
7824   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7825   // discards the imaginary part.
7826   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7827       !LHSType->getAs<ComplexType>())
7828     return Incompatible;
7829 
7830   // Arithmetic conversions.
7831   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7832       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7833     if (ConvertRHS)
7834       Kind = PrepareScalarCast(RHS, LHSType);
7835     return Compatible;
7836   }
7837 
7838   // Conversions to normal pointers.
7839   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7840     // U* -> T*
7841     if (isa<PointerType>(RHSType)) {
7842       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7843       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7844       if (AddrSpaceL != AddrSpaceR)
7845         Kind = CK_AddressSpaceConversion;
7846       else if (Context.hasCvrSimilarType(RHSType, LHSType))
7847         Kind = CK_NoOp;
7848       else
7849         Kind = CK_BitCast;
7850       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7851     }
7852 
7853     // int -> T*
7854     if (RHSType->isIntegerType()) {
7855       Kind = CK_IntegralToPointer; // FIXME: null?
7856       return IntToPointer;
7857     }
7858 
7859     // C pointers are not compatible with ObjC object pointers,
7860     // with two exceptions:
7861     if (isa<ObjCObjectPointerType>(RHSType)) {
7862       //  - conversions to void*
7863       if (LHSPointer->getPointeeType()->isVoidType()) {
7864         Kind = CK_BitCast;
7865         return Compatible;
7866       }
7867 
7868       //  - conversions from 'Class' to the redefinition type
7869       if (RHSType->isObjCClassType() &&
7870           Context.hasSameType(LHSType,
7871                               Context.getObjCClassRedefinitionType())) {
7872         Kind = CK_BitCast;
7873         return Compatible;
7874       }
7875 
7876       Kind = CK_BitCast;
7877       return IncompatiblePointer;
7878     }
7879 
7880     // U^ -> void*
7881     if (RHSType->getAs<BlockPointerType>()) {
7882       if (LHSPointer->getPointeeType()->isVoidType()) {
7883         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7884         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7885                                 ->getPointeeType()
7886                                 .getAddressSpace();
7887         Kind =
7888             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7889         return Compatible;
7890       }
7891     }
7892 
7893     return Incompatible;
7894   }
7895 
7896   // Conversions to block pointers.
7897   if (isa<BlockPointerType>(LHSType)) {
7898     // U^ -> T^
7899     if (RHSType->isBlockPointerType()) {
7900       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7901                               ->getPointeeType()
7902                               .getAddressSpace();
7903       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7904                               ->getPointeeType()
7905                               .getAddressSpace();
7906       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7907       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7908     }
7909 
7910     // int or null -> T^
7911     if (RHSType->isIntegerType()) {
7912       Kind = CK_IntegralToPointer; // FIXME: null
7913       return IntToBlockPointer;
7914     }
7915 
7916     // id -> T^
7917     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
7918       Kind = CK_AnyPointerToBlockPointerCast;
7919       return Compatible;
7920     }
7921 
7922     // void* -> T^
7923     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7924       if (RHSPT->getPointeeType()->isVoidType()) {
7925         Kind = CK_AnyPointerToBlockPointerCast;
7926         return Compatible;
7927       }
7928 
7929     return Incompatible;
7930   }
7931 
7932   // Conversions to Objective-C pointers.
7933   if (isa<ObjCObjectPointerType>(LHSType)) {
7934     // A* -> B*
7935     if (RHSType->isObjCObjectPointerType()) {
7936       Kind = CK_BitCast;
7937       Sema::AssignConvertType result =
7938         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7939       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7940           result == Compatible &&
7941           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7942         result = IncompatibleObjCWeakRef;
7943       return result;
7944     }
7945 
7946     // int or null -> A*
7947     if (RHSType->isIntegerType()) {
7948       Kind = CK_IntegralToPointer; // FIXME: null
7949       return IntToPointer;
7950     }
7951 
7952     // In general, C pointers are not compatible with ObjC object pointers,
7953     // with two exceptions:
7954     if (isa<PointerType>(RHSType)) {
7955       Kind = CK_CPointerToObjCPointerCast;
7956 
7957       //  - conversions from 'void*'
7958       if (RHSType->isVoidPointerType()) {
7959         return Compatible;
7960       }
7961 
7962       //  - conversions to 'Class' from its redefinition type
7963       if (LHSType->isObjCClassType() &&
7964           Context.hasSameType(RHSType,
7965                               Context.getObjCClassRedefinitionType())) {
7966         return Compatible;
7967       }
7968 
7969       return IncompatiblePointer;
7970     }
7971 
7972     // Only under strict condition T^ is compatible with an Objective-C pointer.
7973     if (RHSType->isBlockPointerType() &&
7974         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7975       if (ConvertRHS)
7976         maybeExtendBlockObject(RHS);
7977       Kind = CK_BlockPointerToObjCPointerCast;
7978       return Compatible;
7979     }
7980 
7981     return Incompatible;
7982   }
7983 
7984   // Conversions from pointers that are not covered by the above.
7985   if (isa<PointerType>(RHSType)) {
7986     // T* -> _Bool
7987     if (LHSType == Context.BoolTy) {
7988       Kind = CK_PointerToBoolean;
7989       return Compatible;
7990     }
7991 
7992     // T* -> int
7993     if (LHSType->isIntegerType()) {
7994       Kind = CK_PointerToIntegral;
7995       return PointerToInt;
7996     }
7997 
7998     return Incompatible;
7999   }
8000 
8001   // Conversions from Objective-C pointers that are not covered by the above.
8002   if (isa<ObjCObjectPointerType>(RHSType)) {
8003     // T* -> _Bool
8004     if (LHSType == Context.BoolTy) {
8005       Kind = CK_PointerToBoolean;
8006       return Compatible;
8007     }
8008 
8009     // T* -> int
8010     if (LHSType->isIntegerType()) {
8011       Kind = CK_PointerToIntegral;
8012       return PointerToInt;
8013     }
8014 
8015     return Incompatible;
8016   }
8017 
8018   // struct A -> struct B
8019   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8020     if (Context.typesAreCompatible(LHSType, RHSType)) {
8021       Kind = CK_NoOp;
8022       return Compatible;
8023     }
8024   }
8025 
8026   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8027     Kind = CK_IntToOCLSampler;
8028     return Compatible;
8029   }
8030 
8031   return Incompatible;
8032 }
8033 
8034 /// Constructs a transparent union from an expression that is
8035 /// used to initialize the transparent union.
8036 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8037                                       ExprResult &EResult, QualType UnionType,
8038                                       FieldDecl *Field) {
8039   // Build an initializer list that designates the appropriate member
8040   // of the transparent union.
8041   Expr *E = EResult.get();
8042   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8043                                                    E, SourceLocation());
8044   Initializer->setType(UnionType);
8045   Initializer->setInitializedFieldInUnion(Field);
8046 
8047   // Build a compound literal constructing a value of the transparent
8048   // union type from this initializer list.
8049   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8050   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8051                                         VK_RValue, Initializer, false);
8052 }
8053 
8054 Sema::AssignConvertType
8055 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8056                                                ExprResult &RHS) {
8057   QualType RHSType = RHS.get()->getType();
8058 
8059   // If the ArgType is a Union type, we want to handle a potential
8060   // transparent_union GCC extension.
8061   const RecordType *UT = ArgType->getAsUnionType();
8062   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8063     return Incompatible;
8064 
8065   // The field to initialize within the transparent union.
8066   RecordDecl *UD = UT->getDecl();
8067   FieldDecl *InitField = nullptr;
8068   // It's compatible if the expression matches any of the fields.
8069   for (auto *it : UD->fields()) {
8070     if (it->getType()->isPointerType()) {
8071       // If the transparent union contains a pointer type, we allow:
8072       // 1) void pointer
8073       // 2) null pointer constant
8074       if (RHSType->isPointerType())
8075         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8076           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8077           InitField = it;
8078           break;
8079         }
8080 
8081       if (RHS.get()->isNullPointerConstant(Context,
8082                                            Expr::NPC_ValueDependentIsNull)) {
8083         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8084                                 CK_NullToPointer);
8085         InitField = it;
8086         break;
8087       }
8088     }
8089 
8090     CastKind Kind;
8091     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8092           == Compatible) {
8093       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8094       InitField = it;
8095       break;
8096     }
8097   }
8098 
8099   if (!InitField)
8100     return Incompatible;
8101 
8102   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8103   return Compatible;
8104 }
8105 
8106 Sema::AssignConvertType
8107 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8108                                        bool Diagnose,
8109                                        bool DiagnoseCFAudited,
8110                                        bool ConvertRHS) {
8111   // We need to be able to tell the caller whether we diagnosed a problem, if
8112   // they ask us to issue diagnostics.
8113   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8114 
8115   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8116   // we can't avoid *all* modifications at the moment, so we need some somewhere
8117   // to put the updated value.
8118   ExprResult LocalRHS = CallerRHS;
8119   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8120 
8121   if (getLangOpts().CPlusPlus) {
8122     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8123       // C++ 5.17p3: If the left operand is not of class type, the
8124       // expression is implicitly converted (C++ 4) to the
8125       // cv-unqualified type of the left operand.
8126       QualType RHSType = RHS.get()->getType();
8127       if (Diagnose) {
8128         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8129                                         AA_Assigning);
8130       } else {
8131         ImplicitConversionSequence ICS =
8132             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8133                                   /*SuppressUserConversions=*/false,
8134                                   /*AllowExplicit=*/false,
8135                                   /*InOverloadResolution=*/false,
8136                                   /*CStyle=*/false,
8137                                   /*AllowObjCWritebackConversion=*/false);
8138         if (ICS.isFailure())
8139           return Incompatible;
8140         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8141                                         ICS, AA_Assigning);
8142       }
8143       if (RHS.isInvalid())
8144         return Incompatible;
8145       Sema::AssignConvertType result = Compatible;
8146       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8147           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8148         result = IncompatibleObjCWeakRef;
8149       return result;
8150     }
8151 
8152     // FIXME: Currently, we fall through and treat C++ classes like C
8153     // structures.
8154     // FIXME: We also fall through for atomics; not sure what should
8155     // happen there, though.
8156   } else if (RHS.get()->getType() == Context.OverloadTy) {
8157     // As a set of extensions to C, we support overloading on functions. These
8158     // functions need to be resolved here.
8159     DeclAccessPair DAP;
8160     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8161             RHS.get(), LHSType, /*Complain=*/false, DAP))
8162       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8163     else
8164       return Incompatible;
8165   }
8166 
8167   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8168   // a null pointer constant.
8169   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8170        LHSType->isBlockPointerType()) &&
8171       RHS.get()->isNullPointerConstant(Context,
8172                                        Expr::NPC_ValueDependentIsNull)) {
8173     if (Diagnose || ConvertRHS) {
8174       CastKind Kind;
8175       CXXCastPath Path;
8176       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8177                              /*IgnoreBaseAccess=*/false, Diagnose);
8178       if (ConvertRHS)
8179         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8180     }
8181     return Compatible;
8182   }
8183 
8184   // OpenCL queue_t type assignment.
8185   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8186                                  Context, Expr::NPC_ValueDependentIsNull)) {
8187     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8188     return Compatible;
8189   }
8190 
8191   // This check seems unnatural, however it is necessary to ensure the proper
8192   // conversion of functions/arrays. If the conversion were done for all
8193   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8194   // expressions that suppress this implicit conversion (&, sizeof).
8195   //
8196   // Suppress this for references: C++ 8.5.3p5.
8197   if (!LHSType->isReferenceType()) {
8198     // FIXME: We potentially allocate here even if ConvertRHS is false.
8199     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8200     if (RHS.isInvalid())
8201       return Incompatible;
8202   }
8203   CastKind Kind;
8204   Sema::AssignConvertType result =
8205     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8206 
8207   // C99 6.5.16.1p2: The value of the right operand is converted to the
8208   // type of the assignment expression.
8209   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8210   // so that we can use references in built-in functions even in C.
8211   // The getNonReferenceType() call makes sure that the resulting expression
8212   // does not have reference type.
8213   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8214     QualType Ty = LHSType.getNonLValueExprType(Context);
8215     Expr *E = RHS.get();
8216 
8217     // Check for various Objective-C errors. If we are not reporting
8218     // diagnostics and just checking for errors, e.g., during overload
8219     // resolution, return Incompatible to indicate the failure.
8220     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8221         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8222                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8223       if (!Diagnose)
8224         return Incompatible;
8225     }
8226     if (getLangOpts().ObjC &&
8227         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8228                                            E->getType(), E, Diagnose) ||
8229          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8230       if (!Diagnose)
8231         return Incompatible;
8232       // Replace the expression with a corrected version and continue so we
8233       // can find further errors.
8234       RHS = E;
8235       return Compatible;
8236     }
8237 
8238     if (ConvertRHS)
8239       RHS = ImpCastExprToType(E, Ty, Kind);
8240   }
8241   return result;
8242 }
8243 
8244 namespace {
8245 /// The original operand to an operator, prior to the application of the usual
8246 /// arithmetic conversions and converting the arguments of a builtin operator
8247 /// candidate.
8248 struct OriginalOperand {
8249   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8250     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8251       Op = MTE->GetTemporaryExpr();
8252     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8253       Op = BTE->getSubExpr();
8254     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8255       Orig = ICE->getSubExprAsWritten();
8256       Conversion = ICE->getConversionFunction();
8257     }
8258   }
8259 
8260   QualType getType() const { return Orig->getType(); }
8261 
8262   Expr *Orig;
8263   NamedDecl *Conversion;
8264 };
8265 }
8266 
8267 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8268                                ExprResult &RHS) {
8269   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8270 
8271   Diag(Loc, diag::err_typecheck_invalid_operands)
8272     << OrigLHS.getType() << OrigRHS.getType()
8273     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8274 
8275   // If a user-defined conversion was applied to either of the operands prior
8276   // to applying the built-in operator rules, tell the user about it.
8277   if (OrigLHS.Conversion) {
8278     Diag(OrigLHS.Conversion->getLocation(),
8279          diag::note_typecheck_invalid_operands_converted)
8280       << 0 << LHS.get()->getType();
8281   }
8282   if (OrigRHS.Conversion) {
8283     Diag(OrigRHS.Conversion->getLocation(),
8284          diag::note_typecheck_invalid_operands_converted)
8285       << 1 << RHS.get()->getType();
8286   }
8287 
8288   return QualType();
8289 }
8290 
8291 // Diagnose cases where a scalar was implicitly converted to a vector and
8292 // diagnose the underlying types. Otherwise, diagnose the error
8293 // as invalid vector logical operands for non-C++ cases.
8294 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8295                                             ExprResult &RHS) {
8296   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8297   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8298 
8299   bool LHSNatVec = LHSType->isVectorType();
8300   bool RHSNatVec = RHSType->isVectorType();
8301 
8302   if (!(LHSNatVec && RHSNatVec)) {
8303     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8304     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8305     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8306         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8307         << Vector->getSourceRange();
8308     return QualType();
8309   }
8310 
8311   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8312       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8313       << RHS.get()->getSourceRange();
8314 
8315   return QualType();
8316 }
8317 
8318 /// Try to convert a value of non-vector type to a vector type by converting
8319 /// the type to the element type of the vector and then performing a splat.
8320 /// If the language is OpenCL, we only use conversions that promote scalar
8321 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8322 /// for float->int.
8323 ///
8324 /// OpenCL V2.0 6.2.6.p2:
8325 /// An error shall occur if any scalar operand type has greater rank
8326 /// than the type of the vector element.
8327 ///
8328 /// \param scalar - if non-null, actually perform the conversions
8329 /// \return true if the operation fails (but without diagnosing the failure)
8330 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8331                                      QualType scalarTy,
8332                                      QualType vectorEltTy,
8333                                      QualType vectorTy,
8334                                      unsigned &DiagID) {
8335   // The conversion to apply to the scalar before splatting it,
8336   // if necessary.
8337   CastKind scalarCast = CK_NoOp;
8338 
8339   if (vectorEltTy->isIntegralType(S.Context)) {
8340     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8341         (scalarTy->isIntegerType() &&
8342          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8343       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8344       return true;
8345     }
8346     if (!scalarTy->isIntegralType(S.Context))
8347       return true;
8348     scalarCast = CK_IntegralCast;
8349   } else if (vectorEltTy->isRealFloatingType()) {
8350     if (scalarTy->isRealFloatingType()) {
8351       if (S.getLangOpts().OpenCL &&
8352           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8353         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8354         return true;
8355       }
8356       scalarCast = CK_FloatingCast;
8357     }
8358     else if (scalarTy->isIntegralType(S.Context))
8359       scalarCast = CK_IntegralToFloating;
8360     else
8361       return true;
8362   } else {
8363     return true;
8364   }
8365 
8366   // Adjust scalar if desired.
8367   if (scalar) {
8368     if (scalarCast != CK_NoOp)
8369       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8370     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8371   }
8372   return false;
8373 }
8374 
8375 /// Convert vector E to a vector with the same number of elements but different
8376 /// element type.
8377 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8378   const auto *VecTy = E->getType()->getAs<VectorType>();
8379   assert(VecTy && "Expression E must be a vector");
8380   QualType NewVecTy = S.Context.getVectorType(ElementType,
8381                                               VecTy->getNumElements(),
8382                                               VecTy->getVectorKind());
8383 
8384   // Look through the implicit cast. Return the subexpression if its type is
8385   // NewVecTy.
8386   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8387     if (ICE->getSubExpr()->getType() == NewVecTy)
8388       return ICE->getSubExpr();
8389 
8390   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8391   return S.ImpCastExprToType(E, NewVecTy, Cast);
8392 }
8393 
8394 /// Test if a (constant) integer Int can be casted to another integer type
8395 /// IntTy without losing precision.
8396 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8397                                       QualType OtherIntTy) {
8398   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8399 
8400   // Reject cases where the value of the Int is unknown as that would
8401   // possibly cause truncation, but accept cases where the scalar can be
8402   // demoted without loss of precision.
8403   llvm::APSInt Result;
8404   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8405   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8406   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8407   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8408 
8409   if (CstInt) {
8410     // If the scalar is constant and is of a higher order and has more active
8411     // bits that the vector element type, reject it.
8412     unsigned NumBits = IntSigned
8413                            ? (Result.isNegative() ? Result.getMinSignedBits()
8414                                                   : Result.getActiveBits())
8415                            : Result.getActiveBits();
8416     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8417       return true;
8418 
8419     // If the signedness of the scalar type and the vector element type
8420     // differs and the number of bits is greater than that of the vector
8421     // element reject it.
8422     return (IntSigned != OtherIntSigned &&
8423             NumBits > S.Context.getIntWidth(OtherIntTy));
8424   }
8425 
8426   // Reject cases where the value of the scalar is not constant and it's
8427   // order is greater than that of the vector element type.
8428   return (Order < 0);
8429 }
8430 
8431 /// Test if a (constant) integer Int can be casted to floating point type
8432 /// FloatTy without losing precision.
8433 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8434                                      QualType FloatTy) {
8435   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8436 
8437   // Determine if the integer constant can be expressed as a floating point
8438   // number of the appropriate type.
8439   llvm::APSInt Result;
8440   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8441   uint64_t Bits = 0;
8442   if (CstInt) {
8443     // Reject constants that would be truncated if they were converted to
8444     // the floating point type. Test by simple to/from conversion.
8445     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8446     //        could be avoided if there was a convertFromAPInt method
8447     //        which could signal back if implicit truncation occurred.
8448     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8449     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8450                            llvm::APFloat::rmTowardZero);
8451     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8452                              !IntTy->hasSignedIntegerRepresentation());
8453     bool Ignored = false;
8454     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8455                            &Ignored);
8456     if (Result != ConvertBack)
8457       return true;
8458   } else {
8459     // Reject types that cannot be fully encoded into the mantissa of
8460     // the float.
8461     Bits = S.Context.getTypeSize(IntTy);
8462     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8463         S.Context.getFloatTypeSemantics(FloatTy));
8464     if (Bits > FloatPrec)
8465       return true;
8466   }
8467 
8468   return false;
8469 }
8470 
8471 /// Attempt to convert and splat Scalar into a vector whose types matches
8472 /// Vector following GCC conversion rules. The rule is that implicit
8473 /// conversion can occur when Scalar can be casted to match Vector's element
8474 /// type without causing truncation of Scalar.
8475 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8476                                         ExprResult *Vector) {
8477   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8478   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8479   const VectorType *VT = VectorTy->getAs<VectorType>();
8480 
8481   assert(!isa<ExtVectorType>(VT) &&
8482          "ExtVectorTypes should not be handled here!");
8483 
8484   QualType VectorEltTy = VT->getElementType();
8485 
8486   // Reject cases where the vector element type or the scalar element type are
8487   // not integral or floating point types.
8488   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8489     return true;
8490 
8491   // The conversion to apply to the scalar before splatting it,
8492   // if necessary.
8493   CastKind ScalarCast = CK_NoOp;
8494 
8495   // Accept cases where the vector elements are integers and the scalar is
8496   // an integer.
8497   // FIXME: Notionally if the scalar was a floating point value with a precise
8498   //        integral representation, we could cast it to an appropriate integer
8499   //        type and then perform the rest of the checks here. GCC will perform
8500   //        this conversion in some cases as determined by the input language.
8501   //        We should accept it on a language independent basis.
8502   if (VectorEltTy->isIntegralType(S.Context) &&
8503       ScalarTy->isIntegralType(S.Context) &&
8504       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8505 
8506     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8507       return true;
8508 
8509     ScalarCast = CK_IntegralCast;
8510   } else if (VectorEltTy->isRealFloatingType()) {
8511     if (ScalarTy->isRealFloatingType()) {
8512 
8513       // Reject cases where the scalar type is not a constant and has a higher
8514       // Order than the vector element type.
8515       llvm::APFloat Result(0.0);
8516       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8517       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8518       if (!CstScalar && Order < 0)
8519         return true;
8520 
8521       // If the scalar cannot be safely casted to the vector element type,
8522       // reject it.
8523       if (CstScalar) {
8524         bool Truncated = false;
8525         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8526                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8527         if (Truncated)
8528           return true;
8529       }
8530 
8531       ScalarCast = CK_FloatingCast;
8532     } else if (ScalarTy->isIntegralType(S.Context)) {
8533       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8534         return true;
8535 
8536       ScalarCast = CK_IntegralToFloating;
8537     } else
8538       return true;
8539   }
8540 
8541   // Adjust scalar if desired.
8542   if (Scalar) {
8543     if (ScalarCast != CK_NoOp)
8544       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8545     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8546   }
8547   return false;
8548 }
8549 
8550 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8551                                    SourceLocation Loc, bool IsCompAssign,
8552                                    bool AllowBothBool,
8553                                    bool AllowBoolConversions) {
8554   if (!IsCompAssign) {
8555     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8556     if (LHS.isInvalid())
8557       return QualType();
8558   }
8559   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8560   if (RHS.isInvalid())
8561     return QualType();
8562 
8563   // For conversion purposes, we ignore any qualifiers.
8564   // For example, "const float" and "float" are equivalent.
8565   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8566   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8567 
8568   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8569   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8570   assert(LHSVecType || RHSVecType);
8571 
8572   // AltiVec-style "vector bool op vector bool" combinations are allowed
8573   // for some operators but not others.
8574   if (!AllowBothBool &&
8575       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8576       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8577     return InvalidOperands(Loc, LHS, RHS);
8578 
8579   // If the vector types are identical, return.
8580   if (Context.hasSameType(LHSType, RHSType))
8581     return LHSType;
8582 
8583   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8584   if (LHSVecType && RHSVecType &&
8585       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8586     if (isa<ExtVectorType>(LHSVecType)) {
8587       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8588       return LHSType;
8589     }
8590 
8591     if (!IsCompAssign)
8592       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8593     return RHSType;
8594   }
8595 
8596   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8597   // can be mixed, with the result being the non-bool type.  The non-bool
8598   // operand must have integer element type.
8599   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8600       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8601       (Context.getTypeSize(LHSVecType->getElementType()) ==
8602        Context.getTypeSize(RHSVecType->getElementType()))) {
8603     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8604         LHSVecType->getElementType()->isIntegerType() &&
8605         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8606       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8607       return LHSType;
8608     }
8609     if (!IsCompAssign &&
8610         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8611         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8612         RHSVecType->getElementType()->isIntegerType()) {
8613       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8614       return RHSType;
8615     }
8616   }
8617 
8618   // If there's a vector type and a scalar, try to convert the scalar to
8619   // the vector element type and splat.
8620   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8621   if (!RHSVecType) {
8622     if (isa<ExtVectorType>(LHSVecType)) {
8623       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8624                                     LHSVecType->getElementType(), LHSType,
8625                                     DiagID))
8626         return LHSType;
8627     } else {
8628       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8629         return LHSType;
8630     }
8631   }
8632   if (!LHSVecType) {
8633     if (isa<ExtVectorType>(RHSVecType)) {
8634       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8635                                     LHSType, RHSVecType->getElementType(),
8636                                     RHSType, DiagID))
8637         return RHSType;
8638     } else {
8639       if (LHS.get()->getValueKind() == VK_LValue ||
8640           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8641         return RHSType;
8642     }
8643   }
8644 
8645   // FIXME: The code below also handles conversion between vectors and
8646   // non-scalars, we should break this down into fine grained specific checks
8647   // and emit proper diagnostics.
8648   QualType VecType = LHSVecType ? LHSType : RHSType;
8649   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8650   QualType OtherType = LHSVecType ? RHSType : LHSType;
8651   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8652   if (isLaxVectorConversion(OtherType, VecType)) {
8653     // If we're allowing lax vector conversions, only the total (data) size
8654     // needs to be the same. For non compound assignment, if one of the types is
8655     // scalar, the result is always the vector type.
8656     if (!IsCompAssign) {
8657       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8658       return VecType;
8659     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8660     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8661     // type. Note that this is already done by non-compound assignments in
8662     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8663     // <1 x T> -> T. The result is also a vector type.
8664     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8665                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8666       ExprResult *RHSExpr = &RHS;
8667       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8668       return VecType;
8669     }
8670   }
8671 
8672   // Okay, the expression is invalid.
8673 
8674   // If there's a non-vector, non-real operand, diagnose that.
8675   if ((!RHSVecType && !RHSType->isRealType()) ||
8676       (!LHSVecType && !LHSType->isRealType())) {
8677     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8678       << LHSType << RHSType
8679       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8680     return QualType();
8681   }
8682 
8683   // OpenCL V1.1 6.2.6.p1:
8684   // If the operands are of more than one vector type, then an error shall
8685   // occur. Implicit conversions between vector types are not permitted, per
8686   // section 6.2.1.
8687   if (getLangOpts().OpenCL &&
8688       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8689       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8690     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8691                                                            << RHSType;
8692     return QualType();
8693   }
8694 
8695 
8696   // If there is a vector type that is not a ExtVector and a scalar, we reach
8697   // this point if scalar could not be converted to the vector's element type
8698   // without truncation.
8699   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8700       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8701     QualType Scalar = LHSVecType ? RHSType : LHSType;
8702     QualType Vector = LHSVecType ? LHSType : RHSType;
8703     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8704     Diag(Loc,
8705          diag::err_typecheck_vector_not_convertable_implict_truncation)
8706         << ScalarOrVector << Scalar << Vector;
8707 
8708     return QualType();
8709   }
8710 
8711   // Otherwise, use the generic diagnostic.
8712   Diag(Loc, DiagID)
8713     << LHSType << RHSType
8714     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8715   return QualType();
8716 }
8717 
8718 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8719 // expression.  These are mainly cases where the null pointer is used as an
8720 // integer instead of a pointer.
8721 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8722                                 SourceLocation Loc, bool IsCompare) {
8723   // The canonical way to check for a GNU null is with isNullPointerConstant,
8724   // but we use a bit of a hack here for speed; this is a relatively
8725   // hot path, and isNullPointerConstant is slow.
8726   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8727   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8728 
8729   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8730 
8731   // Avoid analyzing cases where the result will either be invalid (and
8732   // diagnosed as such) or entirely valid and not something to warn about.
8733   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8734       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8735     return;
8736 
8737   // Comparison operations would not make sense with a null pointer no matter
8738   // what the other expression is.
8739   if (!IsCompare) {
8740     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8741         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8742         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8743     return;
8744   }
8745 
8746   // The rest of the operations only make sense with a null pointer
8747   // if the other expression is a pointer.
8748   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8749       NonNullType->canDecayToPointerType())
8750     return;
8751 
8752   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8753       << LHSNull /* LHS is NULL */ << NonNullType
8754       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8755 }
8756 
8757 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8758                                           SourceLocation Loc) {
8759   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8760   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
8761   if (!LUE || !RUE)
8762     return;
8763   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
8764       RUE->getKind() != UETT_SizeOf)
8765     return;
8766 
8767   QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
8768   QualType RHSTy;
8769 
8770   if (RUE->isArgumentType())
8771     RHSTy = RUE->getArgumentType();
8772   else
8773     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
8774 
8775   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
8776     return;
8777   if (LHSTy->getPointeeType() != RHSTy)
8778     return;
8779 
8780   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
8781 }
8782 
8783 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8784                                                ExprResult &RHS,
8785                                                SourceLocation Loc, bool IsDiv) {
8786   // Check for division/remainder by zero.
8787   llvm::APSInt RHSValue;
8788   if (!RHS.get()->isValueDependent() &&
8789       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8790     S.DiagRuntimeBehavior(Loc, RHS.get(),
8791                           S.PDiag(diag::warn_remainder_division_by_zero)
8792                             << IsDiv << RHS.get()->getSourceRange());
8793 }
8794 
8795 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8796                                            SourceLocation Loc,
8797                                            bool IsCompAssign, bool IsDiv) {
8798   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8799 
8800   if (LHS.get()->getType()->isVectorType() ||
8801       RHS.get()->getType()->isVectorType())
8802     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8803                                /*AllowBothBool*/getLangOpts().AltiVec,
8804                                /*AllowBoolConversions*/false);
8805 
8806   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8807   if (LHS.isInvalid() || RHS.isInvalid())
8808     return QualType();
8809 
8810 
8811   if (compType.isNull() || !compType->isArithmeticType())
8812     return InvalidOperands(Loc, LHS, RHS);
8813   if (IsDiv) {
8814     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8815     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
8816   }
8817   return compType;
8818 }
8819 
8820 QualType Sema::CheckRemainderOperands(
8821   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8822   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8823 
8824   if (LHS.get()->getType()->isVectorType() ||
8825       RHS.get()->getType()->isVectorType()) {
8826     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8827         RHS.get()->getType()->hasIntegerRepresentation())
8828       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8829                                  /*AllowBothBool*/getLangOpts().AltiVec,
8830                                  /*AllowBoolConversions*/false);
8831     return InvalidOperands(Loc, LHS, RHS);
8832   }
8833 
8834   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8835   if (LHS.isInvalid() || RHS.isInvalid())
8836     return QualType();
8837 
8838   if (compType.isNull() || !compType->isIntegerType())
8839     return InvalidOperands(Loc, LHS, RHS);
8840   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8841   return compType;
8842 }
8843 
8844 /// Diagnose invalid arithmetic on two void pointers.
8845 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8846                                                 Expr *LHSExpr, Expr *RHSExpr) {
8847   S.Diag(Loc, S.getLangOpts().CPlusPlus
8848                 ? diag::err_typecheck_pointer_arith_void_type
8849                 : diag::ext_gnu_void_ptr)
8850     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8851                             << RHSExpr->getSourceRange();
8852 }
8853 
8854 /// Diagnose invalid arithmetic on a void pointer.
8855 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8856                                             Expr *Pointer) {
8857   S.Diag(Loc, S.getLangOpts().CPlusPlus
8858                 ? diag::err_typecheck_pointer_arith_void_type
8859                 : diag::ext_gnu_void_ptr)
8860     << 0 /* one pointer */ << Pointer->getSourceRange();
8861 }
8862 
8863 /// Diagnose invalid arithmetic on a null pointer.
8864 ///
8865 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8866 /// idiom, which we recognize as a GNU extension.
8867 ///
8868 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8869                                             Expr *Pointer, bool IsGNUIdiom) {
8870   if (IsGNUIdiom)
8871     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8872       << Pointer->getSourceRange();
8873   else
8874     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8875       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8876 }
8877 
8878 /// Diagnose invalid arithmetic on two function pointers.
8879 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8880                                                     Expr *LHS, Expr *RHS) {
8881   assert(LHS->getType()->isAnyPointerType());
8882   assert(RHS->getType()->isAnyPointerType());
8883   S.Diag(Loc, S.getLangOpts().CPlusPlus
8884                 ? diag::err_typecheck_pointer_arith_function_type
8885                 : diag::ext_gnu_ptr_func_arith)
8886     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8887     // We only show the second type if it differs from the first.
8888     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8889                                                    RHS->getType())
8890     << RHS->getType()->getPointeeType()
8891     << LHS->getSourceRange() << RHS->getSourceRange();
8892 }
8893 
8894 /// Diagnose invalid arithmetic on a function pointer.
8895 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8896                                                 Expr *Pointer) {
8897   assert(Pointer->getType()->isAnyPointerType());
8898   S.Diag(Loc, S.getLangOpts().CPlusPlus
8899                 ? diag::err_typecheck_pointer_arith_function_type
8900                 : diag::ext_gnu_ptr_func_arith)
8901     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8902     << 0 /* one pointer, so only one type */
8903     << Pointer->getSourceRange();
8904 }
8905 
8906 /// Emit error if Operand is incomplete pointer type
8907 ///
8908 /// \returns True if pointer has incomplete type
8909 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8910                                                  Expr *Operand) {
8911   QualType ResType = Operand->getType();
8912   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8913     ResType = ResAtomicType->getValueType();
8914 
8915   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8916   QualType PointeeTy = ResType->getPointeeType();
8917   return S.RequireCompleteType(Loc, PointeeTy,
8918                                diag::err_typecheck_arithmetic_incomplete_type,
8919                                PointeeTy, Operand->getSourceRange());
8920 }
8921 
8922 /// Check the validity of an arithmetic pointer operand.
8923 ///
8924 /// If the operand has pointer type, this code will check for pointer types
8925 /// which are invalid in arithmetic operations. These will be diagnosed
8926 /// appropriately, including whether or not the use is supported as an
8927 /// extension.
8928 ///
8929 /// \returns True when the operand is valid to use (even if as an extension).
8930 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8931                                             Expr *Operand) {
8932   QualType ResType = Operand->getType();
8933   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8934     ResType = ResAtomicType->getValueType();
8935 
8936   if (!ResType->isAnyPointerType()) return true;
8937 
8938   QualType PointeeTy = ResType->getPointeeType();
8939   if (PointeeTy->isVoidType()) {
8940     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8941     return !S.getLangOpts().CPlusPlus;
8942   }
8943   if (PointeeTy->isFunctionType()) {
8944     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8945     return !S.getLangOpts().CPlusPlus;
8946   }
8947 
8948   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8949 
8950   return true;
8951 }
8952 
8953 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8954 /// operands.
8955 ///
8956 /// This routine will diagnose any invalid arithmetic on pointer operands much
8957 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8958 /// for emitting a single diagnostic even for operations where both LHS and RHS
8959 /// are (potentially problematic) pointers.
8960 ///
8961 /// \returns True when the operand is valid to use (even if as an extension).
8962 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8963                                                 Expr *LHSExpr, Expr *RHSExpr) {
8964   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8965   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8966   if (!isLHSPointer && !isRHSPointer) return true;
8967 
8968   QualType LHSPointeeTy, RHSPointeeTy;
8969   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8970   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8971 
8972   // if both are pointers check if operation is valid wrt address spaces
8973   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8974     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8975     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8976     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8977       S.Diag(Loc,
8978              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8979           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8980           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8981       return false;
8982     }
8983   }
8984 
8985   // Check for arithmetic on pointers to incomplete types.
8986   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8987   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8988   if (isLHSVoidPtr || isRHSVoidPtr) {
8989     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8990     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8991     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8992 
8993     return !S.getLangOpts().CPlusPlus;
8994   }
8995 
8996   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8997   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8998   if (isLHSFuncPtr || isRHSFuncPtr) {
8999     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9000     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9001                                                                 RHSExpr);
9002     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9003 
9004     return !S.getLangOpts().CPlusPlus;
9005   }
9006 
9007   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9008     return false;
9009   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9010     return false;
9011 
9012   return true;
9013 }
9014 
9015 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9016 /// literal.
9017 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9018                                   Expr *LHSExpr, Expr *RHSExpr) {
9019   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9020   Expr* IndexExpr = RHSExpr;
9021   if (!StrExpr) {
9022     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9023     IndexExpr = LHSExpr;
9024   }
9025 
9026   bool IsStringPlusInt = StrExpr &&
9027       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9028   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9029     return;
9030 
9031   llvm::APSInt index;
9032   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
9033     unsigned StrLenWithNull = StrExpr->getLength() + 1;
9034     if (index.isNonNegative() &&
9035         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
9036                               index.isUnsigned()))
9037       return;
9038   }
9039 
9040   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9041   Self.Diag(OpLoc, diag::warn_string_plus_int)
9042       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9043 
9044   // Only print a fixit for "str" + int, not for int + "str".
9045   if (IndexExpr == RHSExpr) {
9046     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9047     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9048         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9049         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9050         << FixItHint::CreateInsertion(EndLoc, "]");
9051   } else
9052     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9053 }
9054 
9055 /// Emit a warning when adding a char literal to a string.
9056 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9057                                    Expr *LHSExpr, Expr *RHSExpr) {
9058   const Expr *StringRefExpr = LHSExpr;
9059   const CharacterLiteral *CharExpr =
9060       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9061 
9062   if (!CharExpr) {
9063     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9064     StringRefExpr = RHSExpr;
9065   }
9066 
9067   if (!CharExpr || !StringRefExpr)
9068     return;
9069 
9070   const QualType StringType = StringRefExpr->getType();
9071 
9072   // Return if not a PointerType.
9073   if (!StringType->isAnyPointerType())
9074     return;
9075 
9076   // Return if not a CharacterType.
9077   if (!StringType->getPointeeType()->isAnyCharacterType())
9078     return;
9079 
9080   ASTContext &Ctx = Self.getASTContext();
9081   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9082 
9083   const QualType CharType = CharExpr->getType();
9084   if (!CharType->isAnyCharacterType() &&
9085       CharType->isIntegerType() &&
9086       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9087     Self.Diag(OpLoc, diag::warn_string_plus_char)
9088         << DiagRange << Ctx.CharTy;
9089   } else {
9090     Self.Diag(OpLoc, diag::warn_string_plus_char)
9091         << DiagRange << CharExpr->getType();
9092   }
9093 
9094   // Only print a fixit for str + char, not for char + str.
9095   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9096     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9097     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9098         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9099         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9100         << FixItHint::CreateInsertion(EndLoc, "]");
9101   } else {
9102     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9103   }
9104 }
9105 
9106 /// Emit error when two pointers are incompatible.
9107 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9108                                            Expr *LHSExpr, Expr *RHSExpr) {
9109   assert(LHSExpr->getType()->isAnyPointerType());
9110   assert(RHSExpr->getType()->isAnyPointerType());
9111   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9112     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9113     << RHSExpr->getSourceRange();
9114 }
9115 
9116 // C99 6.5.6
9117 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9118                                      SourceLocation Loc, BinaryOperatorKind Opc,
9119                                      QualType* CompLHSTy) {
9120   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9121 
9122   if (LHS.get()->getType()->isVectorType() ||
9123       RHS.get()->getType()->isVectorType()) {
9124     QualType compType = CheckVectorOperands(
9125         LHS, RHS, Loc, CompLHSTy,
9126         /*AllowBothBool*/getLangOpts().AltiVec,
9127         /*AllowBoolConversions*/getLangOpts().ZVector);
9128     if (CompLHSTy) *CompLHSTy = compType;
9129     return compType;
9130   }
9131 
9132   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9133   if (LHS.isInvalid() || RHS.isInvalid())
9134     return QualType();
9135 
9136   // Diagnose "string literal" '+' int and string '+' "char literal".
9137   if (Opc == BO_Add) {
9138     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9139     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9140   }
9141 
9142   // handle the common case first (both operands are arithmetic).
9143   if (!compType.isNull() && compType->isArithmeticType()) {
9144     if (CompLHSTy) *CompLHSTy = compType;
9145     return compType;
9146   }
9147 
9148   // Type-checking.  Ultimately the pointer's going to be in PExp;
9149   // note that we bias towards the LHS being the pointer.
9150   Expr *PExp = LHS.get(), *IExp = RHS.get();
9151 
9152   bool isObjCPointer;
9153   if (PExp->getType()->isPointerType()) {
9154     isObjCPointer = false;
9155   } else if (PExp->getType()->isObjCObjectPointerType()) {
9156     isObjCPointer = true;
9157   } else {
9158     std::swap(PExp, IExp);
9159     if (PExp->getType()->isPointerType()) {
9160       isObjCPointer = false;
9161     } else if (PExp->getType()->isObjCObjectPointerType()) {
9162       isObjCPointer = true;
9163     } else {
9164       return InvalidOperands(Loc, LHS, RHS);
9165     }
9166   }
9167   assert(PExp->getType()->isAnyPointerType());
9168 
9169   if (!IExp->getType()->isIntegerType())
9170     return InvalidOperands(Loc, LHS, RHS);
9171 
9172   // Adding to a null pointer results in undefined behavior.
9173   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9174           Context, Expr::NPC_ValueDependentIsNotNull)) {
9175     // In C++ adding zero to a null pointer is defined.
9176     llvm::APSInt KnownVal;
9177     if (!getLangOpts().CPlusPlus ||
9178         (!IExp->isValueDependent() &&
9179          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9180       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9181       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9182           Context, BO_Add, PExp, IExp);
9183       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9184     }
9185   }
9186 
9187   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9188     return QualType();
9189 
9190   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9191     return QualType();
9192 
9193   // Check array bounds for pointer arithemtic
9194   CheckArrayAccess(PExp, IExp);
9195 
9196   if (CompLHSTy) {
9197     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9198     if (LHSTy.isNull()) {
9199       LHSTy = LHS.get()->getType();
9200       if (LHSTy->isPromotableIntegerType())
9201         LHSTy = Context.getPromotedIntegerType(LHSTy);
9202     }
9203     *CompLHSTy = LHSTy;
9204   }
9205 
9206   return PExp->getType();
9207 }
9208 
9209 // C99 6.5.6
9210 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9211                                         SourceLocation Loc,
9212                                         QualType* CompLHSTy) {
9213   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9214 
9215   if (LHS.get()->getType()->isVectorType() ||
9216       RHS.get()->getType()->isVectorType()) {
9217     QualType compType = CheckVectorOperands(
9218         LHS, RHS, Loc, CompLHSTy,
9219         /*AllowBothBool*/getLangOpts().AltiVec,
9220         /*AllowBoolConversions*/getLangOpts().ZVector);
9221     if (CompLHSTy) *CompLHSTy = compType;
9222     return compType;
9223   }
9224 
9225   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9226   if (LHS.isInvalid() || RHS.isInvalid())
9227     return QualType();
9228 
9229   // Enforce type constraints: C99 6.5.6p3.
9230 
9231   // Handle the common case first (both operands are arithmetic).
9232   if (!compType.isNull() && compType->isArithmeticType()) {
9233     if (CompLHSTy) *CompLHSTy = compType;
9234     return compType;
9235   }
9236 
9237   // Either ptr - int   or   ptr - ptr.
9238   if (LHS.get()->getType()->isAnyPointerType()) {
9239     QualType lpointee = LHS.get()->getType()->getPointeeType();
9240 
9241     // Diagnose bad cases where we step over interface counts.
9242     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9243         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9244       return QualType();
9245 
9246     // The result type of a pointer-int computation is the pointer type.
9247     if (RHS.get()->getType()->isIntegerType()) {
9248       // Subtracting from a null pointer should produce a warning.
9249       // The last argument to the diagnose call says this doesn't match the
9250       // GNU int-to-pointer idiom.
9251       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9252                                            Expr::NPC_ValueDependentIsNotNull)) {
9253         // In C++ adding zero to a null pointer is defined.
9254         llvm::APSInt KnownVal;
9255         if (!getLangOpts().CPlusPlus ||
9256             (!RHS.get()->isValueDependent() &&
9257              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9258           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9259         }
9260       }
9261 
9262       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9263         return QualType();
9264 
9265       // Check array bounds for pointer arithemtic
9266       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9267                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9268 
9269       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9270       return LHS.get()->getType();
9271     }
9272 
9273     // Handle pointer-pointer subtractions.
9274     if (const PointerType *RHSPTy
9275           = RHS.get()->getType()->getAs<PointerType>()) {
9276       QualType rpointee = RHSPTy->getPointeeType();
9277 
9278       if (getLangOpts().CPlusPlus) {
9279         // Pointee types must be the same: C++ [expr.add]
9280         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9281           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9282         }
9283       } else {
9284         // Pointee types must be compatible C99 6.5.6p3
9285         if (!Context.typesAreCompatible(
9286                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9287                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9288           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9289           return QualType();
9290         }
9291       }
9292 
9293       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9294                                                LHS.get(), RHS.get()))
9295         return QualType();
9296 
9297       // FIXME: Add warnings for nullptr - ptr.
9298 
9299       // The pointee type may have zero size.  As an extension, a structure or
9300       // union may have zero size or an array may have zero length.  In this
9301       // case subtraction does not make sense.
9302       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9303         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9304         if (ElementSize.isZero()) {
9305           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9306             << rpointee.getUnqualifiedType()
9307             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9308         }
9309       }
9310 
9311       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9312       return Context.getPointerDiffType();
9313     }
9314   }
9315 
9316   return InvalidOperands(Loc, LHS, RHS);
9317 }
9318 
9319 static bool isScopedEnumerationType(QualType T) {
9320   if (const EnumType *ET = T->getAs<EnumType>())
9321     return ET->getDecl()->isScoped();
9322   return false;
9323 }
9324 
9325 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9326                                    SourceLocation Loc, BinaryOperatorKind Opc,
9327                                    QualType LHSType) {
9328   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9329   // so skip remaining warnings as we don't want to modify values within Sema.
9330   if (S.getLangOpts().OpenCL)
9331     return;
9332 
9333   llvm::APSInt Right;
9334   // Check right/shifter operand
9335   if (RHS.get()->isValueDependent() ||
9336       !RHS.get()->EvaluateAsInt(Right, S.Context))
9337     return;
9338 
9339   if (Right.isNegative()) {
9340     S.DiagRuntimeBehavior(Loc, RHS.get(),
9341                           S.PDiag(diag::warn_shift_negative)
9342                             << RHS.get()->getSourceRange());
9343     return;
9344   }
9345   llvm::APInt LeftBits(Right.getBitWidth(),
9346                        S.Context.getTypeSize(LHS.get()->getType()));
9347   if (Right.uge(LeftBits)) {
9348     S.DiagRuntimeBehavior(Loc, RHS.get(),
9349                           S.PDiag(diag::warn_shift_gt_typewidth)
9350                             << RHS.get()->getSourceRange());
9351     return;
9352   }
9353   if (Opc != BO_Shl)
9354     return;
9355 
9356   // When left shifting an ICE which is signed, we can check for overflow which
9357   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9358   // integers have defined behavior modulo one more than the maximum value
9359   // representable in the result type, so never warn for those.
9360   llvm::APSInt Left;
9361   if (LHS.get()->isValueDependent() ||
9362       LHSType->hasUnsignedIntegerRepresentation() ||
9363       !LHS.get()->EvaluateAsInt(Left, S.Context))
9364     return;
9365 
9366   // If LHS does not have a signed type and non-negative value
9367   // then, the behavior is undefined. Warn about it.
9368   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9369     S.DiagRuntimeBehavior(Loc, LHS.get(),
9370                           S.PDiag(diag::warn_shift_lhs_negative)
9371                             << LHS.get()->getSourceRange());
9372     return;
9373   }
9374 
9375   llvm::APInt ResultBits =
9376       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9377   if (LeftBits.uge(ResultBits))
9378     return;
9379   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9380   Result = Result.shl(Right);
9381 
9382   // Print the bit representation of the signed integer as an unsigned
9383   // hexadecimal number.
9384   SmallString<40> HexResult;
9385   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9386 
9387   // If we are only missing a sign bit, this is less likely to result in actual
9388   // bugs -- if the result is cast back to an unsigned type, it will have the
9389   // expected value. Thus we place this behind a different warning that can be
9390   // turned off separately if needed.
9391   if (LeftBits == ResultBits - 1) {
9392     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9393         << HexResult << LHSType
9394         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9395     return;
9396   }
9397 
9398   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9399     << HexResult.str() << Result.getMinSignedBits() << LHSType
9400     << Left.getBitWidth() << LHS.get()->getSourceRange()
9401     << RHS.get()->getSourceRange();
9402 }
9403 
9404 /// Return the resulting type when a vector is shifted
9405 ///        by a scalar or vector shift amount.
9406 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9407                                  SourceLocation Loc, bool IsCompAssign) {
9408   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9409   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9410       !LHS.get()->getType()->isVectorType()) {
9411     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9412       << RHS.get()->getType() << LHS.get()->getType()
9413       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9414     return QualType();
9415   }
9416 
9417   if (!IsCompAssign) {
9418     LHS = S.UsualUnaryConversions(LHS.get());
9419     if (LHS.isInvalid()) return QualType();
9420   }
9421 
9422   RHS = S.UsualUnaryConversions(RHS.get());
9423   if (RHS.isInvalid()) return QualType();
9424 
9425   QualType LHSType = LHS.get()->getType();
9426   // Note that LHS might be a scalar because the routine calls not only in
9427   // OpenCL case.
9428   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9429   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9430 
9431   // Note that RHS might not be a vector.
9432   QualType RHSType = RHS.get()->getType();
9433   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9434   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9435 
9436   // The operands need to be integers.
9437   if (!LHSEleType->isIntegerType()) {
9438     S.Diag(Loc, diag::err_typecheck_expect_int)
9439       << LHS.get()->getType() << LHS.get()->getSourceRange();
9440     return QualType();
9441   }
9442 
9443   if (!RHSEleType->isIntegerType()) {
9444     S.Diag(Loc, diag::err_typecheck_expect_int)
9445       << RHS.get()->getType() << RHS.get()->getSourceRange();
9446     return QualType();
9447   }
9448 
9449   if (!LHSVecTy) {
9450     assert(RHSVecTy);
9451     if (IsCompAssign)
9452       return RHSType;
9453     if (LHSEleType != RHSEleType) {
9454       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9455       LHSEleType = RHSEleType;
9456     }
9457     QualType VecTy =
9458         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9459     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9460     LHSType = VecTy;
9461   } else if (RHSVecTy) {
9462     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9463     // are applied component-wise. So if RHS is a vector, then ensure
9464     // that the number of elements is the same as LHS...
9465     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9466       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9467         << LHS.get()->getType() << RHS.get()->getType()
9468         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9469       return QualType();
9470     }
9471     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9472       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9473       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9474       if (LHSBT != RHSBT &&
9475           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9476         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9477             << LHS.get()->getType() << RHS.get()->getType()
9478             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9479       }
9480     }
9481   } else {
9482     // ...else expand RHS to match the number of elements in LHS.
9483     QualType VecTy =
9484       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9485     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9486   }
9487 
9488   return LHSType;
9489 }
9490 
9491 // C99 6.5.7
9492 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9493                                   SourceLocation Loc, BinaryOperatorKind Opc,
9494                                   bool IsCompAssign) {
9495   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9496 
9497   // Vector shifts promote their scalar inputs to vector type.
9498   if (LHS.get()->getType()->isVectorType() ||
9499       RHS.get()->getType()->isVectorType()) {
9500     if (LangOpts.ZVector) {
9501       // The shift operators for the z vector extensions work basically
9502       // like general shifts, except that neither the LHS nor the RHS is
9503       // allowed to be a "vector bool".
9504       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9505         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9506           return InvalidOperands(Loc, LHS, RHS);
9507       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9508         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9509           return InvalidOperands(Loc, LHS, RHS);
9510     }
9511     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9512   }
9513 
9514   // Shifts don't perform usual arithmetic conversions, they just do integer
9515   // promotions on each operand. C99 6.5.7p3
9516 
9517   // For the LHS, do usual unary conversions, but then reset them away
9518   // if this is a compound assignment.
9519   ExprResult OldLHS = LHS;
9520   LHS = UsualUnaryConversions(LHS.get());
9521   if (LHS.isInvalid())
9522     return QualType();
9523   QualType LHSType = LHS.get()->getType();
9524   if (IsCompAssign) LHS = OldLHS;
9525 
9526   // The RHS is simpler.
9527   RHS = UsualUnaryConversions(RHS.get());
9528   if (RHS.isInvalid())
9529     return QualType();
9530   QualType RHSType = RHS.get()->getType();
9531 
9532   // C99 6.5.7p2: Each of the operands shall have integer type.
9533   if (!LHSType->hasIntegerRepresentation() ||
9534       !RHSType->hasIntegerRepresentation())
9535     return InvalidOperands(Loc, LHS, RHS);
9536 
9537   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9538   // hasIntegerRepresentation() above instead of this.
9539   if (isScopedEnumerationType(LHSType) ||
9540       isScopedEnumerationType(RHSType)) {
9541     return InvalidOperands(Loc, LHS, RHS);
9542   }
9543   // Sanity-check shift operands
9544   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9545 
9546   // "The type of the result is that of the promoted left operand."
9547   return LHSType;
9548 }
9549 
9550 /// If two different enums are compared, raise a warning.
9551 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9552                                 Expr *RHS) {
9553   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9554   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9555 
9556   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9557   if (!LHSEnumType)
9558     return;
9559   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9560   if (!RHSEnumType)
9561     return;
9562 
9563   // Ignore anonymous enums.
9564   if (!LHSEnumType->getDecl()->getIdentifier() &&
9565       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9566     return;
9567   if (!RHSEnumType->getDecl()->getIdentifier() &&
9568       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9569     return;
9570 
9571   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9572     return;
9573 
9574   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9575       << LHSStrippedType << RHSStrippedType
9576       << LHS->getSourceRange() << RHS->getSourceRange();
9577 }
9578 
9579 /// Diagnose bad pointer comparisons.
9580 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9581                                               ExprResult &LHS, ExprResult &RHS,
9582                                               bool IsError) {
9583   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9584                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9585     << LHS.get()->getType() << RHS.get()->getType()
9586     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9587 }
9588 
9589 /// Returns false if the pointers are converted to a composite type,
9590 /// true otherwise.
9591 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9592                                            ExprResult &LHS, ExprResult &RHS) {
9593   // C++ [expr.rel]p2:
9594   //   [...] Pointer conversions (4.10) and qualification
9595   //   conversions (4.4) are performed on pointer operands (or on
9596   //   a pointer operand and a null pointer constant) to bring
9597   //   them to their composite pointer type. [...]
9598   //
9599   // C++ [expr.eq]p1 uses the same notion for (in)equality
9600   // comparisons of pointers.
9601 
9602   QualType LHSType = LHS.get()->getType();
9603   QualType RHSType = RHS.get()->getType();
9604   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9605          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9606 
9607   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9608   if (T.isNull()) {
9609     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9610         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9611       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9612     else
9613       S.InvalidOperands(Loc, LHS, RHS);
9614     return true;
9615   }
9616 
9617   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9618   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9619   return false;
9620 }
9621 
9622 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9623                                                     ExprResult &LHS,
9624                                                     ExprResult &RHS,
9625                                                     bool IsError) {
9626   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9627                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9628     << LHS.get()->getType() << RHS.get()->getType()
9629     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9630 }
9631 
9632 static bool isObjCObjectLiteral(ExprResult &E) {
9633   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9634   case Stmt::ObjCArrayLiteralClass:
9635   case Stmt::ObjCDictionaryLiteralClass:
9636   case Stmt::ObjCStringLiteralClass:
9637   case Stmt::ObjCBoxedExprClass:
9638     return true;
9639   default:
9640     // Note that ObjCBoolLiteral is NOT an object literal!
9641     return false;
9642   }
9643 }
9644 
9645 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9646   const ObjCObjectPointerType *Type =
9647     LHS->getType()->getAs<ObjCObjectPointerType>();
9648 
9649   // If this is not actually an Objective-C object, bail out.
9650   if (!Type)
9651     return false;
9652 
9653   // Get the LHS object's interface type.
9654   QualType InterfaceType = Type->getPointeeType();
9655 
9656   // If the RHS isn't an Objective-C object, bail out.
9657   if (!RHS->getType()->isObjCObjectPointerType())
9658     return false;
9659 
9660   // Try to find the -isEqual: method.
9661   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9662   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9663                                                       InterfaceType,
9664                                                       /*instance=*/true);
9665   if (!Method) {
9666     if (Type->isObjCIdType()) {
9667       // For 'id', just check the global pool.
9668       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9669                                                   /*receiverId=*/true);
9670     } else {
9671       // Check protocols.
9672       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9673                                              /*instance=*/true);
9674     }
9675   }
9676 
9677   if (!Method)
9678     return false;
9679 
9680   QualType T = Method->parameters()[0]->getType();
9681   if (!T->isObjCObjectPointerType())
9682     return false;
9683 
9684   QualType R = Method->getReturnType();
9685   if (!R->isScalarType())
9686     return false;
9687 
9688   return true;
9689 }
9690 
9691 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9692   FromE = FromE->IgnoreParenImpCasts();
9693   switch (FromE->getStmtClass()) {
9694     default:
9695       break;
9696     case Stmt::ObjCStringLiteralClass:
9697       // "string literal"
9698       return LK_String;
9699     case Stmt::ObjCArrayLiteralClass:
9700       // "array literal"
9701       return LK_Array;
9702     case Stmt::ObjCDictionaryLiteralClass:
9703       // "dictionary literal"
9704       return LK_Dictionary;
9705     case Stmt::BlockExprClass:
9706       return LK_Block;
9707     case Stmt::ObjCBoxedExprClass: {
9708       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9709       switch (Inner->getStmtClass()) {
9710         case Stmt::IntegerLiteralClass:
9711         case Stmt::FloatingLiteralClass:
9712         case Stmt::CharacterLiteralClass:
9713         case Stmt::ObjCBoolLiteralExprClass:
9714         case Stmt::CXXBoolLiteralExprClass:
9715           // "numeric literal"
9716           return LK_Numeric;
9717         case Stmt::ImplicitCastExprClass: {
9718           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9719           // Boolean literals can be represented by implicit casts.
9720           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9721             return LK_Numeric;
9722           break;
9723         }
9724         default:
9725           break;
9726       }
9727       return LK_Boxed;
9728     }
9729   }
9730   return LK_None;
9731 }
9732 
9733 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9734                                           ExprResult &LHS, ExprResult &RHS,
9735                                           BinaryOperator::Opcode Opc){
9736   Expr *Literal;
9737   Expr *Other;
9738   if (isObjCObjectLiteral(LHS)) {
9739     Literal = LHS.get();
9740     Other = RHS.get();
9741   } else {
9742     Literal = RHS.get();
9743     Other = LHS.get();
9744   }
9745 
9746   // Don't warn on comparisons against nil.
9747   Other = Other->IgnoreParenCasts();
9748   if (Other->isNullPointerConstant(S.getASTContext(),
9749                                    Expr::NPC_ValueDependentIsNotNull))
9750     return;
9751 
9752   // This should be kept in sync with warn_objc_literal_comparison.
9753   // LK_String should always be after the other literals, since it has its own
9754   // warning flag.
9755   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9756   assert(LiteralKind != Sema::LK_Block);
9757   if (LiteralKind == Sema::LK_None) {
9758     llvm_unreachable("Unknown Objective-C object literal kind");
9759   }
9760 
9761   if (LiteralKind == Sema::LK_String)
9762     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9763       << Literal->getSourceRange();
9764   else
9765     S.Diag(Loc, diag::warn_objc_literal_comparison)
9766       << LiteralKind << Literal->getSourceRange();
9767 
9768   if (BinaryOperator::isEqualityOp(Opc) &&
9769       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9770     SourceLocation Start = LHS.get()->getBeginLoc();
9771     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
9772     CharSourceRange OpRange =
9773       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9774 
9775     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9776       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9777       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9778       << FixItHint::CreateInsertion(End, "]");
9779   }
9780 }
9781 
9782 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9783 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9784                                            ExprResult &RHS, SourceLocation Loc,
9785                                            BinaryOperatorKind Opc) {
9786   // Check that left hand side is !something.
9787   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9788   if (!UO || UO->getOpcode() != UO_LNot) return;
9789 
9790   // Only check if the right hand side is non-bool arithmetic type.
9791   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9792 
9793   // Make sure that the something in !something is not bool.
9794   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9795   if (SubExpr->isKnownToHaveBooleanValue()) return;
9796 
9797   // Emit warning.
9798   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9799   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9800       << Loc << IsBitwiseOp;
9801 
9802   // First note suggest !(x < y)
9803   SourceLocation FirstOpen = SubExpr->getBeginLoc();
9804   SourceLocation FirstClose = RHS.get()->getEndLoc();
9805   FirstClose = S.getLocForEndOfToken(FirstClose);
9806   if (FirstClose.isInvalid())
9807     FirstOpen = SourceLocation();
9808   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9809       << IsBitwiseOp
9810       << FixItHint::CreateInsertion(FirstOpen, "(")
9811       << FixItHint::CreateInsertion(FirstClose, ")");
9812 
9813   // Second note suggests (!x) < y
9814   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
9815   SourceLocation SecondClose = LHS.get()->getEndLoc();
9816   SecondClose = S.getLocForEndOfToken(SecondClose);
9817   if (SecondClose.isInvalid())
9818     SecondOpen = SourceLocation();
9819   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9820       << FixItHint::CreateInsertion(SecondOpen, "(")
9821       << FixItHint::CreateInsertion(SecondClose, ")");
9822 }
9823 
9824 // Get the decl for a simple expression: a reference to a variable,
9825 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9826 static ValueDecl *getCompareDecl(Expr *E) {
9827   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9828     return DR->getDecl();
9829   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9830     if (Ivar->isFreeIvar())
9831       return Ivar->getDecl();
9832   }
9833   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9834     if (Mem->isImplicitAccess())
9835       return Mem->getMemberDecl();
9836   }
9837   return nullptr;
9838 }
9839 
9840 /// Diagnose some forms of syntactically-obvious tautological comparison.
9841 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9842                                            Expr *LHS, Expr *RHS,
9843                                            BinaryOperatorKind Opc) {
9844   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9845   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9846 
9847   QualType LHSType = LHS->getType();
9848   QualType RHSType = RHS->getType();
9849   if (LHSType->hasFloatingRepresentation() ||
9850       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9851       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
9852       S.inTemplateInstantiation())
9853     return;
9854 
9855   // Comparisons between two array types are ill-formed for operator<=>, so
9856   // we shouldn't emit any additional warnings about it.
9857   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9858     return;
9859 
9860   // For non-floating point types, check for self-comparisons of the form
9861   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9862   // often indicate logic errors in the program.
9863   //
9864   // NOTE: Don't warn about comparison expressions resulting from macro
9865   // expansion. Also don't warn about comparisons which are only self
9866   // comparisons within a template instantiation. The warnings should catch
9867   // obvious cases in the definition of the template anyways. The idea is to
9868   // warn when the typed comparison operator will always evaluate to the same
9869   // result.
9870   ValueDecl *DL = getCompareDecl(LHSStripped);
9871   ValueDecl *DR = getCompareDecl(RHSStripped);
9872   if (DL && DR && declaresSameEntity(DL, DR)) {
9873     StringRef Result;
9874     switch (Opc) {
9875     case BO_EQ: case BO_LE: case BO_GE:
9876       Result = "true";
9877       break;
9878     case BO_NE: case BO_LT: case BO_GT:
9879       Result = "false";
9880       break;
9881     case BO_Cmp:
9882       Result = "'std::strong_ordering::equal'";
9883       break;
9884     default:
9885       break;
9886     }
9887     S.DiagRuntimeBehavior(Loc, nullptr,
9888                           S.PDiag(diag::warn_comparison_always)
9889                               << 0 /*self-comparison*/ << !Result.empty()
9890                               << Result);
9891   } else if (DL && DR &&
9892              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9893              !DL->isWeak() && !DR->isWeak()) {
9894     // What is it always going to evaluate to?
9895     StringRef Result;
9896     switch(Opc) {
9897     case BO_EQ: // e.g. array1 == array2
9898       Result = "false";
9899       break;
9900     case BO_NE: // e.g. array1 != array2
9901       Result = "true";
9902       break;
9903     default: // e.g. array1 <= array2
9904       // The best we can say is 'a constant'
9905       break;
9906     }
9907     S.DiagRuntimeBehavior(Loc, nullptr,
9908                           S.PDiag(diag::warn_comparison_always)
9909                               << 1 /*array comparison*/
9910                               << !Result.empty() << Result);
9911   }
9912 
9913   if (isa<CastExpr>(LHSStripped))
9914     LHSStripped = LHSStripped->IgnoreParenCasts();
9915   if (isa<CastExpr>(RHSStripped))
9916     RHSStripped = RHSStripped->IgnoreParenCasts();
9917 
9918   // Warn about comparisons against a string constant (unless the other
9919   // operand is null); the user probably wants strcmp.
9920   Expr *LiteralString = nullptr;
9921   Expr *LiteralStringStripped = nullptr;
9922   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9923       !RHSStripped->isNullPointerConstant(S.Context,
9924                                           Expr::NPC_ValueDependentIsNull)) {
9925     LiteralString = LHS;
9926     LiteralStringStripped = LHSStripped;
9927   } else if ((isa<StringLiteral>(RHSStripped) ||
9928               isa<ObjCEncodeExpr>(RHSStripped)) &&
9929              !LHSStripped->isNullPointerConstant(S.Context,
9930                                           Expr::NPC_ValueDependentIsNull)) {
9931     LiteralString = RHS;
9932     LiteralStringStripped = RHSStripped;
9933   }
9934 
9935   if (LiteralString) {
9936     S.DiagRuntimeBehavior(Loc, nullptr,
9937                           S.PDiag(diag::warn_stringcompare)
9938                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9939                               << LiteralString->getSourceRange());
9940   }
9941 }
9942 
9943 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9944   switch (CK) {
9945   default: {
9946 #ifndef NDEBUG
9947     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9948                  << "\n";
9949 #endif
9950     llvm_unreachable("unhandled cast kind");
9951   }
9952   case CK_UserDefinedConversion:
9953     return ICK_Identity;
9954   case CK_LValueToRValue:
9955     return ICK_Lvalue_To_Rvalue;
9956   case CK_ArrayToPointerDecay:
9957     return ICK_Array_To_Pointer;
9958   case CK_FunctionToPointerDecay:
9959     return ICK_Function_To_Pointer;
9960   case CK_IntegralCast:
9961     return ICK_Integral_Conversion;
9962   case CK_FloatingCast:
9963     return ICK_Floating_Conversion;
9964   case CK_IntegralToFloating:
9965   case CK_FloatingToIntegral:
9966     return ICK_Floating_Integral;
9967   case CK_IntegralComplexCast:
9968   case CK_FloatingComplexCast:
9969   case CK_FloatingComplexToIntegralComplex:
9970   case CK_IntegralComplexToFloatingComplex:
9971     return ICK_Complex_Conversion;
9972   case CK_FloatingComplexToReal:
9973   case CK_FloatingRealToComplex:
9974   case CK_IntegralComplexToReal:
9975   case CK_IntegralRealToComplex:
9976     return ICK_Complex_Real;
9977   }
9978 }
9979 
9980 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9981                                              QualType FromType,
9982                                              SourceLocation Loc) {
9983   // Check for a narrowing implicit conversion.
9984   StandardConversionSequence SCS;
9985   SCS.setAsIdentityConversion();
9986   SCS.setToType(0, FromType);
9987   SCS.setToType(1, ToType);
9988   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9989     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9990 
9991   APValue PreNarrowingValue;
9992   QualType PreNarrowingType;
9993   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9994                                PreNarrowingType,
9995                                /*IgnoreFloatToIntegralConversion*/ true)) {
9996   case NK_Dependent_Narrowing:
9997     // Implicit conversion to a narrower type, but the expression is
9998     // value-dependent so we can't tell whether it's actually narrowing.
9999   case NK_Not_Narrowing:
10000     return false;
10001 
10002   case NK_Constant_Narrowing:
10003     // Implicit conversion to a narrower type, and the value is not a constant
10004     // expression.
10005     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10006         << /*Constant*/ 1
10007         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10008     return true;
10009 
10010   case NK_Variable_Narrowing:
10011     // Implicit conversion to a narrower type, and the value is not a constant
10012     // expression.
10013   case NK_Type_Narrowing:
10014     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10015         << /*Constant*/ 0 << FromType << ToType;
10016     // TODO: It's not a constant expression, but what if the user intended it
10017     // to be? Can we produce notes to help them figure out why it isn't?
10018     return true;
10019   }
10020   llvm_unreachable("unhandled case in switch");
10021 }
10022 
10023 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10024                                                          ExprResult &LHS,
10025                                                          ExprResult &RHS,
10026                                                          SourceLocation Loc) {
10027   using CCT = ComparisonCategoryType;
10028 
10029   QualType LHSType = LHS.get()->getType();
10030   QualType RHSType = RHS.get()->getType();
10031   // Dig out the original argument type and expression before implicit casts
10032   // were applied. These are the types/expressions we need to check the
10033   // [expr.spaceship] requirements against.
10034   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10035   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10036   QualType LHSStrippedType = LHSStripped.get()->getType();
10037   QualType RHSStrippedType = RHSStripped.get()->getType();
10038 
10039   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10040   // other is not, the program is ill-formed.
10041   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10042     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10043     return QualType();
10044   }
10045 
10046   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10047                     RHSStrippedType->isEnumeralType();
10048   if (NumEnumArgs == 1) {
10049     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10050     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10051     if (OtherTy->hasFloatingRepresentation()) {
10052       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10053       return QualType();
10054     }
10055   }
10056   if (NumEnumArgs == 2) {
10057     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10058     // type E, the operator yields the result of converting the operands
10059     // to the underlying type of E and applying <=> to the converted operands.
10060     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10061       S.InvalidOperands(Loc, LHS, RHS);
10062       return QualType();
10063     }
10064     QualType IntType =
10065         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10066     assert(IntType->isArithmeticType());
10067 
10068     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10069     // promote the boolean type, and all other promotable integer types, to
10070     // avoid this.
10071     if (IntType->isPromotableIntegerType())
10072       IntType = S.Context.getPromotedIntegerType(IntType);
10073 
10074     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10075     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10076     LHSType = RHSType = IntType;
10077   }
10078 
10079   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10080   // usual arithmetic conversions are applied to the operands.
10081   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10082   if (LHS.isInvalid() || RHS.isInvalid())
10083     return QualType();
10084   if (Type.isNull())
10085     return S.InvalidOperands(Loc, LHS, RHS);
10086   assert(Type->isArithmeticType() || Type->isEnumeralType());
10087 
10088   bool HasNarrowing = checkThreeWayNarrowingConversion(
10089       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10090   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10091                                                    RHS.get()->getBeginLoc());
10092   if (HasNarrowing)
10093     return QualType();
10094 
10095   assert(!Type.isNull() && "composite type for <=> has not been set");
10096 
10097   auto TypeKind = [&]() {
10098     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10099       if (CT->getElementType()->hasFloatingRepresentation())
10100         return CCT::WeakEquality;
10101       return CCT::StrongEquality;
10102     }
10103     if (Type->isIntegralOrEnumerationType())
10104       return CCT::StrongOrdering;
10105     if (Type->hasFloatingRepresentation())
10106       return CCT::PartialOrdering;
10107     llvm_unreachable("other types are unimplemented");
10108   }();
10109 
10110   return S.CheckComparisonCategoryType(TypeKind, Loc);
10111 }
10112 
10113 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10114                                                  ExprResult &RHS,
10115                                                  SourceLocation Loc,
10116                                                  BinaryOperatorKind Opc) {
10117   if (Opc == BO_Cmp)
10118     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10119 
10120   // C99 6.5.8p3 / C99 6.5.9p4
10121   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10122   if (LHS.isInvalid() || RHS.isInvalid())
10123     return QualType();
10124   if (Type.isNull())
10125     return S.InvalidOperands(Loc, LHS, RHS);
10126   assert(Type->isArithmeticType() || Type->isEnumeralType());
10127 
10128   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10129 
10130   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10131     return S.InvalidOperands(Loc, LHS, RHS);
10132 
10133   // Check for comparisons of floating point operands using != and ==.
10134   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10135     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10136 
10137   // The result of comparisons is 'bool' in C++, 'int' in C.
10138   return S.Context.getLogicalOperationType();
10139 }
10140 
10141 // C99 6.5.8, C++ [expr.rel]
10142 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10143                                     SourceLocation Loc,
10144                                     BinaryOperatorKind Opc) {
10145   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10146   bool IsThreeWay = Opc == BO_Cmp;
10147   auto IsAnyPointerType = [](ExprResult E) {
10148     QualType Ty = E.get()->getType();
10149     return Ty->isPointerType() || Ty->isMemberPointerType();
10150   };
10151 
10152   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10153   // type, array-to-pointer, ..., conversions are performed on both operands to
10154   // bring them to their composite type.
10155   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10156   // any type-related checks.
10157   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10158     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10159     if (LHS.isInvalid())
10160       return QualType();
10161     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10162     if (RHS.isInvalid())
10163       return QualType();
10164   } else {
10165     LHS = DefaultLvalueConversion(LHS.get());
10166     if (LHS.isInvalid())
10167       return QualType();
10168     RHS = DefaultLvalueConversion(RHS.get());
10169     if (RHS.isInvalid())
10170       return QualType();
10171   }
10172 
10173   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10174 
10175   // Handle vector comparisons separately.
10176   if (LHS.get()->getType()->isVectorType() ||
10177       RHS.get()->getType()->isVectorType())
10178     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10179 
10180   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10181   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10182 
10183   QualType LHSType = LHS.get()->getType();
10184   QualType RHSType = RHS.get()->getType();
10185   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10186       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10187     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10188 
10189   const Expr::NullPointerConstantKind LHSNullKind =
10190       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10191   const Expr::NullPointerConstantKind RHSNullKind =
10192       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10193   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10194   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10195 
10196   auto computeResultTy = [&]() {
10197     if (Opc != BO_Cmp)
10198       return Context.getLogicalOperationType();
10199     assert(getLangOpts().CPlusPlus);
10200     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10201 
10202     QualType CompositeTy = LHS.get()->getType();
10203     assert(!CompositeTy->isReferenceType());
10204 
10205     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10206       return CheckComparisonCategoryType(Kind, Loc);
10207     };
10208 
10209     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10210     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10211     // result is of type std::strong_equality
10212     if (CompositeTy->isFunctionPointerType() ||
10213         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10214       // FIXME: consider making the function pointer case produce
10215       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10216       // and direction polls
10217       return buildResultTy(ComparisonCategoryType::StrongEquality);
10218 
10219     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10220     // pointer type, p <=> q is of type std::strong_ordering.
10221     if (CompositeTy->isPointerType()) {
10222       // P0946R0: Comparisons between a null pointer constant and an object
10223       // pointer result in std::strong_equality
10224       if (LHSIsNull != RHSIsNull)
10225         return buildResultTy(ComparisonCategoryType::StrongEquality);
10226       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10227     }
10228     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10229     // TODO: Extend support for operator<=> to ObjC types.
10230     return InvalidOperands(Loc, LHS, RHS);
10231   };
10232 
10233 
10234   if (!IsRelational && LHSIsNull != RHSIsNull) {
10235     bool IsEquality = Opc == BO_EQ;
10236     if (RHSIsNull)
10237       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10238                                    RHS.get()->getSourceRange());
10239     else
10240       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10241                                    LHS.get()->getSourceRange());
10242   }
10243 
10244   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10245       (RHSType->isIntegerType() && !RHSIsNull)) {
10246     // Skip normal pointer conversion checks in this case; we have better
10247     // diagnostics for this below.
10248   } else if (getLangOpts().CPlusPlus) {
10249     // Equality comparison of a function pointer to a void pointer is invalid,
10250     // but we allow it as an extension.
10251     // FIXME: If we really want to allow this, should it be part of composite
10252     // pointer type computation so it works in conditionals too?
10253     if (!IsRelational &&
10254         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10255          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10256       // This is a gcc extension compatibility comparison.
10257       // In a SFINAE context, we treat this as a hard error to maintain
10258       // conformance with the C++ standard.
10259       diagnoseFunctionPointerToVoidComparison(
10260           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10261 
10262       if (isSFINAEContext())
10263         return QualType();
10264 
10265       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10266       return computeResultTy();
10267     }
10268 
10269     // C++ [expr.eq]p2:
10270     //   If at least one operand is a pointer [...] bring them to their
10271     //   composite pointer type.
10272     // C++ [expr.spaceship]p6
10273     //  If at least one of the operands is of pointer type, [...] bring them
10274     //  to their composite pointer type.
10275     // C++ [expr.rel]p2:
10276     //   If both operands are pointers, [...] bring them to their composite
10277     //   pointer type.
10278     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10279             (IsRelational ? 2 : 1) &&
10280         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10281                                          RHSType->isObjCObjectPointerType()))) {
10282       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10283         return QualType();
10284       return computeResultTy();
10285     }
10286   } else if (LHSType->isPointerType() &&
10287              RHSType->isPointerType()) { // C99 6.5.8p2
10288     // All of the following pointer-related warnings are GCC extensions, except
10289     // when handling null pointer constants.
10290     QualType LCanPointeeTy =
10291       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10292     QualType RCanPointeeTy =
10293       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10294 
10295     // C99 6.5.9p2 and C99 6.5.8p2
10296     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10297                                    RCanPointeeTy.getUnqualifiedType())) {
10298       // Valid unless a relational comparison of function pointers
10299       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10300         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10301           << LHSType << RHSType << LHS.get()->getSourceRange()
10302           << RHS.get()->getSourceRange();
10303       }
10304     } else if (!IsRelational &&
10305                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10306       // Valid unless comparison between non-null pointer and function pointer
10307       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10308           && !LHSIsNull && !RHSIsNull)
10309         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10310                                                 /*isError*/false);
10311     } else {
10312       // Invalid
10313       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10314     }
10315     if (LCanPointeeTy != RCanPointeeTy) {
10316       // Treat NULL constant as a special case in OpenCL.
10317       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10318         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10319         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10320           Diag(Loc,
10321                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10322               << LHSType << RHSType << 0 /* comparison */
10323               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10324         }
10325       }
10326       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10327       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10328       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10329                                                : CK_BitCast;
10330       if (LHSIsNull && !RHSIsNull)
10331         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10332       else
10333         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10334     }
10335     return computeResultTy();
10336   }
10337 
10338   if (getLangOpts().CPlusPlus) {
10339     // C++ [expr.eq]p4:
10340     //   Two operands of type std::nullptr_t or one operand of type
10341     //   std::nullptr_t and the other a null pointer constant compare equal.
10342     if (!IsRelational && LHSIsNull && RHSIsNull) {
10343       if (LHSType->isNullPtrType()) {
10344         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10345         return computeResultTy();
10346       }
10347       if (RHSType->isNullPtrType()) {
10348         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10349         return computeResultTy();
10350       }
10351     }
10352 
10353     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10354     // These aren't covered by the composite pointer type rules.
10355     if (!IsRelational && RHSType->isNullPtrType() &&
10356         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10357       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10358       return computeResultTy();
10359     }
10360     if (!IsRelational && LHSType->isNullPtrType() &&
10361         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10362       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10363       return computeResultTy();
10364     }
10365 
10366     if (IsRelational &&
10367         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10368          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10369       // HACK: Relational comparison of nullptr_t against a pointer type is
10370       // invalid per DR583, but we allow it within std::less<> and friends,
10371       // since otherwise common uses of it break.
10372       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10373       // friends to have std::nullptr_t overload candidates.
10374       DeclContext *DC = CurContext;
10375       if (isa<FunctionDecl>(DC))
10376         DC = DC->getParent();
10377       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10378         if (CTSD->isInStdNamespace() &&
10379             llvm::StringSwitch<bool>(CTSD->getName())
10380                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10381                 .Default(false)) {
10382           if (RHSType->isNullPtrType())
10383             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10384           else
10385             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10386           return computeResultTy();
10387         }
10388       }
10389     }
10390 
10391     // C++ [expr.eq]p2:
10392     //   If at least one operand is a pointer to member, [...] bring them to
10393     //   their composite pointer type.
10394     if (!IsRelational &&
10395         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10396       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10397         return QualType();
10398       else
10399         return computeResultTy();
10400     }
10401   }
10402 
10403   // Handle block pointer types.
10404   if (!IsRelational && LHSType->isBlockPointerType() &&
10405       RHSType->isBlockPointerType()) {
10406     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10407     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10408 
10409     if (!LHSIsNull && !RHSIsNull &&
10410         !Context.typesAreCompatible(lpointee, rpointee)) {
10411       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10412         << LHSType << RHSType << LHS.get()->getSourceRange()
10413         << RHS.get()->getSourceRange();
10414     }
10415     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10416     return computeResultTy();
10417   }
10418 
10419   // Allow block pointers to be compared with null pointer constants.
10420   if (!IsRelational
10421       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10422           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10423     if (!LHSIsNull && !RHSIsNull) {
10424       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10425              ->getPointeeType()->isVoidType())
10426             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10427                 ->getPointeeType()->isVoidType())))
10428         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10429           << LHSType << RHSType << LHS.get()->getSourceRange()
10430           << RHS.get()->getSourceRange();
10431     }
10432     if (LHSIsNull && !RHSIsNull)
10433       LHS = ImpCastExprToType(LHS.get(), RHSType,
10434                               RHSType->isPointerType() ? CK_BitCast
10435                                 : CK_AnyPointerToBlockPointerCast);
10436     else
10437       RHS = ImpCastExprToType(RHS.get(), LHSType,
10438                               LHSType->isPointerType() ? CK_BitCast
10439                                 : CK_AnyPointerToBlockPointerCast);
10440     return computeResultTy();
10441   }
10442 
10443   if (LHSType->isObjCObjectPointerType() ||
10444       RHSType->isObjCObjectPointerType()) {
10445     const PointerType *LPT = LHSType->getAs<PointerType>();
10446     const PointerType *RPT = RHSType->getAs<PointerType>();
10447     if (LPT || RPT) {
10448       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10449       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10450 
10451       if (!LPtrToVoid && !RPtrToVoid &&
10452           !Context.typesAreCompatible(LHSType, RHSType)) {
10453         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10454                                           /*isError*/false);
10455       }
10456       if (LHSIsNull && !RHSIsNull) {
10457         Expr *E = LHS.get();
10458         if (getLangOpts().ObjCAutoRefCount)
10459           CheckObjCConversion(SourceRange(), RHSType, E,
10460                               CCK_ImplicitConversion);
10461         LHS = ImpCastExprToType(E, RHSType,
10462                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10463       }
10464       else {
10465         Expr *E = RHS.get();
10466         if (getLangOpts().ObjCAutoRefCount)
10467           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10468                               /*Diagnose=*/true,
10469                               /*DiagnoseCFAudited=*/false, Opc);
10470         RHS = ImpCastExprToType(E, LHSType,
10471                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10472       }
10473       return computeResultTy();
10474     }
10475     if (LHSType->isObjCObjectPointerType() &&
10476         RHSType->isObjCObjectPointerType()) {
10477       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10478         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10479                                           /*isError*/false);
10480       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10481         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10482 
10483       if (LHSIsNull && !RHSIsNull)
10484         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10485       else
10486         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10487       return computeResultTy();
10488     }
10489 
10490     if (!IsRelational && LHSType->isBlockPointerType() &&
10491         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10492       LHS = ImpCastExprToType(LHS.get(), RHSType,
10493                               CK_BlockPointerToObjCPointerCast);
10494       return computeResultTy();
10495     } else if (!IsRelational &&
10496                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10497                RHSType->isBlockPointerType()) {
10498       RHS = ImpCastExprToType(RHS.get(), LHSType,
10499                               CK_BlockPointerToObjCPointerCast);
10500       return computeResultTy();
10501     }
10502   }
10503   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10504       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10505     unsigned DiagID = 0;
10506     bool isError = false;
10507     if (LangOpts.DebuggerSupport) {
10508       // Under a debugger, allow the comparison of pointers to integers,
10509       // since users tend to want to compare addresses.
10510     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10511                (RHSIsNull && RHSType->isIntegerType())) {
10512       if (IsRelational) {
10513         isError = getLangOpts().CPlusPlus;
10514         DiagID =
10515           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10516                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10517       }
10518     } else if (getLangOpts().CPlusPlus) {
10519       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10520       isError = true;
10521     } else if (IsRelational)
10522       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10523     else
10524       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10525 
10526     if (DiagID) {
10527       Diag(Loc, DiagID)
10528         << LHSType << RHSType << LHS.get()->getSourceRange()
10529         << RHS.get()->getSourceRange();
10530       if (isError)
10531         return QualType();
10532     }
10533 
10534     if (LHSType->isIntegerType())
10535       LHS = ImpCastExprToType(LHS.get(), RHSType,
10536                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10537     else
10538       RHS = ImpCastExprToType(RHS.get(), LHSType,
10539                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10540     return computeResultTy();
10541   }
10542 
10543   // Handle block pointers.
10544   if (!IsRelational && RHSIsNull
10545       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10546     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10547     return computeResultTy();
10548   }
10549   if (!IsRelational && LHSIsNull
10550       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10551     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10552     return computeResultTy();
10553   }
10554 
10555   if (getLangOpts().OpenCLVersion >= 200) {
10556     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10557       return computeResultTy();
10558     }
10559 
10560     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10561       return computeResultTy();
10562     }
10563 
10564     if (LHSIsNull && RHSType->isQueueT()) {
10565       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10566       return computeResultTy();
10567     }
10568 
10569     if (LHSType->isQueueT() && RHSIsNull) {
10570       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10571       return computeResultTy();
10572     }
10573   }
10574 
10575   return InvalidOperands(Loc, LHS, RHS);
10576 }
10577 
10578 // Return a signed ext_vector_type that is of identical size and number of
10579 // elements. For floating point vectors, return an integer type of identical
10580 // size and number of elements. In the non ext_vector_type case, search from
10581 // the largest type to the smallest type to avoid cases where long long == long,
10582 // where long gets picked over long long.
10583 QualType Sema::GetSignedVectorType(QualType V) {
10584   const VectorType *VTy = V->getAs<VectorType>();
10585   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10586 
10587   if (isa<ExtVectorType>(VTy)) {
10588     if (TypeSize == Context.getTypeSize(Context.CharTy))
10589       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10590     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10591       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10592     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10593       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10594     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10595       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10596     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10597            "Unhandled vector element size in vector compare");
10598     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10599   }
10600 
10601   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10602     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10603                                  VectorType::GenericVector);
10604   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10605     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10606                                  VectorType::GenericVector);
10607   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10608     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10609                                  VectorType::GenericVector);
10610   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10611     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10612                                  VectorType::GenericVector);
10613   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10614          "Unhandled vector element size in vector compare");
10615   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10616                                VectorType::GenericVector);
10617 }
10618 
10619 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10620 /// operates on extended vector types.  Instead of producing an IntTy result,
10621 /// like a scalar comparison, a vector comparison produces a vector of integer
10622 /// types.
10623 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10624                                           SourceLocation Loc,
10625                                           BinaryOperatorKind Opc) {
10626   // Check to make sure we're operating on vectors of the same type and width,
10627   // Allowing one side to be a scalar of element type.
10628   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10629                               /*AllowBothBool*/true,
10630                               /*AllowBoolConversions*/getLangOpts().ZVector);
10631   if (vType.isNull())
10632     return vType;
10633 
10634   QualType LHSType = LHS.get()->getType();
10635 
10636   // If AltiVec, the comparison results in a numeric type, i.e.
10637   // bool for C++, int for C
10638   if (getLangOpts().AltiVec &&
10639       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10640     return Context.getLogicalOperationType();
10641 
10642   // For non-floating point types, check for self-comparisons of the form
10643   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10644   // often indicate logic errors in the program.
10645   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10646 
10647   // Check for comparisons of floating point operands using != and ==.
10648   if (BinaryOperator::isEqualityOp(Opc) &&
10649       LHSType->hasFloatingRepresentation()) {
10650     assert(RHS.get()->getType()->hasFloatingRepresentation());
10651     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10652   }
10653 
10654   // Return a signed type for the vector.
10655   return GetSignedVectorType(vType);
10656 }
10657 
10658 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10659                                           SourceLocation Loc) {
10660   // Ensure that either both operands are of the same vector type, or
10661   // one operand is of a vector type and the other is of its element type.
10662   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10663                                        /*AllowBothBool*/true,
10664                                        /*AllowBoolConversions*/false);
10665   if (vType.isNull())
10666     return InvalidOperands(Loc, LHS, RHS);
10667   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10668       vType->hasFloatingRepresentation())
10669     return InvalidOperands(Loc, LHS, RHS);
10670   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10671   //        usage of the logical operators && and || with vectors in C. This
10672   //        check could be notionally dropped.
10673   if (!getLangOpts().CPlusPlus &&
10674       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10675     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10676 
10677   return GetSignedVectorType(LHS.get()->getType());
10678 }
10679 
10680 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10681                                            SourceLocation Loc,
10682                                            BinaryOperatorKind Opc) {
10683   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10684 
10685   bool IsCompAssign =
10686       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10687 
10688   if (LHS.get()->getType()->isVectorType() ||
10689       RHS.get()->getType()->isVectorType()) {
10690     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10691         RHS.get()->getType()->hasIntegerRepresentation())
10692       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10693                         /*AllowBothBool*/true,
10694                         /*AllowBoolConversions*/getLangOpts().ZVector);
10695     return InvalidOperands(Loc, LHS, RHS);
10696   }
10697 
10698   if (Opc == BO_And)
10699     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10700 
10701   ExprResult LHSResult = LHS, RHSResult = RHS;
10702   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10703                                                  IsCompAssign);
10704   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10705     return QualType();
10706   LHS = LHSResult.get();
10707   RHS = RHSResult.get();
10708 
10709   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10710     return compType;
10711   return InvalidOperands(Loc, LHS, RHS);
10712 }
10713 
10714 // C99 6.5.[13,14]
10715 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10716                                            SourceLocation Loc,
10717                                            BinaryOperatorKind Opc) {
10718   // Check vector operands differently.
10719   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10720     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10721 
10722   // Diagnose cases where the user write a logical and/or but probably meant a
10723   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10724   // is a constant.
10725   if (LHS.get()->getType()->isIntegerType() &&
10726       !LHS.get()->getType()->isBooleanType() &&
10727       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10728       // Don't warn in macros or template instantiations.
10729       !Loc.isMacroID() && !inTemplateInstantiation()) {
10730     // If the RHS can be constant folded, and if it constant folds to something
10731     // that isn't 0 or 1 (which indicate a potential logical operation that
10732     // happened to fold to true/false) then warn.
10733     // Parens on the RHS are ignored.
10734     llvm::APSInt Result;
10735     if (RHS.get()->EvaluateAsInt(Result, Context))
10736       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10737            !RHS.get()->getExprLoc().isMacroID()) ||
10738           (Result != 0 && Result != 1)) {
10739         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10740           << RHS.get()->getSourceRange()
10741           << (Opc == BO_LAnd ? "&&" : "||");
10742         // Suggest replacing the logical operator with the bitwise version
10743         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10744             << (Opc == BO_LAnd ? "&" : "|")
10745             << FixItHint::CreateReplacement(SourceRange(
10746                                                  Loc, getLocForEndOfToken(Loc)),
10747                                             Opc == BO_LAnd ? "&" : "|");
10748         if (Opc == BO_LAnd)
10749           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10750           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10751               << FixItHint::CreateRemoval(
10752                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10753                                  RHS.get()->getEndLoc()));
10754       }
10755   }
10756 
10757   if (!Context.getLangOpts().CPlusPlus) {
10758     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10759     // not operate on the built-in scalar and vector float types.
10760     if (Context.getLangOpts().OpenCL &&
10761         Context.getLangOpts().OpenCLVersion < 120) {
10762       if (LHS.get()->getType()->isFloatingType() ||
10763           RHS.get()->getType()->isFloatingType())
10764         return InvalidOperands(Loc, LHS, RHS);
10765     }
10766 
10767     LHS = UsualUnaryConversions(LHS.get());
10768     if (LHS.isInvalid())
10769       return QualType();
10770 
10771     RHS = UsualUnaryConversions(RHS.get());
10772     if (RHS.isInvalid())
10773       return QualType();
10774 
10775     if (!LHS.get()->getType()->isScalarType() ||
10776         !RHS.get()->getType()->isScalarType())
10777       return InvalidOperands(Loc, LHS, RHS);
10778 
10779     return Context.IntTy;
10780   }
10781 
10782   // The following is safe because we only use this method for
10783   // non-overloadable operands.
10784 
10785   // C++ [expr.log.and]p1
10786   // C++ [expr.log.or]p1
10787   // The operands are both contextually converted to type bool.
10788   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10789   if (LHSRes.isInvalid())
10790     return InvalidOperands(Loc, LHS, RHS);
10791   LHS = LHSRes;
10792 
10793   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10794   if (RHSRes.isInvalid())
10795     return InvalidOperands(Loc, LHS, RHS);
10796   RHS = RHSRes;
10797 
10798   // C++ [expr.log.and]p2
10799   // C++ [expr.log.or]p2
10800   // The result is a bool.
10801   return Context.BoolTy;
10802 }
10803 
10804 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10805   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10806   if (!ME) return false;
10807   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10808   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10809       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10810   if (!Base) return false;
10811   return Base->getMethodDecl() != nullptr;
10812 }
10813 
10814 /// Is the given expression (which must be 'const') a reference to a
10815 /// variable which was originally non-const, but which has become
10816 /// 'const' due to being captured within a block?
10817 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10818 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10819   assert(E->isLValue() && E->getType().isConstQualified());
10820   E = E->IgnoreParens();
10821 
10822   // Must be a reference to a declaration from an enclosing scope.
10823   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10824   if (!DRE) return NCCK_None;
10825   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10826 
10827   // The declaration must be a variable which is not declared 'const'.
10828   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10829   if (!var) return NCCK_None;
10830   if (var->getType().isConstQualified()) return NCCK_None;
10831   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10832 
10833   // Decide whether the first capture was for a block or a lambda.
10834   DeclContext *DC = S.CurContext, *Prev = nullptr;
10835   // Decide whether the first capture was for a block or a lambda.
10836   while (DC) {
10837     // For init-capture, it is possible that the variable belongs to the
10838     // template pattern of the current context.
10839     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10840       if (var->isInitCapture() &&
10841           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10842         break;
10843     if (DC == var->getDeclContext())
10844       break;
10845     Prev = DC;
10846     DC = DC->getParent();
10847   }
10848   // Unless we have an init-capture, we've gone one step too far.
10849   if (!var->isInitCapture())
10850     DC = Prev;
10851   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10852 }
10853 
10854 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10855   Ty = Ty.getNonReferenceType();
10856   if (IsDereference && Ty->isPointerType())
10857     Ty = Ty->getPointeeType();
10858   return !Ty.isConstQualified();
10859 }
10860 
10861 // Update err_typecheck_assign_const and note_typecheck_assign_const
10862 // when this enum is changed.
10863 enum {
10864   ConstFunction,
10865   ConstVariable,
10866   ConstMember,
10867   ConstMethod,
10868   NestedConstMember,
10869   ConstUnknown,  // Keep as last element
10870 };
10871 
10872 /// Emit the "read-only variable not assignable" error and print notes to give
10873 /// more information about why the variable is not assignable, such as pointing
10874 /// to the declaration of a const variable, showing that a method is const, or
10875 /// that the function is returning a const reference.
10876 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10877                                     SourceLocation Loc) {
10878   SourceRange ExprRange = E->getSourceRange();
10879 
10880   // Only emit one error on the first const found.  All other consts will emit
10881   // a note to the error.
10882   bool DiagnosticEmitted = false;
10883 
10884   // Track if the current expression is the result of a dereference, and if the
10885   // next checked expression is the result of a dereference.
10886   bool IsDereference = false;
10887   bool NextIsDereference = false;
10888 
10889   // Loop to process MemberExpr chains.
10890   while (true) {
10891     IsDereference = NextIsDereference;
10892 
10893     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10894     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10895       NextIsDereference = ME->isArrow();
10896       const ValueDecl *VD = ME->getMemberDecl();
10897       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10898         // Mutable fields can be modified even if the class is const.
10899         if (Field->isMutable()) {
10900           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10901           break;
10902         }
10903 
10904         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10905           if (!DiagnosticEmitted) {
10906             S.Diag(Loc, diag::err_typecheck_assign_const)
10907                 << ExprRange << ConstMember << false /*static*/ << Field
10908                 << Field->getType();
10909             DiagnosticEmitted = true;
10910           }
10911           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10912               << ConstMember << false /*static*/ << Field << Field->getType()
10913               << Field->getSourceRange();
10914         }
10915         E = ME->getBase();
10916         continue;
10917       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10918         if (VDecl->getType().isConstQualified()) {
10919           if (!DiagnosticEmitted) {
10920             S.Diag(Loc, diag::err_typecheck_assign_const)
10921                 << ExprRange << ConstMember << true /*static*/ << VDecl
10922                 << VDecl->getType();
10923             DiagnosticEmitted = true;
10924           }
10925           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10926               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10927               << VDecl->getSourceRange();
10928         }
10929         // Static fields do not inherit constness from parents.
10930         break;
10931       }
10932       break; // End MemberExpr
10933     } else if (const ArraySubscriptExpr *ASE =
10934                    dyn_cast<ArraySubscriptExpr>(E)) {
10935       E = ASE->getBase()->IgnoreParenImpCasts();
10936       continue;
10937     } else if (const ExtVectorElementExpr *EVE =
10938                    dyn_cast<ExtVectorElementExpr>(E)) {
10939       E = EVE->getBase()->IgnoreParenImpCasts();
10940       continue;
10941     }
10942     break;
10943   }
10944 
10945   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10946     // Function calls
10947     const FunctionDecl *FD = CE->getDirectCallee();
10948     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10949       if (!DiagnosticEmitted) {
10950         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10951                                                       << ConstFunction << FD;
10952         DiagnosticEmitted = true;
10953       }
10954       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10955              diag::note_typecheck_assign_const)
10956           << ConstFunction << FD << FD->getReturnType()
10957           << FD->getReturnTypeSourceRange();
10958     }
10959   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10960     // Point to variable declaration.
10961     if (const ValueDecl *VD = DRE->getDecl()) {
10962       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10963         if (!DiagnosticEmitted) {
10964           S.Diag(Loc, diag::err_typecheck_assign_const)
10965               << ExprRange << ConstVariable << VD << VD->getType();
10966           DiagnosticEmitted = true;
10967         }
10968         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10969             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10970       }
10971     }
10972   } else if (isa<CXXThisExpr>(E)) {
10973     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10974       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10975         if (MD->isConst()) {
10976           if (!DiagnosticEmitted) {
10977             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10978                                                           << ConstMethod << MD;
10979             DiagnosticEmitted = true;
10980           }
10981           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10982               << ConstMethod << MD << MD->getSourceRange();
10983         }
10984       }
10985     }
10986   }
10987 
10988   if (DiagnosticEmitted)
10989     return;
10990 
10991   // Can't determine a more specific message, so display the generic error.
10992   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10993 }
10994 
10995 enum OriginalExprKind {
10996   OEK_Variable,
10997   OEK_Member,
10998   OEK_LValue
10999 };
11000 
11001 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11002                                          const RecordType *Ty,
11003                                          SourceLocation Loc, SourceRange Range,
11004                                          OriginalExprKind OEK,
11005                                          bool &DiagnosticEmitted,
11006                                          bool IsNested = false) {
11007   // We walk the record hierarchy breadth-first to ensure that we print
11008   // diagnostics in field nesting order.
11009   // First, check every field for constness.
11010   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
11011     if (Field->getType().isConstQualified()) {
11012       if (!DiagnosticEmitted) {
11013         S.Diag(Loc, diag::err_typecheck_assign_const)
11014             << Range << NestedConstMember << OEK << VD
11015             << IsNested << Field;
11016         DiagnosticEmitted = true;
11017       }
11018       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11019           << NestedConstMember << IsNested << Field
11020           << Field->getType() << Field->getSourceRange();
11021     }
11022   }
11023   // Then, recurse.
11024   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
11025     QualType FTy = Field->getType();
11026     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
11027       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
11028                                    OEK, DiagnosticEmitted, true);
11029   }
11030 }
11031 
11032 /// Emit an error for the case where a record we are trying to assign to has a
11033 /// const-qualified field somewhere in its hierarchy.
11034 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11035                                          SourceLocation Loc) {
11036   QualType Ty = E->getType();
11037   assert(Ty->isRecordType() && "lvalue was not record?");
11038   SourceRange Range = E->getSourceRange();
11039   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11040   bool DiagEmitted = false;
11041 
11042   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11043     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11044             Range, OEK_Member, DiagEmitted);
11045   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11046     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11047             Range, OEK_Variable, DiagEmitted);
11048   else
11049     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11050             Range, OEK_LValue, DiagEmitted);
11051   if (!DiagEmitted)
11052     DiagnoseConstAssignment(S, E, Loc);
11053 }
11054 
11055 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11056 /// emit an error and return true.  If so, return false.
11057 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11058   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11059 
11060   S.CheckShadowingDeclModification(E, Loc);
11061 
11062   SourceLocation OrigLoc = Loc;
11063   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11064                                                               &Loc);
11065   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11066     IsLV = Expr::MLV_InvalidMessageExpression;
11067   if (IsLV == Expr::MLV_Valid)
11068     return false;
11069 
11070   unsigned DiagID = 0;
11071   bool NeedType = false;
11072   switch (IsLV) { // C99 6.5.16p2
11073   case Expr::MLV_ConstQualified:
11074     // Use a specialized diagnostic when we're assigning to an object
11075     // from an enclosing function or block.
11076     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11077       if (NCCK == NCCK_Block)
11078         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11079       else
11080         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11081       break;
11082     }
11083 
11084     // In ARC, use some specialized diagnostics for occasions where we
11085     // infer 'const'.  These are always pseudo-strong variables.
11086     if (S.getLangOpts().ObjCAutoRefCount) {
11087       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11088       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11089         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11090 
11091         // Use the normal diagnostic if it's pseudo-__strong but the
11092         // user actually wrote 'const'.
11093         if (var->isARCPseudoStrong() &&
11094             (!var->getTypeSourceInfo() ||
11095              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11096           // There are two pseudo-strong cases:
11097           //  - self
11098           ObjCMethodDecl *method = S.getCurMethodDecl();
11099           if (method && var == method->getSelfDecl())
11100             DiagID = method->isClassMethod()
11101               ? diag::err_typecheck_arc_assign_self_class_method
11102               : diag::err_typecheck_arc_assign_self;
11103 
11104           //  - fast enumeration variables
11105           else
11106             DiagID = diag::err_typecheck_arr_assign_enumeration;
11107 
11108           SourceRange Assign;
11109           if (Loc != OrigLoc)
11110             Assign = SourceRange(OrigLoc, OrigLoc);
11111           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11112           // We need to preserve the AST regardless, so migration tool
11113           // can do its job.
11114           return false;
11115         }
11116       }
11117     }
11118 
11119     // If none of the special cases above are triggered, then this is a
11120     // simple const assignment.
11121     if (DiagID == 0) {
11122       DiagnoseConstAssignment(S, E, Loc);
11123       return true;
11124     }
11125 
11126     break;
11127   case Expr::MLV_ConstAddrSpace:
11128     DiagnoseConstAssignment(S, E, Loc);
11129     return true;
11130   case Expr::MLV_ConstQualifiedField:
11131     DiagnoseRecursiveConstFields(S, E, Loc);
11132     return true;
11133   case Expr::MLV_ArrayType:
11134   case Expr::MLV_ArrayTemporary:
11135     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11136     NeedType = true;
11137     break;
11138   case Expr::MLV_NotObjectType:
11139     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11140     NeedType = true;
11141     break;
11142   case Expr::MLV_LValueCast:
11143     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11144     break;
11145   case Expr::MLV_Valid:
11146     llvm_unreachable("did not take early return for MLV_Valid");
11147   case Expr::MLV_InvalidExpression:
11148   case Expr::MLV_MemberFunction:
11149   case Expr::MLV_ClassTemporary:
11150     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11151     break;
11152   case Expr::MLV_IncompleteType:
11153   case Expr::MLV_IncompleteVoidType:
11154     return S.RequireCompleteType(Loc, E->getType(),
11155              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11156   case Expr::MLV_DuplicateVectorComponents:
11157     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11158     break;
11159   case Expr::MLV_NoSetterProperty:
11160     llvm_unreachable("readonly properties should be processed differently");
11161   case Expr::MLV_InvalidMessageExpression:
11162     DiagID = diag::err_readonly_message_assignment;
11163     break;
11164   case Expr::MLV_SubObjCPropertySetting:
11165     DiagID = diag::err_no_subobject_property_setting;
11166     break;
11167   }
11168 
11169   SourceRange Assign;
11170   if (Loc != OrigLoc)
11171     Assign = SourceRange(OrigLoc, OrigLoc);
11172   if (NeedType)
11173     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11174   else
11175     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11176   return true;
11177 }
11178 
11179 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11180                                          SourceLocation Loc,
11181                                          Sema &Sema) {
11182   if (Sema.inTemplateInstantiation())
11183     return;
11184   if (Sema.isUnevaluatedContext())
11185     return;
11186   if (Loc.isInvalid() || Loc.isMacroID())
11187     return;
11188   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11189     return;
11190 
11191   // C / C++ fields
11192   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11193   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11194   if (ML && MR) {
11195     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11196       return;
11197     const ValueDecl *LHSDecl =
11198         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11199     const ValueDecl *RHSDecl =
11200         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11201     if (LHSDecl != RHSDecl)
11202       return;
11203     if (LHSDecl->getType().isVolatileQualified())
11204       return;
11205     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11206       if (RefTy->getPointeeType().isVolatileQualified())
11207         return;
11208 
11209     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11210   }
11211 
11212   // Objective-C instance variables
11213   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11214   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11215   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11216     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11217     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11218     if (RL && RR && RL->getDecl() == RR->getDecl())
11219       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11220   }
11221 }
11222 
11223 // C99 6.5.16.1
11224 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11225                                        SourceLocation Loc,
11226                                        QualType CompoundType) {
11227   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11228 
11229   // Verify that LHS is a modifiable lvalue, and emit error if not.
11230   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11231     return QualType();
11232 
11233   QualType LHSType = LHSExpr->getType();
11234   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11235                                              CompoundType;
11236   // OpenCL v1.2 s6.1.1.1 p2:
11237   // The half data type can only be used to declare a pointer to a buffer that
11238   // contains half values
11239   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11240     LHSType->isHalfType()) {
11241     Diag(Loc, diag::err_opencl_half_load_store) << 1
11242         << LHSType.getUnqualifiedType();
11243     return QualType();
11244   }
11245 
11246   AssignConvertType ConvTy;
11247   if (CompoundType.isNull()) {
11248     Expr *RHSCheck = RHS.get();
11249 
11250     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11251 
11252     QualType LHSTy(LHSType);
11253     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11254     if (RHS.isInvalid())
11255       return QualType();
11256     // Special case of NSObject attributes on c-style pointer types.
11257     if (ConvTy == IncompatiblePointer &&
11258         ((Context.isObjCNSObjectType(LHSType) &&
11259           RHSType->isObjCObjectPointerType()) ||
11260          (Context.isObjCNSObjectType(RHSType) &&
11261           LHSType->isObjCObjectPointerType())))
11262       ConvTy = Compatible;
11263 
11264     if (ConvTy == Compatible &&
11265         LHSType->isObjCObjectType())
11266         Diag(Loc, diag::err_objc_object_assignment)
11267           << LHSType;
11268 
11269     // If the RHS is a unary plus or minus, check to see if they = and + are
11270     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11271     // instead of "x += 4".
11272     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11273       RHSCheck = ICE->getSubExpr();
11274     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11275       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11276           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11277           // Only if the two operators are exactly adjacent.
11278           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11279           // And there is a space or other character before the subexpr of the
11280           // unary +/-.  We don't want to warn on "x=-1".
11281           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11282           UO->getSubExpr()->getBeginLoc().isFileID()) {
11283         Diag(Loc, diag::warn_not_compound_assign)
11284           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11285           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11286       }
11287     }
11288 
11289     if (ConvTy == Compatible) {
11290       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11291         // Warn about retain cycles where a block captures the LHS, but
11292         // not if the LHS is a simple variable into which the block is
11293         // being stored...unless that variable can be captured by reference!
11294         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11295         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11296         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11297           checkRetainCycles(LHSExpr, RHS.get());
11298       }
11299 
11300       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11301           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11302         // It is safe to assign a weak reference into a strong variable.
11303         // Although this code can still have problems:
11304         //   id x = self.weakProp;
11305         //   id y = self.weakProp;
11306         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11307         // paths through the function. This should be revisited if
11308         // -Wrepeated-use-of-weak is made flow-sensitive.
11309         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11310         // variable, which will be valid for the current autorelease scope.
11311         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11312                              RHS.get()->getBeginLoc()))
11313           getCurFunction()->markSafeWeakUse(RHS.get());
11314 
11315       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11316         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11317       }
11318     }
11319   } else {
11320     // Compound assignment "x += y"
11321     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11322   }
11323 
11324   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11325                                RHS.get(), AA_Assigning))
11326     return QualType();
11327 
11328   CheckForNullPointerDereference(*this, LHSExpr);
11329 
11330   // C99 6.5.16p3: The type of an assignment expression is the type of the
11331   // left operand unless the left operand has qualified type, in which case
11332   // it is the unqualified version of the type of the left operand.
11333   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11334   // is converted to the type of the assignment expression (above).
11335   // C++ 5.17p1: the type of the assignment expression is that of its left
11336   // operand.
11337   return (getLangOpts().CPlusPlus
11338           ? LHSType : LHSType.getUnqualifiedType());
11339 }
11340 
11341 // Only ignore explicit casts to void.
11342 static bool IgnoreCommaOperand(const Expr *E) {
11343   E = E->IgnoreParens();
11344 
11345   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11346     if (CE->getCastKind() == CK_ToVoid) {
11347       return true;
11348     }
11349 
11350     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11351     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11352         CE->getSubExpr()->getType()->isDependentType()) {
11353       return true;
11354     }
11355   }
11356 
11357   return false;
11358 }
11359 
11360 // Look for instances where it is likely the comma operator is confused with
11361 // another operator.  There is a whitelist of acceptable expressions for the
11362 // left hand side of the comma operator, otherwise emit a warning.
11363 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11364   // No warnings in macros
11365   if (Loc.isMacroID())
11366     return;
11367 
11368   // Don't warn in template instantiations.
11369   if (inTemplateInstantiation())
11370     return;
11371 
11372   // Scope isn't fine-grained enough to whitelist the specific cases, so
11373   // instead, skip more than needed, then call back into here with the
11374   // CommaVisitor in SemaStmt.cpp.
11375   // The whitelisted locations are the initialization and increment portions
11376   // of a for loop.  The additional checks are on the condition of
11377   // if statements, do/while loops, and for loops.
11378   // Differences in scope flags for C89 mode requires the extra logic.
11379   const unsigned ForIncrementFlags =
11380       getLangOpts().C99 || getLangOpts().CPlusPlus
11381           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11382           : Scope::ContinueScope | Scope::BreakScope;
11383   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11384   const unsigned ScopeFlags = getCurScope()->getFlags();
11385   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11386       (ScopeFlags & ForInitFlags) == ForInitFlags)
11387     return;
11388 
11389   // If there are multiple comma operators used together, get the RHS of the
11390   // of the comma operator as the LHS.
11391   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11392     if (BO->getOpcode() != BO_Comma)
11393       break;
11394     LHS = BO->getRHS();
11395   }
11396 
11397   // Only allow some expressions on LHS to not warn.
11398   if (IgnoreCommaOperand(LHS))
11399     return;
11400 
11401   Diag(Loc, diag::warn_comma_operator);
11402   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11403       << LHS->getSourceRange()
11404       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11405                                     LangOpts.CPlusPlus ? "static_cast<void>("
11406                                                        : "(void)(")
11407       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11408                                     ")");
11409 }
11410 
11411 // C99 6.5.17
11412 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11413                                    SourceLocation Loc) {
11414   LHS = S.CheckPlaceholderExpr(LHS.get());
11415   RHS = S.CheckPlaceholderExpr(RHS.get());
11416   if (LHS.isInvalid() || RHS.isInvalid())
11417     return QualType();
11418 
11419   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11420   // operands, but not unary promotions.
11421   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11422 
11423   // So we treat the LHS as a ignored value, and in C++ we allow the
11424   // containing site to determine what should be done with the RHS.
11425   LHS = S.IgnoredValueConversions(LHS.get());
11426   if (LHS.isInvalid())
11427     return QualType();
11428 
11429   S.DiagnoseUnusedExprResult(LHS.get());
11430 
11431   if (!S.getLangOpts().CPlusPlus) {
11432     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11433     if (RHS.isInvalid())
11434       return QualType();
11435     if (!RHS.get()->getType()->isVoidType())
11436       S.RequireCompleteType(Loc, RHS.get()->getType(),
11437                             diag::err_incomplete_type);
11438   }
11439 
11440   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11441     S.DiagnoseCommaOperator(LHS.get(), Loc);
11442 
11443   return RHS.get()->getType();
11444 }
11445 
11446 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11447 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11448 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11449                                                ExprValueKind &VK,
11450                                                ExprObjectKind &OK,
11451                                                SourceLocation OpLoc,
11452                                                bool IsInc, bool IsPrefix) {
11453   if (Op->isTypeDependent())
11454     return S.Context.DependentTy;
11455 
11456   QualType ResType = Op->getType();
11457   // Atomic types can be used for increment / decrement where the non-atomic
11458   // versions can, so ignore the _Atomic() specifier for the purpose of
11459   // checking.
11460   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11461     ResType = ResAtomicType->getValueType();
11462 
11463   assert(!ResType.isNull() && "no type for increment/decrement expression");
11464 
11465   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11466     // Decrement of bool is not allowed.
11467     if (!IsInc) {
11468       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11469       return QualType();
11470     }
11471     // Increment of bool sets it to true, but is deprecated.
11472     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11473                                               : diag::warn_increment_bool)
11474       << Op->getSourceRange();
11475   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11476     // Error on enum increments and decrements in C++ mode
11477     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11478     return QualType();
11479   } else if (ResType->isRealType()) {
11480     // OK!
11481   } else if (ResType->isPointerType()) {
11482     // C99 6.5.2.4p2, 6.5.6p2
11483     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11484       return QualType();
11485   } else if (ResType->isObjCObjectPointerType()) {
11486     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11487     // Otherwise, we just need a complete type.
11488     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11489         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11490       return QualType();
11491   } else if (ResType->isAnyComplexType()) {
11492     // C99 does not support ++/-- on complex types, we allow as an extension.
11493     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11494       << ResType << Op->getSourceRange();
11495   } else if (ResType->isPlaceholderType()) {
11496     ExprResult PR = S.CheckPlaceholderExpr(Op);
11497     if (PR.isInvalid()) return QualType();
11498     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11499                                           IsInc, IsPrefix);
11500   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11501     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11502   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11503              (ResType->getAs<VectorType>()->getVectorKind() !=
11504               VectorType::AltiVecBool)) {
11505     // The z vector extensions allow ++ and -- for non-bool vectors.
11506   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11507             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11508     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11509   } else {
11510     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11511       << ResType << int(IsInc) << Op->getSourceRange();
11512     return QualType();
11513   }
11514   // At this point, we know we have a real, complex or pointer type.
11515   // Now make sure the operand is a modifiable lvalue.
11516   if (CheckForModifiableLvalue(Op, OpLoc, S))
11517     return QualType();
11518   // In C++, a prefix increment is the same type as the operand. Otherwise
11519   // (in C or with postfix), the increment is the unqualified type of the
11520   // operand.
11521   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11522     VK = VK_LValue;
11523     OK = Op->getObjectKind();
11524     return ResType;
11525   } else {
11526     VK = VK_RValue;
11527     return ResType.getUnqualifiedType();
11528   }
11529 }
11530 
11531 
11532 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11533 /// This routine allows us to typecheck complex/recursive expressions
11534 /// where the declaration is needed for type checking. We only need to
11535 /// handle cases when the expression references a function designator
11536 /// or is an lvalue. Here are some examples:
11537 ///  - &(x) => x
11538 ///  - &*****f => f for f a function designator.
11539 ///  - &s.xx => s
11540 ///  - &s.zz[1].yy -> s, if zz is an array
11541 ///  - *(x + 1) -> x, if x is an array
11542 ///  - &"123"[2] -> 0
11543 ///  - & __real__ x -> x
11544 static ValueDecl *getPrimaryDecl(Expr *E) {
11545   switch (E->getStmtClass()) {
11546   case Stmt::DeclRefExprClass:
11547     return cast<DeclRefExpr>(E)->getDecl();
11548   case Stmt::MemberExprClass:
11549     // If this is an arrow operator, the address is an offset from
11550     // the base's value, so the object the base refers to is
11551     // irrelevant.
11552     if (cast<MemberExpr>(E)->isArrow())
11553       return nullptr;
11554     // Otherwise, the expression refers to a part of the base
11555     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11556   case Stmt::ArraySubscriptExprClass: {
11557     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11558     // promotion of register arrays earlier.
11559     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11560     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11561       if (ICE->getSubExpr()->getType()->isArrayType())
11562         return getPrimaryDecl(ICE->getSubExpr());
11563     }
11564     return nullptr;
11565   }
11566   case Stmt::UnaryOperatorClass: {
11567     UnaryOperator *UO = cast<UnaryOperator>(E);
11568 
11569     switch(UO->getOpcode()) {
11570     case UO_Real:
11571     case UO_Imag:
11572     case UO_Extension:
11573       return getPrimaryDecl(UO->getSubExpr());
11574     default:
11575       return nullptr;
11576     }
11577   }
11578   case Stmt::ParenExprClass:
11579     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11580   case Stmt::ImplicitCastExprClass:
11581     // If the result of an implicit cast is an l-value, we care about
11582     // the sub-expression; otherwise, the result here doesn't matter.
11583     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11584   default:
11585     return nullptr;
11586   }
11587 }
11588 
11589 namespace {
11590   enum {
11591     AO_Bit_Field = 0,
11592     AO_Vector_Element = 1,
11593     AO_Property_Expansion = 2,
11594     AO_Register_Variable = 3,
11595     AO_No_Error = 4
11596   };
11597 }
11598 /// Diagnose invalid operand for address of operations.
11599 ///
11600 /// \param Type The type of operand which cannot have its address taken.
11601 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11602                                          Expr *E, unsigned Type) {
11603   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11604 }
11605 
11606 /// CheckAddressOfOperand - The operand of & must be either a function
11607 /// designator or an lvalue designating an object. If it is an lvalue, the
11608 /// object cannot be declared with storage class register or be a bit field.
11609 /// Note: The usual conversions are *not* applied to the operand of the &
11610 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11611 /// In C++, the operand might be an overloaded function name, in which case
11612 /// we allow the '&' but retain the overloaded-function type.
11613 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11614   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11615     if (PTy->getKind() == BuiltinType::Overload) {
11616       Expr *E = OrigOp.get()->IgnoreParens();
11617       if (!isa<OverloadExpr>(E)) {
11618         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11619         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11620           << OrigOp.get()->getSourceRange();
11621         return QualType();
11622       }
11623 
11624       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11625       if (isa<UnresolvedMemberExpr>(Ovl))
11626         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11627           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11628             << OrigOp.get()->getSourceRange();
11629           return QualType();
11630         }
11631 
11632       return Context.OverloadTy;
11633     }
11634 
11635     if (PTy->getKind() == BuiltinType::UnknownAny)
11636       return Context.UnknownAnyTy;
11637 
11638     if (PTy->getKind() == BuiltinType::BoundMember) {
11639       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11640         << OrigOp.get()->getSourceRange();
11641       return QualType();
11642     }
11643 
11644     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11645     if (OrigOp.isInvalid()) return QualType();
11646   }
11647 
11648   if (OrigOp.get()->isTypeDependent())
11649     return Context.DependentTy;
11650 
11651   assert(!OrigOp.get()->getType()->isPlaceholderType());
11652 
11653   // Make sure to ignore parentheses in subsequent checks
11654   Expr *op = OrigOp.get()->IgnoreParens();
11655 
11656   // In OpenCL captures for blocks called as lambda functions
11657   // are located in the private address space. Blocks used in
11658   // enqueue_kernel can be located in a different address space
11659   // depending on a vendor implementation. Thus preventing
11660   // taking an address of the capture to avoid invalid AS casts.
11661   if (LangOpts.OpenCL) {
11662     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11663     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11664       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11665       return QualType();
11666     }
11667   }
11668 
11669   if (getLangOpts().C99) {
11670     // Implement C99-only parts of addressof rules.
11671     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11672       if (uOp->getOpcode() == UO_Deref)
11673         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11674         // (assuming the deref expression is valid).
11675         return uOp->getSubExpr()->getType();
11676     }
11677     // Technically, there should be a check for array subscript
11678     // expressions here, but the result of one is always an lvalue anyway.
11679   }
11680   ValueDecl *dcl = getPrimaryDecl(op);
11681 
11682   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11683     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11684                                            op->getBeginLoc()))
11685       return QualType();
11686 
11687   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11688   unsigned AddressOfError = AO_No_Error;
11689 
11690   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11691     bool sfinae = (bool)isSFINAEContext();
11692     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11693                                   : diag::ext_typecheck_addrof_temporary)
11694       << op->getType() << op->getSourceRange();
11695     if (sfinae)
11696       return QualType();
11697     // Materialize the temporary as an lvalue so that we can take its address.
11698     OrigOp = op =
11699         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11700   } else if (isa<ObjCSelectorExpr>(op)) {
11701     return Context.getPointerType(op->getType());
11702   } else if (lval == Expr::LV_MemberFunction) {
11703     // If it's an instance method, make a member pointer.
11704     // The expression must have exactly the form &A::foo.
11705 
11706     // If the underlying expression isn't a decl ref, give up.
11707     if (!isa<DeclRefExpr>(op)) {
11708       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11709         << OrigOp.get()->getSourceRange();
11710       return QualType();
11711     }
11712     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11713     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11714 
11715     // The id-expression was parenthesized.
11716     if (OrigOp.get() != DRE) {
11717       Diag(OpLoc, diag::err_parens_pointer_member_function)
11718         << OrigOp.get()->getSourceRange();
11719 
11720     // The method was named without a qualifier.
11721     } else if (!DRE->getQualifier()) {
11722       if (MD->getParent()->getName().empty())
11723         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11724           << op->getSourceRange();
11725       else {
11726         SmallString<32> Str;
11727         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11728         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11729           << op->getSourceRange()
11730           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11731       }
11732     }
11733 
11734     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11735     if (isa<CXXDestructorDecl>(MD))
11736       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11737 
11738     QualType MPTy = Context.getMemberPointerType(
11739         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11740     // Under the MS ABI, lock down the inheritance model now.
11741     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11742       (void)isCompleteType(OpLoc, MPTy);
11743     return MPTy;
11744   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11745     // C99 6.5.3.2p1
11746     // The operand must be either an l-value or a function designator
11747     if (!op->getType()->isFunctionType()) {
11748       // Use a special diagnostic for loads from property references.
11749       if (isa<PseudoObjectExpr>(op)) {
11750         AddressOfError = AO_Property_Expansion;
11751       } else {
11752         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11753           << op->getType() << op->getSourceRange();
11754         return QualType();
11755       }
11756     }
11757   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11758     // The operand cannot be a bit-field
11759     AddressOfError = AO_Bit_Field;
11760   } else if (op->getObjectKind() == OK_VectorComponent) {
11761     // The operand cannot be an element of a vector
11762     AddressOfError = AO_Vector_Element;
11763   } else if (dcl) { // C99 6.5.3.2p1
11764     // We have an lvalue with a decl. Make sure the decl is not declared
11765     // with the register storage-class specifier.
11766     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11767       // in C++ it is not error to take address of a register
11768       // variable (c++03 7.1.1P3)
11769       if (vd->getStorageClass() == SC_Register &&
11770           !getLangOpts().CPlusPlus) {
11771         AddressOfError = AO_Register_Variable;
11772       }
11773     } else if (isa<MSPropertyDecl>(dcl)) {
11774       AddressOfError = AO_Property_Expansion;
11775     } else if (isa<FunctionTemplateDecl>(dcl)) {
11776       return Context.OverloadTy;
11777     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11778       // Okay: we can take the address of a field.
11779       // Could be a pointer to member, though, if there is an explicit
11780       // scope qualifier for the class.
11781       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11782         DeclContext *Ctx = dcl->getDeclContext();
11783         if (Ctx && Ctx->isRecord()) {
11784           if (dcl->getType()->isReferenceType()) {
11785             Diag(OpLoc,
11786                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11787               << dcl->getDeclName() << dcl->getType();
11788             return QualType();
11789           }
11790 
11791           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11792             Ctx = Ctx->getParent();
11793 
11794           QualType MPTy = Context.getMemberPointerType(
11795               op->getType(),
11796               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11797           // Under the MS ABI, lock down the inheritance model now.
11798           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11799             (void)isCompleteType(OpLoc, MPTy);
11800           return MPTy;
11801         }
11802       }
11803     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11804                !isa<BindingDecl>(dcl))
11805       llvm_unreachable("Unknown/unexpected decl type");
11806   }
11807 
11808   if (AddressOfError != AO_No_Error) {
11809     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11810     return QualType();
11811   }
11812 
11813   if (lval == Expr::LV_IncompleteVoidType) {
11814     // Taking the address of a void variable is technically illegal, but we
11815     // allow it in cases which are otherwise valid.
11816     // Example: "extern void x; void* y = &x;".
11817     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11818   }
11819 
11820   // If the operand has type "type", the result has type "pointer to type".
11821   if (op->getType()->isObjCObjectType())
11822     return Context.getObjCObjectPointerType(op->getType());
11823 
11824   CheckAddressOfPackedMember(op);
11825 
11826   return Context.getPointerType(op->getType());
11827 }
11828 
11829 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11830   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11831   if (!DRE)
11832     return;
11833   const Decl *D = DRE->getDecl();
11834   if (!D)
11835     return;
11836   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11837   if (!Param)
11838     return;
11839   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11840     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11841       return;
11842   if (FunctionScopeInfo *FD = S.getCurFunction())
11843     if (!FD->ModifiedNonNullParams.count(Param))
11844       FD->ModifiedNonNullParams.insert(Param);
11845 }
11846 
11847 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11848 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11849                                         SourceLocation OpLoc) {
11850   if (Op->isTypeDependent())
11851     return S.Context.DependentTy;
11852 
11853   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11854   if (ConvResult.isInvalid())
11855     return QualType();
11856   Op = ConvResult.get();
11857   QualType OpTy = Op->getType();
11858   QualType Result;
11859 
11860   if (isa<CXXReinterpretCastExpr>(Op)) {
11861     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11862     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11863                                      Op->getSourceRange());
11864   }
11865 
11866   if (const PointerType *PT = OpTy->getAs<PointerType>())
11867   {
11868     Result = PT->getPointeeType();
11869   }
11870   else if (const ObjCObjectPointerType *OPT =
11871              OpTy->getAs<ObjCObjectPointerType>())
11872     Result = OPT->getPointeeType();
11873   else {
11874     ExprResult PR = S.CheckPlaceholderExpr(Op);
11875     if (PR.isInvalid()) return QualType();
11876     if (PR.get() != Op)
11877       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11878   }
11879 
11880   if (Result.isNull()) {
11881     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11882       << OpTy << Op->getSourceRange();
11883     return QualType();
11884   }
11885 
11886   // Note that per both C89 and C99, indirection is always legal, even if Result
11887   // is an incomplete type or void.  It would be possible to warn about
11888   // dereferencing a void pointer, but it's completely well-defined, and such a
11889   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11890   // for pointers to 'void' but is fine for any other pointer type:
11891   //
11892   // C++ [expr.unary.op]p1:
11893   //   [...] the expression to which [the unary * operator] is applied shall
11894   //   be a pointer to an object type, or a pointer to a function type
11895   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11896     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11897       << OpTy << Op->getSourceRange();
11898 
11899   // Dereferences are usually l-values...
11900   VK = VK_LValue;
11901 
11902   // ...except that certain expressions are never l-values in C.
11903   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11904     VK = VK_RValue;
11905 
11906   return Result;
11907 }
11908 
11909 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11910   BinaryOperatorKind Opc;
11911   switch (Kind) {
11912   default: llvm_unreachable("Unknown binop!");
11913   case tok::periodstar:           Opc = BO_PtrMemD; break;
11914   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11915   case tok::star:                 Opc = BO_Mul; break;
11916   case tok::slash:                Opc = BO_Div; break;
11917   case tok::percent:              Opc = BO_Rem; break;
11918   case tok::plus:                 Opc = BO_Add; break;
11919   case tok::minus:                Opc = BO_Sub; break;
11920   case tok::lessless:             Opc = BO_Shl; break;
11921   case tok::greatergreater:       Opc = BO_Shr; break;
11922   case tok::lessequal:            Opc = BO_LE; break;
11923   case tok::less:                 Opc = BO_LT; break;
11924   case tok::greaterequal:         Opc = BO_GE; break;
11925   case tok::greater:              Opc = BO_GT; break;
11926   case tok::exclaimequal:         Opc = BO_NE; break;
11927   case tok::equalequal:           Opc = BO_EQ; break;
11928   case tok::spaceship:            Opc = BO_Cmp; break;
11929   case tok::amp:                  Opc = BO_And; break;
11930   case tok::caret:                Opc = BO_Xor; break;
11931   case tok::pipe:                 Opc = BO_Or; break;
11932   case tok::ampamp:               Opc = BO_LAnd; break;
11933   case tok::pipepipe:             Opc = BO_LOr; break;
11934   case tok::equal:                Opc = BO_Assign; break;
11935   case tok::starequal:            Opc = BO_MulAssign; break;
11936   case tok::slashequal:           Opc = BO_DivAssign; break;
11937   case tok::percentequal:         Opc = BO_RemAssign; break;
11938   case tok::plusequal:            Opc = BO_AddAssign; break;
11939   case tok::minusequal:           Opc = BO_SubAssign; break;
11940   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11941   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11942   case tok::ampequal:             Opc = BO_AndAssign; break;
11943   case tok::caretequal:           Opc = BO_XorAssign; break;
11944   case tok::pipeequal:            Opc = BO_OrAssign; break;
11945   case tok::comma:                Opc = BO_Comma; break;
11946   }
11947   return Opc;
11948 }
11949 
11950 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11951   tok::TokenKind Kind) {
11952   UnaryOperatorKind Opc;
11953   switch (Kind) {
11954   default: llvm_unreachable("Unknown unary op!");
11955   case tok::plusplus:     Opc = UO_PreInc; break;
11956   case tok::minusminus:   Opc = UO_PreDec; break;
11957   case tok::amp:          Opc = UO_AddrOf; break;
11958   case tok::star:         Opc = UO_Deref; break;
11959   case tok::plus:         Opc = UO_Plus; break;
11960   case tok::minus:        Opc = UO_Minus; break;
11961   case tok::tilde:        Opc = UO_Not; break;
11962   case tok::exclaim:      Opc = UO_LNot; break;
11963   case tok::kw___real:    Opc = UO_Real; break;
11964   case tok::kw___imag:    Opc = UO_Imag; break;
11965   case tok::kw___extension__: Opc = UO_Extension; break;
11966   }
11967   return Opc;
11968 }
11969 
11970 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11971 /// This warning suppressed in the event of macro expansions.
11972 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11973                                    SourceLocation OpLoc, bool IsBuiltin) {
11974   if (S.inTemplateInstantiation())
11975     return;
11976   if (S.isUnevaluatedContext())
11977     return;
11978   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11979     return;
11980   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11981   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11982   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11983   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11984   if (!LHSDeclRef || !RHSDeclRef ||
11985       LHSDeclRef->getLocation().isMacroID() ||
11986       RHSDeclRef->getLocation().isMacroID())
11987     return;
11988   const ValueDecl *LHSDecl =
11989     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11990   const ValueDecl *RHSDecl =
11991     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11992   if (LHSDecl != RHSDecl)
11993     return;
11994   if (LHSDecl->getType().isVolatileQualified())
11995     return;
11996   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11997     if (RefTy->getPointeeType().isVolatileQualified())
11998       return;
11999 
12000   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12001                           : diag::warn_self_assignment_overloaded)
12002       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12003       << RHSExpr->getSourceRange();
12004 }
12005 
12006 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12007 /// is usually indicative of introspection within the Objective-C pointer.
12008 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12009                                           SourceLocation OpLoc) {
12010   if (!S.getLangOpts().ObjC)
12011     return;
12012 
12013   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12014   const Expr *LHS = L.get();
12015   const Expr *RHS = R.get();
12016 
12017   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12018     ObjCPointerExpr = LHS;
12019     OtherExpr = RHS;
12020   }
12021   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12022     ObjCPointerExpr = RHS;
12023     OtherExpr = LHS;
12024   }
12025 
12026   // This warning is deliberately made very specific to reduce false
12027   // positives with logic that uses '&' for hashing.  This logic mainly
12028   // looks for code trying to introspect into tagged pointers, which
12029   // code should generally never do.
12030   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12031     unsigned Diag = diag::warn_objc_pointer_masking;
12032     // Determine if we are introspecting the result of performSelectorXXX.
12033     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12034     // Special case messages to -performSelector and friends, which
12035     // can return non-pointer values boxed in a pointer value.
12036     // Some clients may wish to silence warnings in this subcase.
12037     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12038       Selector S = ME->getSelector();
12039       StringRef SelArg0 = S.getNameForSlot(0);
12040       if (SelArg0.startswith("performSelector"))
12041         Diag = diag::warn_objc_pointer_masking_performSelector;
12042     }
12043 
12044     S.Diag(OpLoc, Diag)
12045       << ObjCPointerExpr->getSourceRange();
12046   }
12047 }
12048 
12049 static NamedDecl *getDeclFromExpr(Expr *E) {
12050   if (!E)
12051     return nullptr;
12052   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12053     return DRE->getDecl();
12054   if (auto *ME = dyn_cast<MemberExpr>(E))
12055     return ME->getMemberDecl();
12056   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12057     return IRE->getDecl();
12058   return nullptr;
12059 }
12060 
12061 // This helper function promotes a binary operator's operands (which are of a
12062 // half vector type) to a vector of floats and then truncates the result to
12063 // a vector of either half or short.
12064 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12065                                       BinaryOperatorKind Opc, QualType ResultTy,
12066                                       ExprValueKind VK, ExprObjectKind OK,
12067                                       bool IsCompAssign, SourceLocation OpLoc,
12068                                       FPOptions FPFeatures) {
12069   auto &Context = S.getASTContext();
12070   assert((isVector(ResultTy, Context.HalfTy) ||
12071           isVector(ResultTy, Context.ShortTy)) &&
12072          "Result must be a vector of half or short");
12073   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12074          isVector(RHS.get()->getType(), Context.HalfTy) &&
12075          "both operands expected to be a half vector");
12076 
12077   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12078   QualType BinOpResTy = RHS.get()->getType();
12079 
12080   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12081   // change BinOpResTy to a vector of ints.
12082   if (isVector(ResultTy, Context.ShortTy))
12083     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12084 
12085   if (IsCompAssign)
12086     return new (Context) CompoundAssignOperator(
12087         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12088         OpLoc, FPFeatures);
12089 
12090   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12091   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12092                                           VK, OK, OpLoc, FPFeatures);
12093   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12094 }
12095 
12096 static std::pair<ExprResult, ExprResult>
12097 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12098                            Expr *RHSExpr) {
12099   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12100   if (!S.getLangOpts().CPlusPlus) {
12101     // C cannot handle TypoExpr nodes on either side of a binop because it
12102     // doesn't handle dependent types properly, so make sure any TypoExprs have
12103     // been dealt with before checking the operands.
12104     LHS = S.CorrectDelayedTyposInExpr(LHS);
12105     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12106       if (Opc != BO_Assign)
12107         return ExprResult(E);
12108       // Avoid correcting the RHS to the same Expr as the LHS.
12109       Decl *D = getDeclFromExpr(E);
12110       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12111     });
12112   }
12113   return std::make_pair(LHS, RHS);
12114 }
12115 
12116 /// Returns true if conversion between vectors of halfs and vectors of floats
12117 /// is needed.
12118 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12119                                      QualType SrcType) {
12120   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12121          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12122          isVector(SrcType, Ctx.HalfTy);
12123 }
12124 
12125 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12126 /// operator @p Opc at location @c TokLoc. This routine only supports
12127 /// built-in operations; ActOnBinOp handles overloaded operators.
12128 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12129                                     BinaryOperatorKind Opc,
12130                                     Expr *LHSExpr, Expr *RHSExpr) {
12131   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12132     // The syntax only allows initializer lists on the RHS of assignment,
12133     // so we don't need to worry about accepting invalid code for
12134     // non-assignment operators.
12135     // C++11 5.17p9:
12136     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12137     //   of x = {} is x = T().
12138     InitializationKind Kind = InitializationKind::CreateDirectList(
12139         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12140     InitializedEntity Entity =
12141         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12142     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12143     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12144     if (Init.isInvalid())
12145       return Init;
12146     RHSExpr = Init.get();
12147   }
12148 
12149   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12150   QualType ResultTy;     // Result type of the binary operator.
12151   // The following two variables are used for compound assignment operators
12152   QualType CompLHSTy;    // Type of LHS after promotions for computation
12153   QualType CompResultTy; // Type of computation result
12154   ExprValueKind VK = VK_RValue;
12155   ExprObjectKind OK = OK_Ordinary;
12156   bool ConvertHalfVec = false;
12157 
12158   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12159   if (!LHS.isUsable() || !RHS.isUsable())
12160     return ExprError();
12161 
12162   if (getLangOpts().OpenCL) {
12163     QualType LHSTy = LHSExpr->getType();
12164     QualType RHSTy = RHSExpr->getType();
12165     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12166     // the ATOMIC_VAR_INIT macro.
12167     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12168       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12169       if (BO_Assign == Opc)
12170         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12171       else
12172         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12173       return ExprError();
12174     }
12175 
12176     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12177     // only with a builtin functions and therefore should be disallowed here.
12178     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12179         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12180         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12181         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12182       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12183       return ExprError();
12184     }
12185   }
12186 
12187   switch (Opc) {
12188   case BO_Assign:
12189     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12190     if (getLangOpts().CPlusPlus &&
12191         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12192       VK = LHS.get()->getValueKind();
12193       OK = LHS.get()->getObjectKind();
12194     }
12195     if (!ResultTy.isNull()) {
12196       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12197       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12198     }
12199     RecordModifiableNonNullParam(*this, LHS.get());
12200     break;
12201   case BO_PtrMemD:
12202   case BO_PtrMemI:
12203     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12204                                             Opc == BO_PtrMemI);
12205     break;
12206   case BO_Mul:
12207   case BO_Div:
12208     ConvertHalfVec = true;
12209     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12210                                            Opc == BO_Div);
12211     break;
12212   case BO_Rem:
12213     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12214     break;
12215   case BO_Add:
12216     ConvertHalfVec = true;
12217     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12218     break;
12219   case BO_Sub:
12220     ConvertHalfVec = true;
12221     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12222     break;
12223   case BO_Shl:
12224   case BO_Shr:
12225     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12226     break;
12227   case BO_LE:
12228   case BO_LT:
12229   case BO_GE:
12230   case BO_GT:
12231     ConvertHalfVec = true;
12232     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12233     break;
12234   case BO_EQ:
12235   case BO_NE:
12236     ConvertHalfVec = true;
12237     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12238     break;
12239   case BO_Cmp:
12240     ConvertHalfVec = true;
12241     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12242     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12243     break;
12244   case BO_And:
12245     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12246     LLVM_FALLTHROUGH;
12247   case BO_Xor:
12248   case BO_Or:
12249     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12250     break;
12251   case BO_LAnd:
12252   case BO_LOr:
12253     ConvertHalfVec = true;
12254     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12255     break;
12256   case BO_MulAssign:
12257   case BO_DivAssign:
12258     ConvertHalfVec = true;
12259     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12260                                                Opc == BO_DivAssign);
12261     CompLHSTy = CompResultTy;
12262     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12263       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12264     break;
12265   case BO_RemAssign:
12266     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12267     CompLHSTy = CompResultTy;
12268     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12269       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12270     break;
12271   case BO_AddAssign:
12272     ConvertHalfVec = true;
12273     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12274     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12275       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12276     break;
12277   case BO_SubAssign:
12278     ConvertHalfVec = true;
12279     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12280     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12281       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12282     break;
12283   case BO_ShlAssign:
12284   case BO_ShrAssign:
12285     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12286     CompLHSTy = CompResultTy;
12287     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12288       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12289     break;
12290   case BO_AndAssign:
12291   case BO_OrAssign: // fallthrough
12292     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12293     LLVM_FALLTHROUGH;
12294   case BO_XorAssign:
12295     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12296     CompLHSTy = CompResultTy;
12297     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12298       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12299     break;
12300   case BO_Comma:
12301     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12302     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12303       VK = RHS.get()->getValueKind();
12304       OK = RHS.get()->getObjectKind();
12305     }
12306     break;
12307   }
12308   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12309     return ExprError();
12310 
12311   // Some of the binary operations require promoting operands of half vector to
12312   // float vectors and truncating the result back to half vector. For now, we do
12313   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12314   // arm64).
12315   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12316          isVector(LHS.get()->getType(), Context.HalfTy) &&
12317          "both sides are half vectors or neither sides are");
12318   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12319                                             LHS.get()->getType());
12320 
12321   // Check for array bounds violations for both sides of the BinaryOperator
12322   CheckArrayAccess(LHS.get());
12323   CheckArrayAccess(RHS.get());
12324 
12325   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12326     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12327                                                  &Context.Idents.get("object_setClass"),
12328                                                  SourceLocation(), LookupOrdinaryName);
12329     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12330       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12331       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12332           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12333                                         "object_setClass(")
12334           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12335                                           ",")
12336           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12337     }
12338     else
12339       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12340   }
12341   else if (const ObjCIvarRefExpr *OIRE =
12342            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12343     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12344 
12345   // Opc is not a compound assignment if CompResultTy is null.
12346   if (CompResultTy.isNull()) {
12347     if (ConvertHalfVec)
12348       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12349                                  OpLoc, FPFeatures);
12350     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12351                                         OK, OpLoc, FPFeatures);
12352   }
12353 
12354   // Handle compound assignments.
12355   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12356       OK_ObjCProperty) {
12357     VK = VK_LValue;
12358     OK = LHS.get()->getObjectKind();
12359   }
12360 
12361   if (ConvertHalfVec)
12362     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12363                                OpLoc, FPFeatures);
12364 
12365   return new (Context) CompoundAssignOperator(
12366       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12367       OpLoc, FPFeatures);
12368 }
12369 
12370 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12371 /// operators are mixed in a way that suggests that the programmer forgot that
12372 /// comparison operators have higher precedence. The most typical example of
12373 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12374 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12375                                       SourceLocation OpLoc, Expr *LHSExpr,
12376                                       Expr *RHSExpr) {
12377   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12378   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12379 
12380   // Check that one of the sides is a comparison operator and the other isn't.
12381   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12382   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12383   if (isLeftComp == isRightComp)
12384     return;
12385 
12386   // Bitwise operations are sometimes used as eager logical ops.
12387   // Don't diagnose this.
12388   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12389   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12390   if (isLeftBitwise || isRightBitwise)
12391     return;
12392 
12393   SourceRange DiagRange = isLeftComp
12394                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12395                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12396   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12397   SourceRange ParensRange =
12398       isLeftComp
12399           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12400           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12401 
12402   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12403     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12404   SuggestParentheses(Self, OpLoc,
12405     Self.PDiag(diag::note_precedence_silence) << OpStr,
12406     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12407   SuggestParentheses(Self, OpLoc,
12408     Self.PDiag(diag::note_precedence_bitwise_first)
12409       << BinaryOperator::getOpcodeStr(Opc),
12410     ParensRange);
12411 }
12412 
12413 /// It accepts a '&&' expr that is inside a '||' one.
12414 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12415 /// in parentheses.
12416 static void
12417 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12418                                        BinaryOperator *Bop) {
12419   assert(Bop->getOpcode() == BO_LAnd);
12420   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12421       << Bop->getSourceRange() << OpLoc;
12422   SuggestParentheses(Self, Bop->getOperatorLoc(),
12423     Self.PDiag(diag::note_precedence_silence)
12424       << Bop->getOpcodeStr(),
12425     Bop->getSourceRange());
12426 }
12427 
12428 /// Returns true if the given expression can be evaluated as a constant
12429 /// 'true'.
12430 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12431   bool Res;
12432   return !E->isValueDependent() &&
12433          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12434 }
12435 
12436 /// Returns true if the given expression can be evaluated as a constant
12437 /// 'false'.
12438 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12439   bool Res;
12440   return !E->isValueDependent() &&
12441          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12442 }
12443 
12444 /// Look for '&&' in the left hand of a '||' expr.
12445 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12446                                              Expr *LHSExpr, Expr *RHSExpr) {
12447   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12448     if (Bop->getOpcode() == BO_LAnd) {
12449       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12450       if (EvaluatesAsFalse(S, RHSExpr))
12451         return;
12452       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12453       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12454         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12455     } else if (Bop->getOpcode() == BO_LOr) {
12456       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12457         // If it's "a || b && 1 || c" we didn't warn earlier for
12458         // "a || b && 1", but warn now.
12459         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12460           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12461       }
12462     }
12463   }
12464 }
12465 
12466 /// Look for '&&' in the right hand of a '||' expr.
12467 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12468                                              Expr *LHSExpr, Expr *RHSExpr) {
12469   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12470     if (Bop->getOpcode() == BO_LAnd) {
12471       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12472       if (EvaluatesAsFalse(S, LHSExpr))
12473         return;
12474       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12475       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12476         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12477     }
12478   }
12479 }
12480 
12481 /// Look for bitwise op in the left or right hand of a bitwise op with
12482 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12483 /// the '&' expression in parentheses.
12484 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12485                                          SourceLocation OpLoc, Expr *SubExpr) {
12486   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12487     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12488       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12489         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12490         << Bop->getSourceRange() << OpLoc;
12491       SuggestParentheses(S, Bop->getOperatorLoc(),
12492         S.PDiag(diag::note_precedence_silence)
12493           << Bop->getOpcodeStr(),
12494         Bop->getSourceRange());
12495     }
12496   }
12497 }
12498 
12499 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12500                                     Expr *SubExpr, StringRef Shift) {
12501   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12502     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12503       StringRef Op = Bop->getOpcodeStr();
12504       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12505           << Bop->getSourceRange() << OpLoc << Shift << Op;
12506       SuggestParentheses(S, Bop->getOperatorLoc(),
12507           S.PDiag(diag::note_precedence_silence) << Op,
12508           Bop->getSourceRange());
12509     }
12510   }
12511 }
12512 
12513 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12514                                  Expr *LHSExpr, Expr *RHSExpr) {
12515   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12516   if (!OCE)
12517     return;
12518 
12519   FunctionDecl *FD = OCE->getDirectCallee();
12520   if (!FD || !FD->isOverloadedOperator())
12521     return;
12522 
12523   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12524   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12525     return;
12526 
12527   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12528       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12529       << (Kind == OO_LessLess);
12530   SuggestParentheses(S, OCE->getOperatorLoc(),
12531                      S.PDiag(diag::note_precedence_silence)
12532                          << (Kind == OO_LessLess ? "<<" : ">>"),
12533                      OCE->getSourceRange());
12534   SuggestParentheses(
12535       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12536       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12537 }
12538 
12539 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12540 /// precedence.
12541 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12542                                     SourceLocation OpLoc, Expr *LHSExpr,
12543                                     Expr *RHSExpr){
12544   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12545   if (BinaryOperator::isBitwiseOp(Opc))
12546     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12547 
12548   // Diagnose "arg1 & arg2 | arg3"
12549   if ((Opc == BO_Or || Opc == BO_Xor) &&
12550       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12551     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12552     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12553   }
12554 
12555   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12556   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12557   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12558     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12559     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12560   }
12561 
12562   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12563       || Opc == BO_Shr) {
12564     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12565     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12566     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12567   }
12568 
12569   // Warn on overloaded shift operators and comparisons, such as:
12570   // cout << 5 == 4;
12571   if (BinaryOperator::isComparisonOp(Opc))
12572     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12573 }
12574 
12575 // Binary Operators.  'Tok' is the token for the operator.
12576 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12577                             tok::TokenKind Kind,
12578                             Expr *LHSExpr, Expr *RHSExpr) {
12579   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12580   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12581   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12582 
12583   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12584   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12585 
12586   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12587 }
12588 
12589 /// Build an overloaded binary operator expression in the given scope.
12590 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12591                                        BinaryOperatorKind Opc,
12592                                        Expr *LHS, Expr *RHS) {
12593   switch (Opc) {
12594   case BO_Assign:
12595   case BO_DivAssign:
12596   case BO_RemAssign:
12597   case BO_SubAssign:
12598   case BO_AndAssign:
12599   case BO_OrAssign:
12600   case BO_XorAssign:
12601     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12602     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12603     break;
12604   default:
12605     break;
12606   }
12607 
12608   // Find all of the overloaded operators visible from this
12609   // point. We perform both an operator-name lookup from the local
12610   // scope and an argument-dependent lookup based on the types of
12611   // the arguments.
12612   UnresolvedSet<16> Functions;
12613   OverloadedOperatorKind OverOp
12614     = BinaryOperator::getOverloadedOperator(Opc);
12615   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12616     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12617                                    RHS->getType(), Functions);
12618 
12619   // Build the (potentially-overloaded, potentially-dependent)
12620   // binary operation.
12621   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12622 }
12623 
12624 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12625                             BinaryOperatorKind Opc,
12626                             Expr *LHSExpr, Expr *RHSExpr) {
12627   ExprResult LHS, RHS;
12628   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12629   if (!LHS.isUsable() || !RHS.isUsable())
12630     return ExprError();
12631   LHSExpr = LHS.get();
12632   RHSExpr = RHS.get();
12633 
12634   // We want to end up calling one of checkPseudoObjectAssignment
12635   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12636   // both expressions are overloadable or either is type-dependent),
12637   // or CreateBuiltinBinOp (in any other case).  We also want to get
12638   // any placeholder types out of the way.
12639 
12640   // Handle pseudo-objects in the LHS.
12641   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12642     // Assignments with a pseudo-object l-value need special analysis.
12643     if (pty->getKind() == BuiltinType::PseudoObject &&
12644         BinaryOperator::isAssignmentOp(Opc))
12645       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12646 
12647     // Don't resolve overloads if the other type is overloadable.
12648     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12649       // We can't actually test that if we still have a placeholder,
12650       // though.  Fortunately, none of the exceptions we see in that
12651       // code below are valid when the LHS is an overload set.  Note
12652       // that an overload set can be dependently-typed, but it never
12653       // instantiates to having an overloadable type.
12654       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12655       if (resolvedRHS.isInvalid()) return ExprError();
12656       RHSExpr = resolvedRHS.get();
12657 
12658       if (RHSExpr->isTypeDependent() ||
12659           RHSExpr->getType()->isOverloadableType())
12660         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12661     }
12662 
12663     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12664     // template, diagnose the missing 'template' keyword instead of diagnosing
12665     // an invalid use of a bound member function.
12666     //
12667     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12668     // to C++1z [over.over]/1.4, but we already checked for that case above.
12669     if (Opc == BO_LT && inTemplateInstantiation() &&
12670         (pty->getKind() == BuiltinType::BoundMember ||
12671          pty->getKind() == BuiltinType::Overload)) {
12672       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12673       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12674           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12675             return isa<FunctionTemplateDecl>(ND);
12676           })) {
12677         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12678                                 : OE->getNameLoc(),
12679              diag::err_template_kw_missing)
12680           << OE->getName().getAsString() << "";
12681         return ExprError();
12682       }
12683     }
12684 
12685     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12686     if (LHS.isInvalid()) return ExprError();
12687     LHSExpr = LHS.get();
12688   }
12689 
12690   // Handle pseudo-objects in the RHS.
12691   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12692     // An overload in the RHS can potentially be resolved by the type
12693     // being assigned to.
12694     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12695       if (getLangOpts().CPlusPlus &&
12696           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12697            LHSExpr->getType()->isOverloadableType()))
12698         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12699 
12700       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12701     }
12702 
12703     // Don't resolve overloads if the other type is overloadable.
12704     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12705         LHSExpr->getType()->isOverloadableType())
12706       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12707 
12708     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12709     if (!resolvedRHS.isUsable()) return ExprError();
12710     RHSExpr = resolvedRHS.get();
12711   }
12712 
12713   if (getLangOpts().CPlusPlus) {
12714     // If either expression is type-dependent, always build an
12715     // overloaded op.
12716     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12717       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12718 
12719     // Otherwise, build an overloaded op if either expression has an
12720     // overloadable type.
12721     if (LHSExpr->getType()->isOverloadableType() ||
12722         RHSExpr->getType()->isOverloadableType())
12723       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12724   }
12725 
12726   // Build a built-in binary operation.
12727   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12728 }
12729 
12730 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12731   if (T.isNull() || T->isDependentType())
12732     return false;
12733 
12734   if (!T->isPromotableIntegerType())
12735     return true;
12736 
12737   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12738 }
12739 
12740 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12741                                       UnaryOperatorKind Opc,
12742                                       Expr *InputExpr) {
12743   ExprResult Input = InputExpr;
12744   ExprValueKind VK = VK_RValue;
12745   ExprObjectKind OK = OK_Ordinary;
12746   QualType resultType;
12747   bool CanOverflow = false;
12748 
12749   bool ConvertHalfVec = false;
12750   if (getLangOpts().OpenCL) {
12751     QualType Ty = InputExpr->getType();
12752     // The only legal unary operation for atomics is '&'.
12753     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12754     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12755     // only with a builtin functions and therefore should be disallowed here.
12756         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12757         || Ty->isBlockPointerType())) {
12758       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12759                        << InputExpr->getType()
12760                        << Input.get()->getSourceRange());
12761     }
12762   }
12763   switch (Opc) {
12764   case UO_PreInc:
12765   case UO_PreDec:
12766   case UO_PostInc:
12767   case UO_PostDec:
12768     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12769                                                 OpLoc,
12770                                                 Opc == UO_PreInc ||
12771                                                 Opc == UO_PostInc,
12772                                                 Opc == UO_PreInc ||
12773                                                 Opc == UO_PreDec);
12774     CanOverflow = isOverflowingIntegerType(Context, resultType);
12775     break;
12776   case UO_AddrOf:
12777     resultType = CheckAddressOfOperand(Input, OpLoc);
12778     RecordModifiableNonNullParam(*this, InputExpr);
12779     break;
12780   case UO_Deref: {
12781     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12782     if (Input.isInvalid()) return ExprError();
12783     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12784     break;
12785   }
12786   case UO_Plus:
12787   case UO_Minus:
12788     CanOverflow = Opc == UO_Minus &&
12789                   isOverflowingIntegerType(Context, Input.get()->getType());
12790     Input = UsualUnaryConversions(Input.get());
12791     if (Input.isInvalid()) return ExprError();
12792     // Unary plus and minus require promoting an operand of half vector to a
12793     // float vector and truncating the result back to a half vector. For now, we
12794     // do this only when HalfArgsAndReturns is set (that is, when the target is
12795     // arm or arm64).
12796     ConvertHalfVec =
12797         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12798 
12799     // If the operand is a half vector, promote it to a float vector.
12800     if (ConvertHalfVec)
12801       Input = convertVector(Input.get(), Context.FloatTy, *this);
12802     resultType = Input.get()->getType();
12803     if (resultType->isDependentType())
12804       break;
12805     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12806       break;
12807     else if (resultType->isVectorType() &&
12808              // The z vector extensions don't allow + or - with bool vectors.
12809              (!Context.getLangOpts().ZVector ||
12810               resultType->getAs<VectorType>()->getVectorKind() !=
12811               VectorType::AltiVecBool))
12812       break;
12813     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12814              Opc == UO_Plus &&
12815              resultType->isPointerType())
12816       break;
12817 
12818     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12819       << resultType << Input.get()->getSourceRange());
12820 
12821   case UO_Not: // bitwise complement
12822     Input = UsualUnaryConversions(Input.get());
12823     if (Input.isInvalid())
12824       return ExprError();
12825     resultType = Input.get()->getType();
12826 
12827     if (resultType->isDependentType())
12828       break;
12829     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12830     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12831       // C99 does not support '~' for complex conjugation.
12832       Diag(OpLoc, diag::ext_integer_complement_complex)
12833           << resultType << Input.get()->getSourceRange();
12834     else if (resultType->hasIntegerRepresentation())
12835       break;
12836     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12837       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12838       // on vector float types.
12839       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12840       if (!T->isIntegerType())
12841         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12842                           << resultType << Input.get()->getSourceRange());
12843     } else {
12844       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12845                        << resultType << Input.get()->getSourceRange());
12846     }
12847     break;
12848 
12849   case UO_LNot: // logical negation
12850     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12851     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12852     if (Input.isInvalid()) return ExprError();
12853     resultType = Input.get()->getType();
12854 
12855     // Though we still have to promote half FP to float...
12856     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12857       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12858       resultType = Context.FloatTy;
12859     }
12860 
12861     if (resultType->isDependentType())
12862       break;
12863     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12864       // C99 6.5.3.3p1: ok, fallthrough;
12865       if (Context.getLangOpts().CPlusPlus) {
12866         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12867         // operand contextually converted to bool.
12868         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12869                                   ScalarTypeToBooleanCastKind(resultType));
12870       } else if (Context.getLangOpts().OpenCL &&
12871                  Context.getLangOpts().OpenCLVersion < 120) {
12872         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12873         // operate on scalar float types.
12874         if (!resultType->isIntegerType() && !resultType->isPointerType())
12875           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12876                            << resultType << Input.get()->getSourceRange());
12877       }
12878     } else if (resultType->isExtVectorType()) {
12879       if (Context.getLangOpts().OpenCL &&
12880           Context.getLangOpts().OpenCLVersion < 120) {
12881         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12882         // operate on vector float types.
12883         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12884         if (!T->isIntegerType())
12885           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12886                            << resultType << Input.get()->getSourceRange());
12887       }
12888       // Vector logical not returns the signed variant of the operand type.
12889       resultType = GetSignedVectorType(resultType);
12890       break;
12891     } else {
12892       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12893       //        type in C++. We should allow that here too.
12894       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12895         << resultType << Input.get()->getSourceRange());
12896     }
12897 
12898     // LNot always has type int. C99 6.5.3.3p5.
12899     // In C++, it's bool. C++ 5.3.1p8
12900     resultType = Context.getLogicalOperationType();
12901     break;
12902   case UO_Real:
12903   case UO_Imag:
12904     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12905     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12906     // complex l-values to ordinary l-values and all other values to r-values.
12907     if (Input.isInvalid()) return ExprError();
12908     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12909       if (Input.get()->getValueKind() != VK_RValue &&
12910           Input.get()->getObjectKind() == OK_Ordinary)
12911         VK = Input.get()->getValueKind();
12912     } else if (!getLangOpts().CPlusPlus) {
12913       // In C, a volatile scalar is read by __imag. In C++, it is not.
12914       Input = DefaultLvalueConversion(Input.get());
12915     }
12916     break;
12917   case UO_Extension:
12918     resultType = Input.get()->getType();
12919     VK = Input.get()->getValueKind();
12920     OK = Input.get()->getObjectKind();
12921     break;
12922   case UO_Coawait:
12923     // It's unnecessary to represent the pass-through operator co_await in the
12924     // AST; just return the input expression instead.
12925     assert(!Input.get()->getType()->isDependentType() &&
12926                    "the co_await expression must be non-dependant before "
12927                    "building operator co_await");
12928     return Input;
12929   }
12930   if (resultType.isNull() || Input.isInvalid())
12931     return ExprError();
12932 
12933   // Check for array bounds violations in the operand of the UnaryOperator,
12934   // except for the '*' and '&' operators that have to be handled specially
12935   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12936   // that are explicitly defined as valid by the standard).
12937   if (Opc != UO_AddrOf && Opc != UO_Deref)
12938     CheckArrayAccess(Input.get());
12939 
12940   auto *UO = new (Context)
12941       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12942   // Convert the result back to a half vector.
12943   if (ConvertHalfVec)
12944     return convertVector(UO, Context.HalfTy, *this);
12945   return UO;
12946 }
12947 
12948 /// Determine whether the given expression is a qualified member
12949 /// access expression, of a form that could be turned into a pointer to member
12950 /// with the address-of operator.
12951 bool Sema::isQualifiedMemberAccess(Expr *E) {
12952   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12953     if (!DRE->getQualifier())
12954       return false;
12955 
12956     ValueDecl *VD = DRE->getDecl();
12957     if (!VD->isCXXClassMember())
12958       return false;
12959 
12960     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12961       return true;
12962     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12963       return Method->isInstance();
12964 
12965     return false;
12966   }
12967 
12968   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12969     if (!ULE->getQualifier())
12970       return false;
12971 
12972     for (NamedDecl *D : ULE->decls()) {
12973       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12974         if (Method->isInstance())
12975           return true;
12976       } else {
12977         // Overload set does not contain methods.
12978         break;
12979       }
12980     }
12981 
12982     return false;
12983   }
12984 
12985   return false;
12986 }
12987 
12988 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12989                               UnaryOperatorKind Opc, Expr *Input) {
12990   // First things first: handle placeholders so that the
12991   // overloaded-operator check considers the right type.
12992   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12993     // Increment and decrement of pseudo-object references.
12994     if (pty->getKind() == BuiltinType::PseudoObject &&
12995         UnaryOperator::isIncrementDecrementOp(Opc))
12996       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12997 
12998     // extension is always a builtin operator.
12999     if (Opc == UO_Extension)
13000       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13001 
13002     // & gets special logic for several kinds of placeholder.
13003     // The builtin code knows what to do.
13004     if (Opc == UO_AddrOf &&
13005         (pty->getKind() == BuiltinType::Overload ||
13006          pty->getKind() == BuiltinType::UnknownAny ||
13007          pty->getKind() == BuiltinType::BoundMember))
13008       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13009 
13010     // Anything else needs to be handled now.
13011     ExprResult Result = CheckPlaceholderExpr(Input);
13012     if (Result.isInvalid()) return ExprError();
13013     Input = Result.get();
13014   }
13015 
13016   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13017       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13018       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13019     // Find all of the overloaded operators visible from this
13020     // point. We perform both an operator-name lookup from the local
13021     // scope and an argument-dependent lookup based on the types of
13022     // the arguments.
13023     UnresolvedSet<16> Functions;
13024     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13025     if (S && OverOp != OO_None)
13026       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13027                                    Functions);
13028 
13029     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13030   }
13031 
13032   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13033 }
13034 
13035 // Unary Operators.  'Tok' is the token for the operator.
13036 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13037                               tok::TokenKind Op, Expr *Input) {
13038   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13039 }
13040 
13041 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13042 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13043                                 LabelDecl *TheDecl) {
13044   TheDecl->markUsed(Context);
13045   // Create the AST node.  The address of a label always has type 'void*'.
13046   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13047                                      Context.getPointerType(Context.VoidTy));
13048 }
13049 
13050 /// Given the last statement in a statement-expression, check whether
13051 /// the result is a producing expression (like a call to an
13052 /// ns_returns_retained function) and, if so, rebuild it to hoist the
13053 /// release out of the full-expression.  Otherwise, return null.
13054 /// Cannot fail.
13055 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
13056   // Should always be wrapped with one of these.
13057   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
13058   if (!cleanups) return nullptr;
13059 
13060   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
13061   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
13062     return nullptr;
13063 
13064   // Splice out the cast.  This shouldn't modify any interesting
13065   // features of the statement.
13066   Expr *producer = cast->getSubExpr();
13067   assert(producer->getType() == cast->getType());
13068   assert(producer->getValueKind() == cast->getValueKind());
13069   cleanups->setSubExpr(producer);
13070   return cleanups;
13071 }
13072 
13073 void Sema::ActOnStartStmtExpr() {
13074   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13075 }
13076 
13077 void Sema::ActOnStmtExprError() {
13078   // Note that function is also called by TreeTransform when leaving a
13079   // StmtExpr scope without rebuilding anything.
13080 
13081   DiscardCleanupsInEvaluationContext();
13082   PopExpressionEvaluationContext();
13083 }
13084 
13085 ExprResult
13086 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13087                     SourceLocation RPLoc) { // "({..})"
13088   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13089   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13090 
13091   if (hasAnyUnrecoverableErrorsInThisFunction())
13092     DiscardCleanupsInEvaluationContext();
13093   assert(!Cleanup.exprNeedsCleanups() &&
13094          "cleanups within StmtExpr not correctly bound!");
13095   PopExpressionEvaluationContext();
13096 
13097   // FIXME: there are a variety of strange constraints to enforce here, for
13098   // example, it is not possible to goto into a stmt expression apparently.
13099   // More semantic analysis is needed.
13100 
13101   // If there are sub-stmts in the compound stmt, take the type of the last one
13102   // as the type of the stmtexpr.
13103   QualType Ty = Context.VoidTy;
13104   bool StmtExprMayBindToTemp = false;
13105   if (!Compound->body_empty()) {
13106     Stmt *LastStmt = Compound->body_back();
13107     LabelStmt *LastLabelStmt = nullptr;
13108     // If LastStmt is a label, skip down through into the body.
13109     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
13110       LastLabelStmt = Label;
13111       LastStmt = Label->getSubStmt();
13112     }
13113 
13114     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
13115       // Do function/array conversion on the last expression, but not
13116       // lvalue-to-rvalue.  However, initialize an unqualified type.
13117       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
13118       if (LastExpr.isInvalid())
13119         return ExprError();
13120       Ty = LastExpr.get()->getType().getUnqualifiedType();
13121 
13122       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
13123         // In ARC, if the final expression ends in a consume, splice
13124         // the consume out and bind it later.  In the alternate case
13125         // (when dealing with a retainable type), the result
13126         // initialization will create a produce.  In both cases the
13127         // result will be +1, and we'll need to balance that out with
13128         // a bind.
13129         if (Expr *rebuiltLastStmt
13130               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
13131           LastExpr = rebuiltLastStmt;
13132         } else {
13133           LastExpr = PerformCopyInitialization(
13134               InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
13135               SourceLocation(), LastExpr);
13136         }
13137 
13138         if (LastExpr.isInvalid())
13139           return ExprError();
13140         if (LastExpr.get() != nullptr) {
13141           if (!LastLabelStmt)
13142             Compound->setLastStmt(LastExpr.get());
13143           else
13144             LastLabelStmt->setSubStmt(LastExpr.get());
13145           StmtExprMayBindToTemp = true;
13146         }
13147       }
13148     }
13149   }
13150 
13151   // FIXME: Check that expression type is complete/non-abstract; statement
13152   // expressions are not lvalues.
13153   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13154   if (StmtExprMayBindToTemp)
13155     return MaybeBindToTemporary(ResStmtExpr);
13156   return ResStmtExpr;
13157 }
13158 
13159 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13160                                       TypeSourceInfo *TInfo,
13161                                       ArrayRef<OffsetOfComponent> Components,
13162                                       SourceLocation RParenLoc) {
13163   QualType ArgTy = TInfo->getType();
13164   bool Dependent = ArgTy->isDependentType();
13165   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13166 
13167   // We must have at least one component that refers to the type, and the first
13168   // one is known to be a field designator.  Verify that the ArgTy represents
13169   // a struct/union/class.
13170   if (!Dependent && !ArgTy->isRecordType())
13171     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13172                        << ArgTy << TypeRange);
13173 
13174   // Type must be complete per C99 7.17p3 because a declaring a variable
13175   // with an incomplete type would be ill-formed.
13176   if (!Dependent
13177       && RequireCompleteType(BuiltinLoc, ArgTy,
13178                              diag::err_offsetof_incomplete_type, TypeRange))
13179     return ExprError();
13180 
13181   bool DidWarnAboutNonPOD = false;
13182   QualType CurrentType = ArgTy;
13183   SmallVector<OffsetOfNode, 4> Comps;
13184   SmallVector<Expr*, 4> Exprs;
13185   for (const OffsetOfComponent &OC : Components) {
13186     if (OC.isBrackets) {
13187       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13188       if (!CurrentType->isDependentType()) {
13189         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13190         if(!AT)
13191           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13192                            << CurrentType);
13193         CurrentType = AT->getElementType();
13194       } else
13195         CurrentType = Context.DependentTy;
13196 
13197       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13198       if (IdxRval.isInvalid())
13199         return ExprError();
13200       Expr *Idx = IdxRval.get();
13201 
13202       // The expression must be an integral expression.
13203       // FIXME: An integral constant expression?
13204       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13205           !Idx->getType()->isIntegerType())
13206         return ExprError(
13207             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13208             << Idx->getSourceRange());
13209 
13210       // Record this array index.
13211       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13212       Exprs.push_back(Idx);
13213       continue;
13214     }
13215 
13216     // Offset of a field.
13217     if (CurrentType->isDependentType()) {
13218       // We have the offset of a field, but we can't look into the dependent
13219       // type. Just record the identifier of the field.
13220       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13221       CurrentType = Context.DependentTy;
13222       continue;
13223     }
13224 
13225     // We need to have a complete type to look into.
13226     if (RequireCompleteType(OC.LocStart, CurrentType,
13227                             diag::err_offsetof_incomplete_type))
13228       return ExprError();
13229 
13230     // Look for the designated field.
13231     const RecordType *RC = CurrentType->getAs<RecordType>();
13232     if (!RC)
13233       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13234                        << CurrentType);
13235     RecordDecl *RD = RC->getDecl();
13236 
13237     // C++ [lib.support.types]p5:
13238     //   The macro offsetof accepts a restricted set of type arguments in this
13239     //   International Standard. type shall be a POD structure or a POD union
13240     //   (clause 9).
13241     // C++11 [support.types]p4:
13242     //   If type is not a standard-layout class (Clause 9), the results are
13243     //   undefined.
13244     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13245       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13246       unsigned DiagID =
13247         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13248                             : diag::ext_offsetof_non_pod_type;
13249 
13250       if (!IsSafe && !DidWarnAboutNonPOD &&
13251           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13252                               PDiag(DiagID)
13253                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13254                               << CurrentType))
13255         DidWarnAboutNonPOD = true;
13256     }
13257 
13258     // Look for the field.
13259     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13260     LookupQualifiedName(R, RD);
13261     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13262     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13263     if (!MemberDecl) {
13264       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13265         MemberDecl = IndirectMemberDecl->getAnonField();
13266     }
13267 
13268     if (!MemberDecl)
13269       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13270                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13271                                                               OC.LocEnd));
13272 
13273     // C99 7.17p3:
13274     //   (If the specified member is a bit-field, the behavior is undefined.)
13275     //
13276     // We diagnose this as an error.
13277     if (MemberDecl->isBitField()) {
13278       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13279         << MemberDecl->getDeclName()
13280         << SourceRange(BuiltinLoc, RParenLoc);
13281       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13282       return ExprError();
13283     }
13284 
13285     RecordDecl *Parent = MemberDecl->getParent();
13286     if (IndirectMemberDecl)
13287       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13288 
13289     // If the member was found in a base class, introduce OffsetOfNodes for
13290     // the base class indirections.
13291     CXXBasePaths Paths;
13292     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13293                       Paths)) {
13294       if (Paths.getDetectedVirtual()) {
13295         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13296           << MemberDecl->getDeclName()
13297           << SourceRange(BuiltinLoc, RParenLoc);
13298         return ExprError();
13299       }
13300 
13301       CXXBasePath &Path = Paths.front();
13302       for (const CXXBasePathElement &B : Path)
13303         Comps.push_back(OffsetOfNode(B.Base));
13304     }
13305 
13306     if (IndirectMemberDecl) {
13307       for (auto *FI : IndirectMemberDecl->chain()) {
13308         assert(isa<FieldDecl>(FI));
13309         Comps.push_back(OffsetOfNode(OC.LocStart,
13310                                      cast<FieldDecl>(FI), OC.LocEnd));
13311       }
13312     } else
13313       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13314 
13315     CurrentType = MemberDecl->getType().getNonReferenceType();
13316   }
13317 
13318   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13319                               Comps, Exprs, RParenLoc);
13320 }
13321 
13322 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13323                                       SourceLocation BuiltinLoc,
13324                                       SourceLocation TypeLoc,
13325                                       ParsedType ParsedArgTy,
13326                                       ArrayRef<OffsetOfComponent> Components,
13327                                       SourceLocation RParenLoc) {
13328 
13329   TypeSourceInfo *ArgTInfo;
13330   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13331   if (ArgTy.isNull())
13332     return ExprError();
13333 
13334   if (!ArgTInfo)
13335     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13336 
13337   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13338 }
13339 
13340 
13341 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13342                                  Expr *CondExpr,
13343                                  Expr *LHSExpr, Expr *RHSExpr,
13344                                  SourceLocation RPLoc) {
13345   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13346 
13347   ExprValueKind VK = VK_RValue;
13348   ExprObjectKind OK = OK_Ordinary;
13349   QualType resType;
13350   bool ValueDependent = false;
13351   bool CondIsTrue = false;
13352   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13353     resType = Context.DependentTy;
13354     ValueDependent = true;
13355   } else {
13356     // The conditional expression is required to be a constant expression.
13357     llvm::APSInt condEval(32);
13358     ExprResult CondICE
13359       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13360           diag::err_typecheck_choose_expr_requires_constant, false);
13361     if (CondICE.isInvalid())
13362       return ExprError();
13363     CondExpr = CondICE.get();
13364     CondIsTrue = condEval.getZExtValue();
13365 
13366     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13367     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13368 
13369     resType = ActiveExpr->getType();
13370     ValueDependent = ActiveExpr->isValueDependent();
13371     VK = ActiveExpr->getValueKind();
13372     OK = ActiveExpr->getObjectKind();
13373   }
13374 
13375   return new (Context)
13376       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13377                  CondIsTrue, resType->isDependentType(), ValueDependent);
13378 }
13379 
13380 //===----------------------------------------------------------------------===//
13381 // Clang Extensions.
13382 //===----------------------------------------------------------------------===//
13383 
13384 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13385 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13386   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13387 
13388   if (LangOpts.CPlusPlus) {
13389     Decl *ManglingContextDecl;
13390     if (MangleNumberingContext *MCtx =
13391             getCurrentMangleNumberContext(Block->getDeclContext(),
13392                                           ManglingContextDecl)) {
13393       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13394       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13395     }
13396   }
13397 
13398   PushBlockScope(CurScope, Block);
13399   CurContext->addDecl(Block);
13400   if (CurScope)
13401     PushDeclContext(CurScope, Block);
13402   else
13403     CurContext = Block;
13404 
13405   getCurBlock()->HasImplicitReturnType = true;
13406 
13407   // Enter a new evaluation context to insulate the block from any
13408   // cleanups from the enclosing full-expression.
13409   PushExpressionEvaluationContext(
13410       ExpressionEvaluationContext::PotentiallyEvaluated);
13411 }
13412 
13413 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13414                                Scope *CurScope) {
13415   assert(ParamInfo.getIdentifier() == nullptr &&
13416          "block-id should have no identifier!");
13417   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13418   BlockScopeInfo *CurBlock = getCurBlock();
13419 
13420   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13421   QualType T = Sig->getType();
13422 
13423   // FIXME: We should allow unexpanded parameter packs here, but that would,
13424   // in turn, make the block expression contain unexpanded parameter packs.
13425   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13426     // Drop the parameters.
13427     FunctionProtoType::ExtProtoInfo EPI;
13428     EPI.HasTrailingReturn = false;
13429     EPI.TypeQuals |= DeclSpec::TQ_const;
13430     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13431     Sig = Context.getTrivialTypeSourceInfo(T);
13432   }
13433 
13434   // GetTypeForDeclarator always produces a function type for a block
13435   // literal signature.  Furthermore, it is always a FunctionProtoType
13436   // unless the function was written with a typedef.
13437   assert(T->isFunctionType() &&
13438          "GetTypeForDeclarator made a non-function block signature");
13439 
13440   // Look for an explicit signature in that function type.
13441   FunctionProtoTypeLoc ExplicitSignature;
13442 
13443   if ((ExplicitSignature =
13444            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13445 
13446     // Check whether that explicit signature was synthesized by
13447     // GetTypeForDeclarator.  If so, don't save that as part of the
13448     // written signature.
13449     if (ExplicitSignature.getLocalRangeBegin() ==
13450         ExplicitSignature.getLocalRangeEnd()) {
13451       // This would be much cheaper if we stored TypeLocs instead of
13452       // TypeSourceInfos.
13453       TypeLoc Result = ExplicitSignature.getReturnLoc();
13454       unsigned Size = Result.getFullDataSize();
13455       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13456       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13457 
13458       ExplicitSignature = FunctionProtoTypeLoc();
13459     }
13460   }
13461 
13462   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13463   CurBlock->FunctionType = T;
13464 
13465   const FunctionType *Fn = T->getAs<FunctionType>();
13466   QualType RetTy = Fn->getReturnType();
13467   bool isVariadic =
13468     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13469 
13470   CurBlock->TheDecl->setIsVariadic(isVariadic);
13471 
13472   // Context.DependentTy is used as a placeholder for a missing block
13473   // return type.  TODO:  what should we do with declarators like:
13474   //   ^ * { ... }
13475   // If the answer is "apply template argument deduction"....
13476   if (RetTy != Context.DependentTy) {
13477     CurBlock->ReturnType = RetTy;
13478     CurBlock->TheDecl->setBlockMissingReturnType(false);
13479     CurBlock->HasImplicitReturnType = false;
13480   }
13481 
13482   // Push block parameters from the declarator if we had them.
13483   SmallVector<ParmVarDecl*, 8> Params;
13484   if (ExplicitSignature) {
13485     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13486       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13487       if (Param->getIdentifier() == nullptr &&
13488           !Param->isImplicit() &&
13489           !Param->isInvalidDecl() &&
13490           !getLangOpts().CPlusPlus)
13491         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13492       Params.push_back(Param);
13493     }
13494 
13495   // Fake up parameter variables if we have a typedef, like
13496   //   ^ fntype { ... }
13497   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13498     for (const auto &I : Fn->param_types()) {
13499       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13500           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13501       Params.push_back(Param);
13502     }
13503   }
13504 
13505   // Set the parameters on the block decl.
13506   if (!Params.empty()) {
13507     CurBlock->TheDecl->setParams(Params);
13508     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13509                              /*CheckParameterNames=*/false);
13510   }
13511 
13512   // Finally we can process decl attributes.
13513   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13514 
13515   // Put the parameter variables in scope.
13516   for (auto AI : CurBlock->TheDecl->parameters()) {
13517     AI->setOwningFunction(CurBlock->TheDecl);
13518 
13519     // If this has an identifier, add it to the scope stack.
13520     if (AI->getIdentifier()) {
13521       CheckShadow(CurBlock->TheScope, AI);
13522 
13523       PushOnScopeChains(AI, CurBlock->TheScope);
13524     }
13525   }
13526 }
13527 
13528 /// ActOnBlockError - If there is an error parsing a block, this callback
13529 /// is invoked to pop the information about the block from the action impl.
13530 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13531   // Leave the expression-evaluation context.
13532   DiscardCleanupsInEvaluationContext();
13533   PopExpressionEvaluationContext();
13534 
13535   // Pop off CurBlock, handle nested blocks.
13536   PopDeclContext();
13537   PopFunctionScopeInfo();
13538 }
13539 
13540 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13541 /// literal was successfully completed.  ^(int x){...}
13542 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13543                                     Stmt *Body, Scope *CurScope) {
13544   // If blocks are disabled, emit an error.
13545   if (!LangOpts.Blocks)
13546     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13547 
13548   // Leave the expression-evaluation context.
13549   if (hasAnyUnrecoverableErrorsInThisFunction())
13550     DiscardCleanupsInEvaluationContext();
13551   assert(!Cleanup.exprNeedsCleanups() &&
13552          "cleanups within block not correctly bound!");
13553   PopExpressionEvaluationContext();
13554 
13555   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13556   BlockDecl *BD = BSI->TheDecl;
13557 
13558   if (BSI->HasImplicitReturnType)
13559     deduceClosureReturnType(*BSI);
13560 
13561   PopDeclContext();
13562 
13563   QualType RetTy = Context.VoidTy;
13564   if (!BSI->ReturnType.isNull())
13565     RetTy = BSI->ReturnType;
13566 
13567   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13568   QualType BlockTy;
13569 
13570   // Set the captured variables on the block.
13571   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13572   SmallVector<BlockDecl::Capture, 4> Captures;
13573   for (Capture &Cap : BSI->Captures) {
13574     if (Cap.isThisCapture())
13575       continue;
13576     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13577                               Cap.isNested(), Cap.getInitExpr());
13578     Captures.push_back(NewCap);
13579   }
13580   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13581 
13582   // If the user wrote a function type in some form, try to use that.
13583   if (!BSI->FunctionType.isNull()) {
13584     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13585 
13586     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13587     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13588 
13589     // Turn protoless block types into nullary block types.
13590     if (isa<FunctionNoProtoType>(FTy)) {
13591       FunctionProtoType::ExtProtoInfo EPI;
13592       EPI.ExtInfo = Ext;
13593       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13594 
13595     // Otherwise, if we don't need to change anything about the function type,
13596     // preserve its sugar structure.
13597     } else if (FTy->getReturnType() == RetTy &&
13598                (!NoReturn || FTy->getNoReturnAttr())) {
13599       BlockTy = BSI->FunctionType;
13600 
13601     // Otherwise, make the minimal modifications to the function type.
13602     } else {
13603       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13604       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13605       EPI.TypeQuals = 0; // FIXME: silently?
13606       EPI.ExtInfo = Ext;
13607       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13608     }
13609 
13610   // If we don't have a function type, just build one from nothing.
13611   } else {
13612     FunctionProtoType::ExtProtoInfo EPI;
13613     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13614     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13615   }
13616 
13617   DiagnoseUnusedParameters(BD->parameters());
13618   BlockTy = Context.getBlockPointerType(BlockTy);
13619 
13620   // If needed, diagnose invalid gotos and switches in the block.
13621   if (getCurFunction()->NeedsScopeChecking() &&
13622       !PP.isCodeCompletionEnabled())
13623     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13624 
13625   BD->setBody(cast<CompoundStmt>(Body));
13626 
13627   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13628     DiagnoseUnguardedAvailabilityViolations(BD);
13629 
13630   // Try to apply the named return value optimization. We have to check again
13631   // if we can do this, though, because blocks keep return statements around
13632   // to deduce an implicit return type.
13633   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13634       !BD->isDependentContext())
13635     computeNRVO(Body, BSI);
13636 
13637   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13638   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13639   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13640 
13641   // If the block isn't obviously global, i.e. it captures anything at
13642   // all, then we need to do a few things in the surrounding context:
13643   if (Result->getBlockDecl()->hasCaptures()) {
13644     // First, this expression has a new cleanup object.
13645     ExprCleanupObjects.push_back(Result->getBlockDecl());
13646     Cleanup.setExprNeedsCleanups(true);
13647 
13648     // It also gets a branch-protected scope if any of the captured
13649     // variables needs destruction.
13650     for (const auto &CI : Result->getBlockDecl()->captures()) {
13651       const VarDecl *var = CI.getVariable();
13652       if (var->getType().isDestructedType() != QualType::DK_none) {
13653         setFunctionHasBranchProtectedScope();
13654         break;
13655       }
13656     }
13657   }
13658 
13659   if (getCurFunction())
13660     getCurFunction()->addBlock(BD);
13661 
13662   return Result;
13663 }
13664 
13665 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13666                             SourceLocation RPLoc) {
13667   TypeSourceInfo *TInfo;
13668   GetTypeFromParser(Ty, &TInfo);
13669   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13670 }
13671 
13672 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13673                                 Expr *E, TypeSourceInfo *TInfo,
13674                                 SourceLocation RPLoc) {
13675   Expr *OrigExpr = E;
13676   bool IsMS = false;
13677 
13678   // CUDA device code does not support varargs.
13679   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13680     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13681       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13682       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13683         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13684     }
13685   }
13686 
13687   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13688   // as Microsoft ABI on an actual Microsoft platform, where
13689   // __builtin_ms_va_list and __builtin_va_list are the same.)
13690   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13691       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13692     QualType MSVaListType = Context.getBuiltinMSVaListType();
13693     if (Context.hasSameType(MSVaListType, E->getType())) {
13694       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13695         return ExprError();
13696       IsMS = true;
13697     }
13698   }
13699 
13700   // Get the va_list type
13701   QualType VaListType = Context.getBuiltinVaListType();
13702   if (!IsMS) {
13703     if (VaListType->isArrayType()) {
13704       // Deal with implicit array decay; for example, on x86-64,
13705       // va_list is an array, but it's supposed to decay to
13706       // a pointer for va_arg.
13707       VaListType = Context.getArrayDecayedType(VaListType);
13708       // Make sure the input expression also decays appropriately.
13709       ExprResult Result = UsualUnaryConversions(E);
13710       if (Result.isInvalid())
13711         return ExprError();
13712       E = Result.get();
13713     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13714       // If va_list is a record type and we are compiling in C++ mode,
13715       // check the argument using reference binding.
13716       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13717           Context, Context.getLValueReferenceType(VaListType), false);
13718       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13719       if (Init.isInvalid())
13720         return ExprError();
13721       E = Init.getAs<Expr>();
13722     } else {
13723       // Otherwise, the va_list argument must be an l-value because
13724       // it is modified by va_arg.
13725       if (!E->isTypeDependent() &&
13726           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13727         return ExprError();
13728     }
13729   }
13730 
13731   if (!IsMS && !E->isTypeDependent() &&
13732       !Context.hasSameType(VaListType, E->getType()))
13733     return ExprError(
13734         Diag(E->getBeginLoc(),
13735              diag::err_first_argument_to_va_arg_not_of_type_va_list)
13736         << OrigExpr->getType() << E->getSourceRange());
13737 
13738   if (!TInfo->getType()->isDependentType()) {
13739     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13740                             diag::err_second_parameter_to_va_arg_incomplete,
13741                             TInfo->getTypeLoc()))
13742       return ExprError();
13743 
13744     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13745                                TInfo->getType(),
13746                                diag::err_second_parameter_to_va_arg_abstract,
13747                                TInfo->getTypeLoc()))
13748       return ExprError();
13749 
13750     if (!TInfo->getType().isPODType(Context)) {
13751       Diag(TInfo->getTypeLoc().getBeginLoc(),
13752            TInfo->getType()->isObjCLifetimeType()
13753              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13754              : diag::warn_second_parameter_to_va_arg_not_pod)
13755         << TInfo->getType()
13756         << TInfo->getTypeLoc().getSourceRange();
13757     }
13758 
13759     // Check for va_arg where arguments of the given type will be promoted
13760     // (i.e. this va_arg is guaranteed to have undefined behavior).
13761     QualType PromoteType;
13762     if (TInfo->getType()->isPromotableIntegerType()) {
13763       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13764       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13765         PromoteType = QualType();
13766     }
13767     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13768       PromoteType = Context.DoubleTy;
13769     if (!PromoteType.isNull())
13770       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13771                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13772                           << TInfo->getType()
13773                           << PromoteType
13774                           << TInfo->getTypeLoc().getSourceRange());
13775   }
13776 
13777   QualType T = TInfo->getType().getNonLValueExprType(Context);
13778   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13779 }
13780 
13781 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13782   // The type of __null will be int or long, depending on the size of
13783   // pointers on the target.
13784   QualType Ty;
13785   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13786   if (pw == Context.getTargetInfo().getIntWidth())
13787     Ty = Context.IntTy;
13788   else if (pw == Context.getTargetInfo().getLongWidth())
13789     Ty = Context.LongTy;
13790   else if (pw == Context.getTargetInfo().getLongLongWidth())
13791     Ty = Context.LongLongTy;
13792   else {
13793     llvm_unreachable("I don't know size of pointer!");
13794   }
13795 
13796   return new (Context) GNUNullExpr(Ty, TokenLoc);
13797 }
13798 
13799 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13800                                               bool Diagnose) {
13801   if (!getLangOpts().ObjC)
13802     return false;
13803 
13804   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13805   if (!PT)
13806     return false;
13807 
13808   if (!PT->isObjCIdType()) {
13809     // Check if the destination is the 'NSString' interface.
13810     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13811     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13812       return false;
13813   }
13814 
13815   // Ignore any parens, implicit casts (should only be
13816   // array-to-pointer decays), and not-so-opaque values.  The last is
13817   // important for making this trigger for property assignments.
13818   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13819   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13820     if (OV->getSourceExpr())
13821       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13822 
13823   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13824   if (!SL || !SL->isAscii())
13825     return false;
13826   if (Diagnose) {
13827     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
13828         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
13829     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
13830   }
13831   return true;
13832 }
13833 
13834 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13835                                               const Expr *SrcExpr) {
13836   if (!DstType->isFunctionPointerType() ||
13837       !SrcExpr->getType()->isFunctionType())
13838     return false;
13839 
13840   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13841   if (!DRE)
13842     return false;
13843 
13844   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13845   if (!FD)
13846     return false;
13847 
13848   return !S.checkAddressOfFunctionIsAvailable(FD,
13849                                               /*Complain=*/true,
13850                                               SrcExpr->getBeginLoc());
13851 }
13852 
13853 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13854                                     SourceLocation Loc,
13855                                     QualType DstType, QualType SrcType,
13856                                     Expr *SrcExpr, AssignmentAction Action,
13857                                     bool *Complained) {
13858   if (Complained)
13859     *Complained = false;
13860 
13861   // Decode the result (notice that AST's are still created for extensions).
13862   bool CheckInferredResultType = false;
13863   bool isInvalid = false;
13864   unsigned DiagKind = 0;
13865   FixItHint Hint;
13866   ConversionFixItGenerator ConvHints;
13867   bool MayHaveConvFixit = false;
13868   bool MayHaveFunctionDiff = false;
13869   const ObjCInterfaceDecl *IFace = nullptr;
13870   const ObjCProtocolDecl *PDecl = nullptr;
13871 
13872   switch (ConvTy) {
13873   case Compatible:
13874       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13875       return false;
13876 
13877   case PointerToInt:
13878     DiagKind = diag::ext_typecheck_convert_pointer_int;
13879     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13880     MayHaveConvFixit = true;
13881     break;
13882   case IntToPointer:
13883     DiagKind = diag::ext_typecheck_convert_int_pointer;
13884     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13885     MayHaveConvFixit = true;
13886     break;
13887   case IncompatiblePointer:
13888     if (Action == AA_Passing_CFAudited)
13889       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13890     else if (SrcType->isFunctionPointerType() &&
13891              DstType->isFunctionPointerType())
13892       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13893     else
13894       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13895 
13896     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13897       SrcType->isObjCObjectPointerType();
13898     if (Hint.isNull() && !CheckInferredResultType) {
13899       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13900     }
13901     else if (CheckInferredResultType) {
13902       SrcType = SrcType.getUnqualifiedType();
13903       DstType = DstType.getUnqualifiedType();
13904     }
13905     MayHaveConvFixit = true;
13906     break;
13907   case IncompatiblePointerSign:
13908     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13909     break;
13910   case FunctionVoidPointer:
13911     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13912     break;
13913   case IncompatiblePointerDiscardsQualifiers: {
13914     // Perform array-to-pointer decay if necessary.
13915     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13916 
13917     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13918     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13919     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13920       DiagKind = diag::err_typecheck_incompatible_address_space;
13921       break;
13922 
13923     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13924       DiagKind = diag::err_typecheck_incompatible_ownership;
13925       break;
13926     }
13927 
13928     llvm_unreachable("unknown error case for discarding qualifiers!");
13929     // fallthrough
13930   }
13931   case CompatiblePointerDiscardsQualifiers:
13932     // If the qualifiers lost were because we were applying the
13933     // (deprecated) C++ conversion from a string literal to a char*
13934     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13935     // Ideally, this check would be performed in
13936     // checkPointerTypesForAssignment. However, that would require a
13937     // bit of refactoring (so that the second argument is an
13938     // expression, rather than a type), which should be done as part
13939     // of a larger effort to fix checkPointerTypesForAssignment for
13940     // C++ semantics.
13941     if (getLangOpts().CPlusPlus &&
13942         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13943       return false;
13944     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13945     break;
13946   case IncompatibleNestedPointerQualifiers:
13947     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13948     break;
13949   case IntToBlockPointer:
13950     DiagKind = diag::err_int_to_block_pointer;
13951     break;
13952   case IncompatibleBlockPointer:
13953     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13954     break;
13955   case IncompatibleObjCQualifiedId: {
13956     if (SrcType->isObjCQualifiedIdType()) {
13957       const ObjCObjectPointerType *srcOPT =
13958                 SrcType->getAs<ObjCObjectPointerType>();
13959       for (auto *srcProto : srcOPT->quals()) {
13960         PDecl = srcProto;
13961         break;
13962       }
13963       if (const ObjCInterfaceType *IFaceT =
13964             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13965         IFace = IFaceT->getDecl();
13966     }
13967     else if (DstType->isObjCQualifiedIdType()) {
13968       const ObjCObjectPointerType *dstOPT =
13969         DstType->getAs<ObjCObjectPointerType>();
13970       for (auto *dstProto : dstOPT->quals()) {
13971         PDecl = dstProto;
13972         break;
13973       }
13974       if (const ObjCInterfaceType *IFaceT =
13975             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13976         IFace = IFaceT->getDecl();
13977     }
13978     DiagKind = diag::warn_incompatible_qualified_id;
13979     break;
13980   }
13981   case IncompatibleVectors:
13982     DiagKind = diag::warn_incompatible_vectors;
13983     break;
13984   case IncompatibleObjCWeakRef:
13985     DiagKind = diag::err_arc_weak_unavailable_assign;
13986     break;
13987   case Incompatible:
13988     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13989       if (Complained)
13990         *Complained = true;
13991       return true;
13992     }
13993 
13994     DiagKind = diag::err_typecheck_convert_incompatible;
13995     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13996     MayHaveConvFixit = true;
13997     isInvalid = true;
13998     MayHaveFunctionDiff = true;
13999     break;
14000   }
14001 
14002   QualType FirstType, SecondType;
14003   switch (Action) {
14004   case AA_Assigning:
14005   case AA_Initializing:
14006     // The destination type comes first.
14007     FirstType = DstType;
14008     SecondType = SrcType;
14009     break;
14010 
14011   case AA_Returning:
14012   case AA_Passing:
14013   case AA_Passing_CFAudited:
14014   case AA_Converting:
14015   case AA_Sending:
14016   case AA_Casting:
14017     // The source type comes first.
14018     FirstType = SrcType;
14019     SecondType = DstType;
14020     break;
14021   }
14022 
14023   PartialDiagnostic FDiag = PDiag(DiagKind);
14024   if (Action == AA_Passing_CFAudited)
14025     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14026   else
14027     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14028 
14029   // If we can fix the conversion, suggest the FixIts.
14030   assert(ConvHints.isNull() || Hint.isNull());
14031   if (!ConvHints.isNull()) {
14032     for (FixItHint &H : ConvHints.Hints)
14033       FDiag << H;
14034   } else {
14035     FDiag << Hint;
14036   }
14037   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14038 
14039   if (MayHaveFunctionDiff)
14040     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14041 
14042   Diag(Loc, FDiag);
14043   if (DiagKind == diag::warn_incompatible_qualified_id &&
14044       PDecl && IFace && !IFace->hasDefinition())
14045       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14046         << IFace << PDecl;
14047 
14048   if (SecondType == Context.OverloadTy)
14049     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14050                               FirstType, /*TakingAddress=*/true);
14051 
14052   if (CheckInferredResultType)
14053     EmitRelatedResultTypeNote(SrcExpr);
14054 
14055   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14056     EmitRelatedResultTypeNoteForReturn(DstType);
14057 
14058   if (Complained)
14059     *Complained = true;
14060   return isInvalid;
14061 }
14062 
14063 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14064                                                  llvm::APSInt *Result) {
14065   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14066   public:
14067     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14068       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14069     }
14070   } Diagnoser;
14071 
14072   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14073 }
14074 
14075 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14076                                                  llvm::APSInt *Result,
14077                                                  unsigned DiagID,
14078                                                  bool AllowFold) {
14079   class IDDiagnoser : public VerifyICEDiagnoser {
14080     unsigned DiagID;
14081 
14082   public:
14083     IDDiagnoser(unsigned DiagID)
14084       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14085 
14086     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14087       S.Diag(Loc, DiagID) << SR;
14088     }
14089   } Diagnoser(DiagID);
14090 
14091   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14092 }
14093 
14094 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14095                                             SourceRange SR) {
14096   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14097 }
14098 
14099 ExprResult
14100 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14101                                       VerifyICEDiagnoser &Diagnoser,
14102                                       bool AllowFold) {
14103   SourceLocation DiagLoc = E->getBeginLoc();
14104 
14105   if (getLangOpts().CPlusPlus11) {
14106     // C++11 [expr.const]p5:
14107     //   If an expression of literal class type is used in a context where an
14108     //   integral constant expression is required, then that class type shall
14109     //   have a single non-explicit conversion function to an integral or
14110     //   unscoped enumeration type
14111     ExprResult Converted;
14112     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14113     public:
14114       CXX11ConvertDiagnoser(bool Silent)
14115           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14116                                 Silent, true) {}
14117 
14118       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14119                                            QualType T) override {
14120         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14121       }
14122 
14123       SemaDiagnosticBuilder diagnoseIncomplete(
14124           Sema &S, SourceLocation Loc, QualType T) override {
14125         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14126       }
14127 
14128       SemaDiagnosticBuilder diagnoseExplicitConv(
14129           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14130         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14131       }
14132 
14133       SemaDiagnosticBuilder noteExplicitConv(
14134           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14135         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14136                  << ConvTy->isEnumeralType() << ConvTy;
14137       }
14138 
14139       SemaDiagnosticBuilder diagnoseAmbiguous(
14140           Sema &S, SourceLocation Loc, QualType T) override {
14141         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14142       }
14143 
14144       SemaDiagnosticBuilder noteAmbiguous(
14145           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14146         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14147                  << ConvTy->isEnumeralType() << ConvTy;
14148       }
14149 
14150       SemaDiagnosticBuilder diagnoseConversion(
14151           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14152         llvm_unreachable("conversion functions are permitted");
14153       }
14154     } ConvertDiagnoser(Diagnoser.Suppress);
14155 
14156     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14157                                                     ConvertDiagnoser);
14158     if (Converted.isInvalid())
14159       return Converted;
14160     E = Converted.get();
14161     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14162       return ExprError();
14163   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14164     // An ICE must be of integral or unscoped enumeration type.
14165     if (!Diagnoser.Suppress)
14166       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14167     return ExprError();
14168   }
14169 
14170   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14171   // in the non-ICE case.
14172   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14173     if (Result)
14174       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14175     return new (Context) ConstantExpr(E);
14176   }
14177 
14178   Expr::EvalResult EvalResult;
14179   SmallVector<PartialDiagnosticAt, 8> Notes;
14180   EvalResult.Diag = &Notes;
14181 
14182   // Try to evaluate the expression, and produce diagnostics explaining why it's
14183   // not a constant expression as a side-effect.
14184   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14185                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14186 
14187   // In C++11, we can rely on diagnostics being produced for any expression
14188   // which is not a constant expression. If no diagnostics were produced, then
14189   // this is a constant expression.
14190   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14191     if (Result)
14192       *Result = EvalResult.Val.getInt();
14193     return new (Context) ConstantExpr(E);
14194   }
14195 
14196   // If our only note is the usual "invalid subexpression" note, just point
14197   // the caret at its location rather than producing an essentially
14198   // redundant note.
14199   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14200         diag::note_invalid_subexpr_in_const_expr) {
14201     DiagLoc = Notes[0].first;
14202     Notes.clear();
14203   }
14204 
14205   if (!Folded || !AllowFold) {
14206     if (!Diagnoser.Suppress) {
14207       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14208       for (const PartialDiagnosticAt &Note : Notes)
14209         Diag(Note.first, Note.second);
14210     }
14211 
14212     return ExprError();
14213   }
14214 
14215   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14216   for (const PartialDiagnosticAt &Note : Notes)
14217     Diag(Note.first, Note.second);
14218 
14219   if (Result)
14220     *Result = EvalResult.Val.getInt();
14221   return new (Context) ConstantExpr(E);
14222 }
14223 
14224 namespace {
14225   // Handle the case where we conclude a expression which we speculatively
14226   // considered to be unevaluated is actually evaluated.
14227   class TransformToPE : public TreeTransform<TransformToPE> {
14228     typedef TreeTransform<TransformToPE> BaseTransform;
14229 
14230   public:
14231     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14232 
14233     // Make sure we redo semantic analysis
14234     bool AlwaysRebuild() { return true; }
14235 
14236     // Make sure we handle LabelStmts correctly.
14237     // FIXME: This does the right thing, but maybe we need a more general
14238     // fix to TreeTransform?
14239     StmtResult TransformLabelStmt(LabelStmt *S) {
14240       S->getDecl()->setStmt(nullptr);
14241       return BaseTransform::TransformLabelStmt(S);
14242     }
14243 
14244     // We need to special-case DeclRefExprs referring to FieldDecls which
14245     // are not part of a member pointer formation; normal TreeTransforming
14246     // doesn't catch this case because of the way we represent them in the AST.
14247     // FIXME: This is a bit ugly; is it really the best way to handle this
14248     // case?
14249     //
14250     // Error on DeclRefExprs referring to FieldDecls.
14251     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14252       if (isa<FieldDecl>(E->getDecl()) &&
14253           !SemaRef.isUnevaluatedContext())
14254         return SemaRef.Diag(E->getLocation(),
14255                             diag::err_invalid_non_static_member_use)
14256             << E->getDecl() << E->getSourceRange();
14257 
14258       return BaseTransform::TransformDeclRefExpr(E);
14259     }
14260 
14261     // Exception: filter out member pointer formation
14262     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14263       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14264         return E;
14265 
14266       return BaseTransform::TransformUnaryOperator(E);
14267     }
14268 
14269     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14270       // Lambdas never need to be transformed.
14271       return E;
14272     }
14273   };
14274 }
14275 
14276 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14277   assert(isUnevaluatedContext() &&
14278          "Should only transform unevaluated expressions");
14279   ExprEvalContexts.back().Context =
14280       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14281   if (isUnevaluatedContext())
14282     return E;
14283   return TransformToPE(*this).TransformExpr(E);
14284 }
14285 
14286 void
14287 Sema::PushExpressionEvaluationContext(
14288     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14289     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14290   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14291                                 LambdaContextDecl, ExprContext);
14292   Cleanup.reset();
14293   if (!MaybeODRUseExprs.empty())
14294     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14295 }
14296 
14297 void
14298 Sema::PushExpressionEvaluationContext(
14299     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14300     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14301   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14302   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14303 }
14304 
14305 void Sema::PopExpressionEvaluationContext() {
14306   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14307   unsigned NumTypos = Rec.NumTypos;
14308 
14309   if (!Rec.Lambdas.empty()) {
14310     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14311     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14312         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14313       unsigned D;
14314       if (Rec.isUnevaluated()) {
14315         // C++11 [expr.prim.lambda]p2:
14316         //   A lambda-expression shall not appear in an unevaluated operand
14317         //   (Clause 5).
14318         D = diag::err_lambda_unevaluated_operand;
14319       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14320         // C++1y [expr.const]p2:
14321         //   A conditional-expression e is a core constant expression unless the
14322         //   evaluation of e, following the rules of the abstract machine, would
14323         //   evaluate [...] a lambda-expression.
14324         D = diag::err_lambda_in_constant_expression;
14325       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14326         // C++17 [expr.prim.lamda]p2:
14327         // A lambda-expression shall not appear [...] in a template-argument.
14328         D = diag::err_lambda_in_invalid_context;
14329       } else
14330         llvm_unreachable("Couldn't infer lambda error message.");
14331 
14332       for (const auto *L : Rec.Lambdas)
14333         Diag(L->getBeginLoc(), D);
14334     } else {
14335       // Mark the capture expressions odr-used. This was deferred
14336       // during lambda expression creation.
14337       for (auto *Lambda : Rec.Lambdas) {
14338         for (auto *C : Lambda->capture_inits())
14339           MarkDeclarationsReferencedInExpr(C);
14340       }
14341     }
14342   }
14343 
14344   // When are coming out of an unevaluated context, clear out any
14345   // temporaries that we may have created as part of the evaluation of
14346   // the expression in that context: they aren't relevant because they
14347   // will never be constructed.
14348   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14349     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14350                              ExprCleanupObjects.end());
14351     Cleanup = Rec.ParentCleanup;
14352     CleanupVarDeclMarking();
14353     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14354   // Otherwise, merge the contexts together.
14355   } else {
14356     Cleanup.mergeFrom(Rec.ParentCleanup);
14357     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14358                             Rec.SavedMaybeODRUseExprs.end());
14359   }
14360 
14361   // Pop the current expression evaluation context off the stack.
14362   ExprEvalContexts.pop_back();
14363 
14364   if (!ExprEvalContexts.empty())
14365     ExprEvalContexts.back().NumTypos += NumTypos;
14366   else
14367     assert(NumTypos == 0 && "There are outstanding typos after popping the "
14368                             "last ExpressionEvaluationContextRecord");
14369 }
14370 
14371 void Sema::DiscardCleanupsInEvaluationContext() {
14372   ExprCleanupObjects.erase(
14373          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14374          ExprCleanupObjects.end());
14375   Cleanup.reset();
14376   MaybeODRUseExprs.clear();
14377 }
14378 
14379 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14380   if (!E->getType()->isVariablyModifiedType())
14381     return E;
14382   return TransformToPotentiallyEvaluated(E);
14383 }
14384 
14385 /// Are we within a context in which some evaluation could be performed (be it
14386 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14387 /// captured by C++'s idea of an "unevaluated context".
14388 static bool isEvaluatableContext(Sema &SemaRef) {
14389   switch (SemaRef.ExprEvalContexts.back().Context) {
14390     case Sema::ExpressionEvaluationContext::Unevaluated:
14391     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14392       // Expressions in this context are never evaluated.
14393       return false;
14394 
14395     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14396     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14397     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14398     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14399       // Expressions in this context could be evaluated.
14400       return true;
14401 
14402     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14403       // Referenced declarations will only be used if the construct in the
14404       // containing expression is used, at which point we'll be given another
14405       // turn to mark them.
14406       return false;
14407   }
14408   llvm_unreachable("Invalid context");
14409 }
14410 
14411 /// Are we within a context in which references to resolved functions or to
14412 /// variables result in odr-use?
14413 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14414   // An expression in a template is not really an expression until it's been
14415   // instantiated, so it doesn't trigger odr-use.
14416   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14417     return false;
14418 
14419   switch (SemaRef.ExprEvalContexts.back().Context) {
14420     case Sema::ExpressionEvaluationContext::Unevaluated:
14421     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14422     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14423     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14424       return false;
14425 
14426     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14427     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14428       return true;
14429 
14430     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14431       return false;
14432   }
14433   llvm_unreachable("Invalid context");
14434 }
14435 
14436 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14437   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14438   return Func->isConstexpr() &&
14439          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14440 }
14441 
14442 /// Mark a function referenced, and check whether it is odr-used
14443 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14444 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14445                                   bool MightBeOdrUse) {
14446   assert(Func && "No function?");
14447 
14448   Func->setReferenced();
14449 
14450   // C++11 [basic.def.odr]p3:
14451   //   A function whose name appears as a potentially-evaluated expression is
14452   //   odr-used if it is the unique lookup result or the selected member of a
14453   //   set of overloaded functions [...].
14454   //
14455   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14456   // can just check that here.
14457   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14458 
14459   // Determine whether we require a function definition to exist, per
14460   // C++11 [temp.inst]p3:
14461   //   Unless a function template specialization has been explicitly
14462   //   instantiated or explicitly specialized, the function template
14463   //   specialization is implicitly instantiated when the specialization is
14464   //   referenced in a context that requires a function definition to exist.
14465   //
14466   // That is either when this is an odr-use, or when a usage of a constexpr
14467   // function occurs within an evaluatable context.
14468   bool NeedDefinition =
14469       OdrUse || (isEvaluatableContext(*this) &&
14470                  isImplicitlyDefinableConstexprFunction(Func));
14471 
14472   // C++14 [temp.expl.spec]p6:
14473   //   If a template [...] is explicitly specialized then that specialization
14474   //   shall be declared before the first use of that specialization that would
14475   //   cause an implicit instantiation to take place, in every translation unit
14476   //   in which such a use occurs
14477   if (NeedDefinition &&
14478       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14479        Func->getMemberSpecializationInfo()))
14480     checkSpecializationVisibility(Loc, Func);
14481 
14482   // C++14 [except.spec]p17:
14483   //   An exception-specification is considered to be needed when:
14484   //   - the function is odr-used or, if it appears in an unevaluated operand,
14485   //     would be odr-used if the expression were potentially-evaluated;
14486   //
14487   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14488   // function is a pure virtual function we're calling, and in that case the
14489   // function was selected by overload resolution and we need to resolve its
14490   // exception specification for a different reason.
14491   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14492   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14493     ResolveExceptionSpec(Loc, FPT);
14494 
14495   // If we don't need to mark the function as used, and we don't need to
14496   // try to provide a definition, there's nothing more to do.
14497   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14498       (!NeedDefinition || Func->getBody()))
14499     return;
14500 
14501   // Note that this declaration has been used.
14502   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14503     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14504     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14505       if (Constructor->isDefaultConstructor()) {
14506         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14507           return;
14508         DefineImplicitDefaultConstructor(Loc, Constructor);
14509       } else if (Constructor->isCopyConstructor()) {
14510         DefineImplicitCopyConstructor(Loc, Constructor);
14511       } else if (Constructor->isMoveConstructor()) {
14512         DefineImplicitMoveConstructor(Loc, Constructor);
14513       }
14514     } else if (Constructor->getInheritedConstructor()) {
14515       DefineInheritingConstructor(Loc, Constructor);
14516     }
14517   } else if (CXXDestructorDecl *Destructor =
14518                  dyn_cast<CXXDestructorDecl>(Func)) {
14519     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14520     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14521       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14522         return;
14523       DefineImplicitDestructor(Loc, Destructor);
14524     }
14525     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14526       MarkVTableUsed(Loc, Destructor->getParent());
14527   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14528     if (MethodDecl->isOverloadedOperator() &&
14529         MethodDecl->getOverloadedOperator() == OO_Equal) {
14530       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14531       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14532         if (MethodDecl->isCopyAssignmentOperator())
14533           DefineImplicitCopyAssignment(Loc, MethodDecl);
14534         else if (MethodDecl->isMoveAssignmentOperator())
14535           DefineImplicitMoveAssignment(Loc, MethodDecl);
14536       }
14537     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14538                MethodDecl->getParent()->isLambda()) {
14539       CXXConversionDecl *Conversion =
14540           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14541       if (Conversion->isLambdaToBlockPointerConversion())
14542         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14543       else
14544         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14545     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14546       MarkVTableUsed(Loc, MethodDecl->getParent());
14547   }
14548 
14549   // Recursive functions should be marked when used from another function.
14550   // FIXME: Is this really right?
14551   if (CurContext == Func) return;
14552 
14553   // Implicit instantiation of function templates and member functions of
14554   // class templates.
14555   if (Func->isImplicitlyInstantiable()) {
14556     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14557     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14558     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14559     if (FirstInstantiation) {
14560       PointOfInstantiation = Loc;
14561       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14562     } else if (TSK != TSK_ImplicitInstantiation) {
14563       // Use the point of use as the point of instantiation, instead of the
14564       // point of explicit instantiation (which we track as the actual point of
14565       // instantiation). This gives better backtraces in diagnostics.
14566       PointOfInstantiation = Loc;
14567     }
14568 
14569     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14570         Func->isConstexpr()) {
14571       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14572           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14573           CodeSynthesisContexts.size())
14574         PendingLocalImplicitInstantiations.push_back(
14575             std::make_pair(Func, PointOfInstantiation));
14576       else if (Func->isConstexpr())
14577         // Do not defer instantiations of constexpr functions, to avoid the
14578         // expression evaluator needing to call back into Sema if it sees a
14579         // call to such a function.
14580         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14581       else {
14582         Func->setInstantiationIsPending(true);
14583         PendingInstantiations.push_back(std::make_pair(Func,
14584                                                        PointOfInstantiation));
14585         // Notify the consumer that a function was implicitly instantiated.
14586         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14587       }
14588     }
14589   } else {
14590     // Walk redefinitions, as some of them may be instantiable.
14591     for (auto i : Func->redecls()) {
14592       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14593         MarkFunctionReferenced(Loc, i, OdrUse);
14594     }
14595   }
14596 
14597   if (!OdrUse) return;
14598 
14599   // Keep track of used but undefined functions.
14600   if (!Func->isDefined()) {
14601     if (mightHaveNonExternalLinkage(Func))
14602       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14603     else if (Func->getMostRecentDecl()->isInlined() &&
14604              !LangOpts.GNUInline &&
14605              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14606       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14607     else if (isExternalWithNoLinkageType(Func))
14608       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14609   }
14610 
14611   Func->markUsed(Context);
14612 }
14613 
14614 static void
14615 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14616                                    ValueDecl *var, DeclContext *DC) {
14617   DeclContext *VarDC = var->getDeclContext();
14618 
14619   //  If the parameter still belongs to the translation unit, then
14620   //  we're actually just using one parameter in the declaration of
14621   //  the next.
14622   if (isa<ParmVarDecl>(var) &&
14623       isa<TranslationUnitDecl>(VarDC))
14624     return;
14625 
14626   // For C code, don't diagnose about capture if we're not actually in code
14627   // right now; it's impossible to write a non-constant expression outside of
14628   // function context, so we'll get other (more useful) diagnostics later.
14629   //
14630   // For C++, things get a bit more nasty... it would be nice to suppress this
14631   // diagnostic for certain cases like using a local variable in an array bound
14632   // for a member of a local class, but the correct predicate is not obvious.
14633   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14634     return;
14635 
14636   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14637   unsigned ContextKind = 3; // unknown
14638   if (isa<CXXMethodDecl>(VarDC) &&
14639       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14640     ContextKind = 2;
14641   } else if (isa<FunctionDecl>(VarDC)) {
14642     ContextKind = 0;
14643   } else if (isa<BlockDecl>(VarDC)) {
14644     ContextKind = 1;
14645   }
14646 
14647   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14648     << var << ValueKind << ContextKind << VarDC;
14649   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14650       << var;
14651 
14652   // FIXME: Add additional diagnostic info about class etc. which prevents
14653   // capture.
14654 }
14655 
14656 
14657 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14658                                       bool &SubCapturesAreNested,
14659                                       QualType &CaptureType,
14660                                       QualType &DeclRefType) {
14661    // Check whether we've already captured it.
14662   if (CSI->CaptureMap.count(Var)) {
14663     // If we found a capture, any subcaptures are nested.
14664     SubCapturesAreNested = true;
14665 
14666     // Retrieve the capture type for this variable.
14667     CaptureType = CSI->getCapture(Var).getCaptureType();
14668 
14669     // Compute the type of an expression that refers to this variable.
14670     DeclRefType = CaptureType.getNonReferenceType();
14671 
14672     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14673     // are mutable in the sense that user can change their value - they are
14674     // private instances of the captured declarations.
14675     const Capture &Cap = CSI->getCapture(Var);
14676     if (Cap.isCopyCapture() &&
14677         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14678         !(isa<CapturedRegionScopeInfo>(CSI) &&
14679           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14680       DeclRefType.addConst();
14681     return true;
14682   }
14683   return false;
14684 }
14685 
14686 // Only block literals, captured statements, and lambda expressions can
14687 // capture; other scopes don't work.
14688 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14689                                  SourceLocation Loc,
14690                                  const bool Diagnose, Sema &S) {
14691   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14692     return getLambdaAwareParentOfDeclContext(DC);
14693   else if (Var->hasLocalStorage()) {
14694     if (Diagnose)
14695        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14696   }
14697   return nullptr;
14698 }
14699 
14700 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14701 // certain types of variables (unnamed, variably modified types etc.)
14702 // so check for eligibility.
14703 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14704                                  SourceLocation Loc,
14705                                  const bool Diagnose, Sema &S) {
14706 
14707   bool IsBlock = isa<BlockScopeInfo>(CSI);
14708   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14709 
14710   // Lambdas are not allowed to capture unnamed variables
14711   // (e.g. anonymous unions).
14712   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14713   // assuming that's the intent.
14714   if (IsLambda && !Var->getDeclName()) {
14715     if (Diagnose) {
14716       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14717       S.Diag(Var->getLocation(), diag::note_declared_at);
14718     }
14719     return false;
14720   }
14721 
14722   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14723   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14724     if (Diagnose) {
14725       S.Diag(Loc, diag::err_ref_vm_type);
14726       S.Diag(Var->getLocation(), diag::note_previous_decl)
14727         << Var->getDeclName();
14728     }
14729     return false;
14730   }
14731   // Prohibit structs with flexible array members too.
14732   // We cannot capture what is in the tail end of the struct.
14733   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14734     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14735       if (Diagnose) {
14736         if (IsBlock)
14737           S.Diag(Loc, diag::err_ref_flexarray_type);
14738         else
14739           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14740             << Var->getDeclName();
14741         S.Diag(Var->getLocation(), diag::note_previous_decl)
14742           << Var->getDeclName();
14743       }
14744       return false;
14745     }
14746   }
14747   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14748   // Lambdas and captured statements are not allowed to capture __block
14749   // variables; they don't support the expected semantics.
14750   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14751     if (Diagnose) {
14752       S.Diag(Loc, diag::err_capture_block_variable)
14753         << Var->getDeclName() << !IsLambda;
14754       S.Diag(Var->getLocation(), diag::note_previous_decl)
14755         << Var->getDeclName();
14756     }
14757     return false;
14758   }
14759   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14760   if (S.getLangOpts().OpenCL && IsBlock &&
14761       Var->getType()->isBlockPointerType()) {
14762     if (Diagnose)
14763       S.Diag(Loc, diag::err_opencl_block_ref_block);
14764     return false;
14765   }
14766 
14767   return true;
14768 }
14769 
14770 // Returns true if the capture by block was successful.
14771 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14772                                  SourceLocation Loc,
14773                                  const bool BuildAndDiagnose,
14774                                  QualType &CaptureType,
14775                                  QualType &DeclRefType,
14776                                  const bool Nested,
14777                                  Sema &S) {
14778   Expr *CopyExpr = nullptr;
14779   bool ByRef = false;
14780 
14781   // Blocks are not allowed to capture arrays, excepting OpenCL.
14782   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
14783   // (decayed to pointers).
14784   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
14785     if (BuildAndDiagnose) {
14786       S.Diag(Loc, diag::err_ref_array_type);
14787       S.Diag(Var->getLocation(), diag::note_previous_decl)
14788       << Var->getDeclName();
14789     }
14790     return false;
14791   }
14792 
14793   // Forbid the block-capture of autoreleasing variables.
14794   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14795     if (BuildAndDiagnose) {
14796       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14797         << /*block*/ 0;
14798       S.Diag(Var->getLocation(), diag::note_previous_decl)
14799         << Var->getDeclName();
14800     }
14801     return false;
14802   }
14803 
14804   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14805   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14806     // This function finds out whether there is an AttributedType of kind
14807     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
14808     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
14809     // rather than being added implicitly by the compiler.
14810     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14811       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14812         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
14813           return true;
14814 
14815         // Peel off AttributedTypes that are not of kind ObjCOwnership.
14816         Ty = AttrTy->getModifiedType();
14817       }
14818 
14819       return false;
14820     };
14821 
14822     QualType PointeeTy = PT->getPointeeType();
14823 
14824     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14825         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14826         !IsObjCOwnershipAttributedType(PointeeTy)) {
14827       if (BuildAndDiagnose) {
14828         SourceLocation VarLoc = Var->getLocation();
14829         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14830         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14831       }
14832     }
14833   }
14834 
14835   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14836   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14837       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14838     // Block capture by reference does not change the capture or
14839     // declaration reference types.
14840     ByRef = true;
14841   } else {
14842     // Block capture by copy introduces 'const'.
14843     CaptureType = CaptureType.getNonReferenceType().withConst();
14844     DeclRefType = CaptureType;
14845 
14846     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14847       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14848         // The capture logic needs the destructor, so make sure we mark it.
14849         // Usually this is unnecessary because most local variables have
14850         // their destructors marked at declaration time, but parameters are
14851         // an exception because it's technically only the call site that
14852         // actually requires the destructor.
14853         if (isa<ParmVarDecl>(Var))
14854           S.FinalizeVarWithDestructor(Var, Record);
14855 
14856         // Enter a new evaluation context to insulate the copy
14857         // full-expression.
14858         EnterExpressionEvaluationContext scope(
14859             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14860 
14861         // According to the blocks spec, the capture of a variable from
14862         // the stack requires a const copy constructor.  This is not true
14863         // of the copy/move done to move a __block variable to the heap.
14864         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14865                                                   DeclRefType.withConst(),
14866                                                   VK_LValue, Loc);
14867 
14868         ExprResult Result
14869           = S.PerformCopyInitialization(
14870               InitializedEntity::InitializeBlock(Var->getLocation(),
14871                                                   CaptureType, false),
14872               Loc, DeclRef);
14873 
14874         // Build a full-expression copy expression if initialization
14875         // succeeded and used a non-trivial constructor.  Recover from
14876         // errors by pretending that the copy isn't necessary.
14877         if (!Result.isInvalid() &&
14878             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14879                 ->isTrivial()) {
14880           Result = S.MaybeCreateExprWithCleanups(Result);
14881           CopyExpr = Result.get();
14882         }
14883       }
14884     }
14885   }
14886 
14887   // Actually capture the variable.
14888   if (BuildAndDiagnose)
14889     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14890                     SourceLocation(), CaptureType, CopyExpr);
14891 
14892   return true;
14893 
14894 }
14895 
14896 
14897 /// Capture the given variable in the captured region.
14898 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14899                                     VarDecl *Var,
14900                                     SourceLocation Loc,
14901                                     const bool BuildAndDiagnose,
14902                                     QualType &CaptureType,
14903                                     QualType &DeclRefType,
14904                                     const bool RefersToCapturedVariable,
14905                                     Sema &S) {
14906   // By default, capture variables by reference.
14907   bool ByRef = true;
14908   // Using an LValue reference type is consistent with Lambdas (see below).
14909   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14910     if (S.isOpenMPCapturedDecl(Var)) {
14911       bool HasConst = DeclRefType.isConstQualified();
14912       DeclRefType = DeclRefType.getUnqualifiedType();
14913       // Don't lose diagnostics about assignments to const.
14914       if (HasConst)
14915         DeclRefType.addConst();
14916     }
14917     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14918   }
14919 
14920   if (ByRef)
14921     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14922   else
14923     CaptureType = DeclRefType;
14924 
14925   Expr *CopyExpr = nullptr;
14926   if (BuildAndDiagnose) {
14927     // The current implementation assumes that all variables are captured
14928     // by references. Since there is no capture by copy, no expression
14929     // evaluation will be needed.
14930     RecordDecl *RD = RSI->TheRecordDecl;
14931 
14932     FieldDecl *Field
14933       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14934                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14935                           nullptr, false, ICIS_NoInit);
14936     Field->setImplicit(true);
14937     Field->setAccess(AS_private);
14938     RD->addDecl(Field);
14939     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14940       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14941 
14942     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14943                                             DeclRefType, VK_LValue, Loc);
14944     Var->setReferenced(true);
14945     Var->markUsed(S.Context);
14946   }
14947 
14948   // Actually capture the variable.
14949   if (BuildAndDiagnose)
14950     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14951                     SourceLocation(), CaptureType, CopyExpr);
14952 
14953 
14954   return true;
14955 }
14956 
14957 /// Create a field within the lambda class for the variable
14958 /// being captured.
14959 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14960                                     QualType FieldType, QualType DeclRefType,
14961                                     SourceLocation Loc,
14962                                     bool RefersToCapturedVariable) {
14963   CXXRecordDecl *Lambda = LSI->Lambda;
14964 
14965   // Build the non-static data member.
14966   FieldDecl *Field
14967     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14968                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14969                         nullptr, false, ICIS_NoInit);
14970   Field->setImplicit(true);
14971   Field->setAccess(AS_private);
14972   Lambda->addDecl(Field);
14973 }
14974 
14975 /// Capture the given variable in the lambda.
14976 static bool captureInLambda(LambdaScopeInfo *LSI,
14977                             VarDecl *Var,
14978                             SourceLocation Loc,
14979                             const bool BuildAndDiagnose,
14980                             QualType &CaptureType,
14981                             QualType &DeclRefType,
14982                             const bool RefersToCapturedVariable,
14983                             const Sema::TryCaptureKind Kind,
14984                             SourceLocation EllipsisLoc,
14985                             const bool IsTopScope,
14986                             Sema &S) {
14987 
14988   // Determine whether we are capturing by reference or by value.
14989   bool ByRef = false;
14990   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14991     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14992   } else {
14993     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14994   }
14995 
14996   // Compute the type of the field that will capture this variable.
14997   if (ByRef) {
14998     // C++11 [expr.prim.lambda]p15:
14999     //   An entity is captured by reference if it is implicitly or
15000     //   explicitly captured but not captured by copy. It is
15001     //   unspecified whether additional unnamed non-static data
15002     //   members are declared in the closure type for entities
15003     //   captured by reference.
15004     //
15005     // FIXME: It is not clear whether we want to build an lvalue reference
15006     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15007     // to do the former, while EDG does the latter. Core issue 1249 will
15008     // clarify, but for now we follow GCC because it's a more permissive and
15009     // easily defensible position.
15010     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15011   } else {
15012     // C++11 [expr.prim.lambda]p14:
15013     //   For each entity captured by copy, an unnamed non-static
15014     //   data member is declared in the closure type. The
15015     //   declaration order of these members is unspecified. The type
15016     //   of such a data member is the type of the corresponding
15017     //   captured entity if the entity is not a reference to an
15018     //   object, or the referenced type otherwise. [Note: If the
15019     //   captured entity is a reference to a function, the
15020     //   corresponding data member is also a reference to a
15021     //   function. - end note ]
15022     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15023       if (!RefType->getPointeeType()->isFunctionType())
15024         CaptureType = RefType->getPointeeType();
15025     }
15026 
15027     // Forbid the lambda copy-capture of autoreleasing variables.
15028     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15029       if (BuildAndDiagnose) {
15030         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15031         S.Diag(Var->getLocation(), diag::note_previous_decl)
15032           << Var->getDeclName();
15033       }
15034       return false;
15035     }
15036 
15037     // Make sure that by-copy captures are of a complete and non-abstract type.
15038     if (BuildAndDiagnose) {
15039       if (!CaptureType->isDependentType() &&
15040           S.RequireCompleteType(Loc, CaptureType,
15041                                 diag::err_capture_of_incomplete_type,
15042                                 Var->getDeclName()))
15043         return false;
15044 
15045       if (S.RequireNonAbstractType(Loc, CaptureType,
15046                                    diag::err_capture_of_abstract_type))
15047         return false;
15048     }
15049   }
15050 
15051   // Capture this variable in the lambda.
15052   if (BuildAndDiagnose)
15053     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15054                             RefersToCapturedVariable);
15055 
15056   // Compute the type of a reference to this captured variable.
15057   if (ByRef)
15058     DeclRefType = CaptureType.getNonReferenceType();
15059   else {
15060     // C++ [expr.prim.lambda]p5:
15061     //   The closure type for a lambda-expression has a public inline
15062     //   function call operator [...]. This function call operator is
15063     //   declared const (9.3.1) if and only if the lambda-expression's
15064     //   parameter-declaration-clause is not followed by mutable.
15065     DeclRefType = CaptureType.getNonReferenceType();
15066     if (!LSI->Mutable && !CaptureType->isReferenceType())
15067       DeclRefType.addConst();
15068   }
15069 
15070   // Add the capture.
15071   if (BuildAndDiagnose)
15072     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15073                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15074 
15075   return true;
15076 }
15077 
15078 bool Sema::tryCaptureVariable(
15079     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15080     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15081     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15082   // An init-capture is notionally from the context surrounding its
15083   // declaration, but its parent DC is the lambda class.
15084   DeclContext *VarDC = Var->getDeclContext();
15085   if (Var->isInitCapture())
15086     VarDC = VarDC->getParent();
15087 
15088   DeclContext *DC = CurContext;
15089   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15090       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15091   // We need to sync up the Declaration Context with the
15092   // FunctionScopeIndexToStopAt
15093   if (FunctionScopeIndexToStopAt) {
15094     unsigned FSIndex = FunctionScopes.size() - 1;
15095     while (FSIndex != MaxFunctionScopesIndex) {
15096       DC = getLambdaAwareParentOfDeclContext(DC);
15097       --FSIndex;
15098     }
15099   }
15100 
15101 
15102   // If the variable is declared in the current context, there is no need to
15103   // capture it.
15104   if (VarDC == DC) return true;
15105 
15106   // Capture global variables if it is required to use private copy of this
15107   // variable.
15108   bool IsGlobal = !Var->hasLocalStorage();
15109   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15110     return true;
15111   Var = Var->getCanonicalDecl();
15112 
15113   // Walk up the stack to determine whether we can capture the variable,
15114   // performing the "simple" checks that don't depend on type. We stop when
15115   // we've either hit the declared scope of the variable or find an existing
15116   // capture of that variable.  We start from the innermost capturing-entity
15117   // (the DC) and ensure that all intervening capturing-entities
15118   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15119   // declcontext can either capture the variable or have already captured
15120   // the variable.
15121   CaptureType = Var->getType();
15122   DeclRefType = CaptureType.getNonReferenceType();
15123   bool Nested = false;
15124   bool Explicit = (Kind != TryCapture_Implicit);
15125   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15126   do {
15127     // Only block literals, captured statements, and lambda expressions can
15128     // capture; other scopes don't work.
15129     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15130                                                               ExprLoc,
15131                                                               BuildAndDiagnose,
15132                                                               *this);
15133     // We need to check for the parent *first* because, if we *have*
15134     // private-captured a global variable, we need to recursively capture it in
15135     // intermediate blocks, lambdas, etc.
15136     if (!ParentDC) {
15137       if (IsGlobal) {
15138         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15139         break;
15140       }
15141       return true;
15142     }
15143 
15144     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15145     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15146 
15147 
15148     // Check whether we've already captured it.
15149     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15150                                              DeclRefType)) {
15151       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15152       break;
15153     }
15154     // If we are instantiating a generic lambda call operator body,
15155     // we do not want to capture new variables.  What was captured
15156     // during either a lambdas transformation or initial parsing
15157     // should be used.
15158     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15159       if (BuildAndDiagnose) {
15160         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15161         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15162           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15163           Diag(Var->getLocation(), diag::note_previous_decl)
15164              << Var->getDeclName();
15165           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15166         } else
15167           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15168       }
15169       return true;
15170     }
15171     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15172     // certain types of variables (unnamed, variably modified types etc.)
15173     // so check for eligibility.
15174     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15175        return true;
15176 
15177     // Try to capture variable-length arrays types.
15178     if (Var->getType()->isVariablyModifiedType()) {
15179       // We're going to walk down into the type and look for VLA
15180       // expressions.
15181       QualType QTy = Var->getType();
15182       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15183         QTy = PVD->getOriginalType();
15184       captureVariablyModifiedType(Context, QTy, CSI);
15185     }
15186 
15187     if (getLangOpts().OpenMP) {
15188       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15189         // OpenMP private variables should not be captured in outer scope, so
15190         // just break here. Similarly, global variables that are captured in a
15191         // target region should not be captured outside the scope of the region.
15192         if (RSI->CapRegionKind == CR_OpenMP) {
15193           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15194           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15195                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15196           // When we detect target captures we are looking from inside the
15197           // target region, therefore we need to propagate the capture from the
15198           // enclosing region. Therefore, the capture is not initially nested.
15199           if (IsTargetCap)
15200             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15201 
15202           if (IsTargetCap || IsOpenMPPrivateDecl) {
15203             Nested = !IsTargetCap;
15204             DeclRefType = DeclRefType.getUnqualifiedType();
15205             CaptureType = Context.getLValueReferenceType(DeclRefType);
15206             break;
15207           }
15208         }
15209       }
15210     }
15211     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15212       // No capture-default, and this is not an explicit capture
15213       // so cannot capture this variable.
15214       if (BuildAndDiagnose) {
15215         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15216         Diag(Var->getLocation(), diag::note_previous_decl)
15217           << Var->getDeclName();
15218         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15219           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15220                diag::note_lambda_decl);
15221         // FIXME: If we error out because an outer lambda can not implicitly
15222         // capture a variable that an inner lambda explicitly captures, we
15223         // should have the inner lambda do the explicit capture - because
15224         // it makes for cleaner diagnostics later.  This would purely be done
15225         // so that the diagnostic does not misleadingly claim that a variable
15226         // can not be captured by a lambda implicitly even though it is captured
15227         // explicitly.  Suggestion:
15228         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15229         //    at the function head
15230         //  - cache the StartingDeclContext - this must be a lambda
15231         //  - captureInLambda in the innermost lambda the variable.
15232       }
15233       return true;
15234     }
15235 
15236     FunctionScopesIndex--;
15237     DC = ParentDC;
15238     Explicit = false;
15239   } while (!VarDC->Equals(DC));
15240 
15241   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15242   // computing the type of the capture at each step, checking type-specific
15243   // requirements, and adding captures if requested.
15244   // If the variable had already been captured previously, we start capturing
15245   // at the lambda nested within that one.
15246   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15247        ++I) {
15248     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15249 
15250     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15251       if (!captureInBlock(BSI, Var, ExprLoc,
15252                           BuildAndDiagnose, CaptureType,
15253                           DeclRefType, Nested, *this))
15254         return true;
15255       Nested = true;
15256     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15257       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15258                                    BuildAndDiagnose, CaptureType,
15259                                    DeclRefType, Nested, *this))
15260         return true;
15261       Nested = true;
15262     } else {
15263       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15264       if (!captureInLambda(LSI, Var, ExprLoc,
15265                            BuildAndDiagnose, CaptureType,
15266                            DeclRefType, Nested, Kind, EllipsisLoc,
15267                             /*IsTopScope*/I == N - 1, *this))
15268         return true;
15269       Nested = true;
15270     }
15271   }
15272   return false;
15273 }
15274 
15275 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15276                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15277   QualType CaptureType;
15278   QualType DeclRefType;
15279   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15280                             /*BuildAndDiagnose=*/true, CaptureType,
15281                             DeclRefType, nullptr);
15282 }
15283 
15284 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15285   QualType CaptureType;
15286   QualType DeclRefType;
15287   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15288                              /*BuildAndDiagnose=*/false, CaptureType,
15289                              DeclRefType, nullptr);
15290 }
15291 
15292 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15293   QualType CaptureType;
15294   QualType DeclRefType;
15295 
15296   // Determine whether we can capture this variable.
15297   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15298                          /*BuildAndDiagnose=*/false, CaptureType,
15299                          DeclRefType, nullptr))
15300     return QualType();
15301 
15302   return DeclRefType;
15303 }
15304 
15305 
15306 
15307 // If either the type of the variable or the initializer is dependent,
15308 // return false. Otherwise, determine whether the variable is a constant
15309 // expression. Use this if you need to know if a variable that might or
15310 // might not be dependent is truly a constant expression.
15311 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15312     ASTContext &Context) {
15313 
15314   if (Var->getType()->isDependentType())
15315     return false;
15316   const VarDecl *DefVD = nullptr;
15317   Var->getAnyInitializer(DefVD);
15318   if (!DefVD)
15319     return false;
15320   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15321   Expr *Init = cast<Expr>(Eval->Value);
15322   if (Init->isValueDependent())
15323     return false;
15324   return IsVariableAConstantExpression(Var, Context);
15325 }
15326 
15327 
15328 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15329   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15330   // an object that satisfies the requirements for appearing in a
15331   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15332   // is immediately applied."  This function handles the lvalue-to-rvalue
15333   // conversion part.
15334   MaybeODRUseExprs.erase(E->IgnoreParens());
15335 
15336   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15337   // to a variable that is a constant expression, and if so, identify it as
15338   // a reference to a variable that does not involve an odr-use of that
15339   // variable.
15340   if (LambdaScopeInfo *LSI = getCurLambda()) {
15341     Expr *SansParensExpr = E->IgnoreParens();
15342     VarDecl *Var = nullptr;
15343     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15344       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15345     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15346       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15347 
15348     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15349       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15350   }
15351 }
15352 
15353 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15354   Res = CorrectDelayedTyposInExpr(Res);
15355 
15356   if (!Res.isUsable())
15357     return Res;
15358 
15359   // If a constant-expression is a reference to a variable where we delay
15360   // deciding whether it is an odr-use, just assume we will apply the
15361   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15362   // (a non-type template argument), we have special handling anyway.
15363   UpdateMarkingForLValueToRValue(Res.get());
15364   return Res;
15365 }
15366 
15367 void Sema::CleanupVarDeclMarking() {
15368   for (Expr *E : MaybeODRUseExprs) {
15369     VarDecl *Var;
15370     SourceLocation Loc;
15371     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15372       Var = cast<VarDecl>(DRE->getDecl());
15373       Loc = DRE->getLocation();
15374     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15375       Var = cast<VarDecl>(ME->getMemberDecl());
15376       Loc = ME->getMemberLoc();
15377     } else {
15378       llvm_unreachable("Unexpected expression");
15379     }
15380 
15381     MarkVarDeclODRUsed(Var, Loc, *this,
15382                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15383   }
15384 
15385   MaybeODRUseExprs.clear();
15386 }
15387 
15388 
15389 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15390                                     VarDecl *Var, Expr *E) {
15391   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15392          "Invalid Expr argument to DoMarkVarDeclReferenced");
15393   Var->setReferenced();
15394 
15395   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15396 
15397   bool OdrUseContext = isOdrUseContext(SemaRef);
15398   bool UsableInConstantExpr =
15399       Var->isUsableInConstantExpressions(SemaRef.Context);
15400   bool NeedDefinition =
15401       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15402 
15403   VarTemplateSpecializationDecl *VarSpec =
15404       dyn_cast<VarTemplateSpecializationDecl>(Var);
15405   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15406          "Can't instantiate a partial template specialization.");
15407 
15408   // If this might be a member specialization of a static data member, check
15409   // the specialization is visible. We already did the checks for variable
15410   // template specializations when we created them.
15411   if (NeedDefinition && TSK != TSK_Undeclared &&
15412       !isa<VarTemplateSpecializationDecl>(Var))
15413     SemaRef.checkSpecializationVisibility(Loc, Var);
15414 
15415   // Perform implicit instantiation of static data members, static data member
15416   // templates of class templates, and variable template specializations. Delay
15417   // instantiations of variable templates, except for those that could be used
15418   // in a constant expression.
15419   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15420     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15421     // instantiation declaration if a variable is usable in a constant
15422     // expression (among other cases).
15423     bool TryInstantiating =
15424         TSK == TSK_ImplicitInstantiation ||
15425         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15426 
15427     if (TryInstantiating) {
15428       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15429       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15430       if (FirstInstantiation) {
15431         PointOfInstantiation = Loc;
15432         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15433       }
15434 
15435       bool InstantiationDependent = false;
15436       bool IsNonDependent =
15437           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15438                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15439                   : true;
15440 
15441       // Do not instantiate specializations that are still type-dependent.
15442       if (IsNonDependent) {
15443         if (UsableInConstantExpr) {
15444           // Do not defer instantiations of variables that could be used in a
15445           // constant expression.
15446           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15447         } else if (FirstInstantiation ||
15448                    isa<VarTemplateSpecializationDecl>(Var)) {
15449           // FIXME: For a specialization of a variable template, we don't
15450           // distinguish between "declaration and type implicitly instantiated"
15451           // and "implicit instantiation of definition requested", so we have
15452           // no direct way to avoid enqueueing the pending instantiation
15453           // multiple times.
15454           SemaRef.PendingInstantiations
15455               .push_back(std::make_pair(Var, PointOfInstantiation));
15456         }
15457       }
15458     }
15459   }
15460 
15461   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15462   // the requirements for appearing in a constant expression (5.19) and, if
15463   // it is an object, the lvalue-to-rvalue conversion (4.1)
15464   // is immediately applied."  We check the first part here, and
15465   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15466   // Note that we use the C++11 definition everywhere because nothing in
15467   // C++03 depends on whether we get the C++03 version correct. The second
15468   // part does not apply to references, since they are not objects.
15469   if (OdrUseContext && E &&
15470       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15471     // A reference initialized by a constant expression can never be
15472     // odr-used, so simply ignore it.
15473     if (!Var->getType()->isReferenceType() ||
15474         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15475       SemaRef.MaybeODRUseExprs.insert(E);
15476   } else if (OdrUseContext) {
15477     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15478                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15479   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15480     // If this is a dependent context, we don't need to mark variables as
15481     // odr-used, but we may still need to track them for lambda capture.
15482     // FIXME: Do we also need to do this inside dependent typeid expressions
15483     // (which are modeled as unevaluated at this point)?
15484     const bool RefersToEnclosingScope =
15485         (SemaRef.CurContext != Var->getDeclContext() &&
15486          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15487     if (RefersToEnclosingScope) {
15488       LambdaScopeInfo *const LSI =
15489           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15490       if (LSI && (!LSI->CallOperator ||
15491                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15492         // If a variable could potentially be odr-used, defer marking it so
15493         // until we finish analyzing the full expression for any
15494         // lvalue-to-rvalue
15495         // or discarded value conversions that would obviate odr-use.
15496         // Add it to the list of potential captures that will be analyzed
15497         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15498         // unless the variable is a reference that was initialized by a constant
15499         // expression (this will never need to be captured or odr-used).
15500         assert(E && "Capture variable should be used in an expression.");
15501         if (!Var->getType()->isReferenceType() ||
15502             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15503           LSI->addPotentialCapture(E->IgnoreParens());
15504       }
15505     }
15506   }
15507 }
15508 
15509 /// Mark a variable referenced, and check whether it is odr-used
15510 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15511 /// used directly for normal expressions referring to VarDecl.
15512 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15513   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15514 }
15515 
15516 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15517                                Decl *D, Expr *E, bool MightBeOdrUse) {
15518   if (SemaRef.isInOpenMPDeclareTargetContext())
15519     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15520 
15521   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15522     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15523     return;
15524   }
15525 
15526   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15527 
15528   // If this is a call to a method via a cast, also mark the method in the
15529   // derived class used in case codegen can devirtualize the call.
15530   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15531   if (!ME)
15532     return;
15533   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15534   if (!MD)
15535     return;
15536   // Only attempt to devirtualize if this is truly a virtual call.
15537   bool IsVirtualCall = MD->isVirtual() &&
15538                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15539   if (!IsVirtualCall)
15540     return;
15541 
15542   // If it's possible to devirtualize the call, mark the called function
15543   // referenced.
15544   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15545       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15546   if (DM)
15547     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15548 }
15549 
15550 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15551 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15552   // TODO: update this with DR# once a defect report is filed.
15553   // C++11 defect. The address of a pure member should not be an ODR use, even
15554   // if it's a qualified reference.
15555   bool OdrUse = true;
15556   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15557     if (Method->isVirtual() &&
15558         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15559       OdrUse = false;
15560   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15561 }
15562 
15563 /// Perform reference-marking and odr-use handling for a MemberExpr.
15564 void Sema::MarkMemberReferenced(MemberExpr *E) {
15565   // C++11 [basic.def.odr]p2:
15566   //   A non-overloaded function whose name appears as a potentially-evaluated
15567   //   expression or a member of a set of candidate functions, if selected by
15568   //   overload resolution when referred to from a potentially-evaluated
15569   //   expression, is odr-used, unless it is a pure virtual function and its
15570   //   name is not explicitly qualified.
15571   bool MightBeOdrUse = true;
15572   if (E->performsVirtualDispatch(getLangOpts())) {
15573     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15574       if (Method->isPure())
15575         MightBeOdrUse = false;
15576   }
15577   SourceLocation Loc =
15578       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15579   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15580 }
15581 
15582 /// Perform marking for a reference to an arbitrary declaration.  It
15583 /// marks the declaration referenced, and performs odr-use checking for
15584 /// functions and variables. This method should not be used when building a
15585 /// normal expression which refers to a variable.
15586 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15587                                  bool MightBeOdrUse) {
15588   if (MightBeOdrUse) {
15589     if (auto *VD = dyn_cast<VarDecl>(D)) {
15590       MarkVariableReferenced(Loc, VD);
15591       return;
15592     }
15593   }
15594   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15595     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15596     return;
15597   }
15598   D->setReferenced();
15599 }
15600 
15601 namespace {
15602   // Mark all of the declarations used by a type as referenced.
15603   // FIXME: Not fully implemented yet! We need to have a better understanding
15604   // of when we're entering a context we should not recurse into.
15605   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15606   // TreeTransforms rebuilding the type in a new context. Rather than
15607   // duplicating the TreeTransform logic, we should consider reusing it here.
15608   // Currently that causes problems when rebuilding LambdaExprs.
15609   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15610     Sema &S;
15611     SourceLocation Loc;
15612 
15613   public:
15614     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15615 
15616     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15617 
15618     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15619   };
15620 }
15621 
15622 bool MarkReferencedDecls::TraverseTemplateArgument(
15623     const TemplateArgument &Arg) {
15624   {
15625     // A non-type template argument is a constant-evaluated context.
15626     EnterExpressionEvaluationContext Evaluated(
15627         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15628     if (Arg.getKind() == TemplateArgument::Declaration) {
15629       if (Decl *D = Arg.getAsDecl())
15630         S.MarkAnyDeclReferenced(Loc, D, true);
15631     } else if (Arg.getKind() == TemplateArgument::Expression) {
15632       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15633     }
15634   }
15635 
15636   return Inherited::TraverseTemplateArgument(Arg);
15637 }
15638 
15639 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15640   MarkReferencedDecls Marker(*this, Loc);
15641   Marker.TraverseType(T);
15642 }
15643 
15644 namespace {
15645   /// Helper class that marks all of the declarations referenced by
15646   /// potentially-evaluated subexpressions as "referenced".
15647   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15648     Sema &S;
15649     bool SkipLocalVariables;
15650 
15651   public:
15652     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15653 
15654     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15655       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15656 
15657     void VisitDeclRefExpr(DeclRefExpr *E) {
15658       // If we were asked not to visit local variables, don't.
15659       if (SkipLocalVariables) {
15660         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15661           if (VD->hasLocalStorage())
15662             return;
15663       }
15664 
15665       S.MarkDeclRefReferenced(E);
15666     }
15667 
15668     void VisitMemberExpr(MemberExpr *E) {
15669       S.MarkMemberReferenced(E);
15670       Inherited::VisitMemberExpr(E);
15671     }
15672 
15673     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15674       S.MarkFunctionReferenced(
15675           E->getBeginLoc(),
15676           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15677       Visit(E->getSubExpr());
15678     }
15679 
15680     void VisitCXXNewExpr(CXXNewExpr *E) {
15681       if (E->getOperatorNew())
15682         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
15683       if (E->getOperatorDelete())
15684         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15685       Inherited::VisitCXXNewExpr(E);
15686     }
15687 
15688     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15689       if (E->getOperatorDelete())
15690         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15691       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15692       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15693         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15694         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
15695       }
15696 
15697       Inherited::VisitCXXDeleteExpr(E);
15698     }
15699 
15700     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15701       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
15702       Inherited::VisitCXXConstructExpr(E);
15703     }
15704 
15705     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15706       Visit(E->getExpr());
15707     }
15708 
15709     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15710       Inherited::VisitImplicitCastExpr(E);
15711 
15712       if (E->getCastKind() == CK_LValueToRValue)
15713         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15714     }
15715   };
15716 }
15717 
15718 /// Mark any declarations that appear within this expression or any
15719 /// potentially-evaluated subexpressions as "referenced".
15720 ///
15721 /// \param SkipLocalVariables If true, don't mark local variables as
15722 /// 'referenced'.
15723 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15724                                             bool SkipLocalVariables) {
15725   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15726 }
15727 
15728 /// Emit a diagnostic that describes an effect on the run-time behavior
15729 /// of the program being compiled.
15730 ///
15731 /// This routine emits the given diagnostic when the code currently being
15732 /// type-checked is "potentially evaluated", meaning that there is a
15733 /// possibility that the code will actually be executable. Code in sizeof()
15734 /// expressions, code used only during overload resolution, etc., are not
15735 /// potentially evaluated. This routine will suppress such diagnostics or,
15736 /// in the absolutely nutty case of potentially potentially evaluated
15737 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15738 /// later.
15739 ///
15740 /// This routine should be used for all diagnostics that describe the run-time
15741 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15742 /// Failure to do so will likely result in spurious diagnostics or failures
15743 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15744 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15745                                const PartialDiagnostic &PD) {
15746   switch (ExprEvalContexts.back().Context) {
15747   case ExpressionEvaluationContext::Unevaluated:
15748   case ExpressionEvaluationContext::UnevaluatedList:
15749   case ExpressionEvaluationContext::UnevaluatedAbstract:
15750   case ExpressionEvaluationContext::DiscardedStatement:
15751     // The argument will never be evaluated, so don't complain.
15752     break;
15753 
15754   case ExpressionEvaluationContext::ConstantEvaluated:
15755     // Relevant diagnostics should be produced by constant evaluation.
15756     break;
15757 
15758   case ExpressionEvaluationContext::PotentiallyEvaluated:
15759   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15760     if (Statement && getCurFunctionOrMethodDecl()) {
15761       FunctionScopes.back()->PossiblyUnreachableDiags.
15762         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15763       return true;
15764     }
15765 
15766     // The initializer of a constexpr variable or of the first declaration of a
15767     // static data member is not syntactically a constant evaluated constant,
15768     // but nonetheless is always required to be a constant expression, so we
15769     // can skip diagnosing.
15770     // FIXME: Using the mangling context here is a hack.
15771     if (auto *VD = dyn_cast_or_null<VarDecl>(
15772             ExprEvalContexts.back().ManglingContextDecl)) {
15773       if (VD->isConstexpr() ||
15774           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15775         break;
15776       // FIXME: For any other kind of variable, we should build a CFG for its
15777       // initializer and check whether the context in question is reachable.
15778     }
15779 
15780     Diag(Loc, PD);
15781     return true;
15782   }
15783 
15784   return false;
15785 }
15786 
15787 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15788                                CallExpr *CE, FunctionDecl *FD) {
15789   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15790     return false;
15791 
15792   // If we're inside a decltype's expression, don't check for a valid return
15793   // type or construct temporaries until we know whether this is the last call.
15794   if (ExprEvalContexts.back().ExprContext ==
15795       ExpressionEvaluationContextRecord::EK_Decltype) {
15796     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15797     return false;
15798   }
15799 
15800   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15801     FunctionDecl *FD;
15802     CallExpr *CE;
15803 
15804   public:
15805     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15806       : FD(FD), CE(CE) { }
15807 
15808     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15809       if (!FD) {
15810         S.Diag(Loc, diag::err_call_incomplete_return)
15811           << T << CE->getSourceRange();
15812         return;
15813       }
15814 
15815       S.Diag(Loc, diag::err_call_function_incomplete_return)
15816         << CE->getSourceRange() << FD->getDeclName() << T;
15817       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15818           << FD->getDeclName();
15819     }
15820   } Diagnoser(FD, CE);
15821 
15822   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15823     return true;
15824 
15825   return false;
15826 }
15827 
15828 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15829 // will prevent this condition from triggering, which is what we want.
15830 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15831   SourceLocation Loc;
15832 
15833   unsigned diagnostic = diag::warn_condition_is_assignment;
15834   bool IsOrAssign = false;
15835 
15836   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15837     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15838       return;
15839 
15840     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15841 
15842     // Greylist some idioms by putting them into a warning subcategory.
15843     if (ObjCMessageExpr *ME
15844           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15845       Selector Sel = ME->getSelector();
15846 
15847       // self = [<foo> init...]
15848       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15849         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15850 
15851       // <foo> = [<bar> nextObject]
15852       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15853         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15854     }
15855 
15856     Loc = Op->getOperatorLoc();
15857   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15858     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15859       return;
15860 
15861     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15862     Loc = Op->getOperatorLoc();
15863   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15864     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15865   else {
15866     // Not an assignment.
15867     return;
15868   }
15869 
15870   Diag(Loc, diagnostic) << E->getSourceRange();
15871 
15872   SourceLocation Open = E->getBeginLoc();
15873   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15874   Diag(Loc, diag::note_condition_assign_silence)
15875         << FixItHint::CreateInsertion(Open, "(")
15876         << FixItHint::CreateInsertion(Close, ")");
15877 
15878   if (IsOrAssign)
15879     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15880       << FixItHint::CreateReplacement(Loc, "!=");
15881   else
15882     Diag(Loc, diag::note_condition_assign_to_comparison)
15883       << FixItHint::CreateReplacement(Loc, "==");
15884 }
15885 
15886 /// Redundant parentheses over an equality comparison can indicate
15887 /// that the user intended an assignment used as condition.
15888 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15889   // Don't warn if the parens came from a macro.
15890   SourceLocation parenLoc = ParenE->getBeginLoc();
15891   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15892     return;
15893   // Don't warn for dependent expressions.
15894   if (ParenE->isTypeDependent())
15895     return;
15896 
15897   Expr *E = ParenE->IgnoreParens();
15898 
15899   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15900     if (opE->getOpcode() == BO_EQ &&
15901         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15902                                                            == Expr::MLV_Valid) {
15903       SourceLocation Loc = opE->getOperatorLoc();
15904 
15905       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15906       SourceRange ParenERange = ParenE->getSourceRange();
15907       Diag(Loc, diag::note_equality_comparison_silence)
15908         << FixItHint::CreateRemoval(ParenERange.getBegin())
15909         << FixItHint::CreateRemoval(ParenERange.getEnd());
15910       Diag(Loc, diag::note_equality_comparison_to_assign)
15911         << FixItHint::CreateReplacement(Loc, "=");
15912     }
15913 }
15914 
15915 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15916                                        bool IsConstexpr) {
15917   DiagnoseAssignmentAsCondition(E);
15918   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15919     DiagnoseEqualityWithExtraParens(parenE);
15920 
15921   ExprResult result = CheckPlaceholderExpr(E);
15922   if (result.isInvalid()) return ExprError();
15923   E = result.get();
15924 
15925   if (!E->isTypeDependent()) {
15926     if (getLangOpts().CPlusPlus)
15927       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15928 
15929     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15930     if (ERes.isInvalid())
15931       return ExprError();
15932     E = ERes.get();
15933 
15934     QualType T = E->getType();
15935     if (!T->isScalarType()) { // C99 6.8.4.1p1
15936       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15937         << T << E->getSourceRange();
15938       return ExprError();
15939     }
15940     CheckBoolLikeConversion(E, Loc);
15941   }
15942 
15943   return E;
15944 }
15945 
15946 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15947                                            Expr *SubExpr, ConditionKind CK) {
15948   // Empty conditions are valid in for-statements.
15949   if (!SubExpr)
15950     return ConditionResult();
15951 
15952   ExprResult Cond;
15953   switch (CK) {
15954   case ConditionKind::Boolean:
15955     Cond = CheckBooleanCondition(Loc, SubExpr);
15956     break;
15957 
15958   case ConditionKind::ConstexprIf:
15959     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15960     break;
15961 
15962   case ConditionKind::Switch:
15963     Cond = CheckSwitchCondition(Loc, SubExpr);
15964     break;
15965   }
15966   if (Cond.isInvalid())
15967     return ConditionError();
15968 
15969   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15970   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15971   if (!FullExpr.get())
15972     return ConditionError();
15973 
15974   return ConditionResult(*this, nullptr, FullExpr,
15975                          CK == ConditionKind::ConstexprIf);
15976 }
15977 
15978 namespace {
15979   /// A visitor for rebuilding a call to an __unknown_any expression
15980   /// to have an appropriate type.
15981   struct RebuildUnknownAnyFunction
15982     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15983 
15984     Sema &S;
15985 
15986     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15987 
15988     ExprResult VisitStmt(Stmt *S) {
15989       llvm_unreachable("unexpected statement!");
15990     }
15991 
15992     ExprResult VisitExpr(Expr *E) {
15993       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15994         << E->getSourceRange();
15995       return ExprError();
15996     }
15997 
15998     /// Rebuild an expression which simply semantically wraps another
15999     /// expression which it shares the type and value kind of.
16000     template <class T> ExprResult rebuildSugarExpr(T *E) {
16001       ExprResult SubResult = Visit(E->getSubExpr());
16002       if (SubResult.isInvalid()) return ExprError();
16003 
16004       Expr *SubExpr = SubResult.get();
16005       E->setSubExpr(SubExpr);
16006       E->setType(SubExpr->getType());
16007       E->setValueKind(SubExpr->getValueKind());
16008       assert(E->getObjectKind() == OK_Ordinary);
16009       return E;
16010     }
16011 
16012     ExprResult VisitParenExpr(ParenExpr *E) {
16013       return rebuildSugarExpr(E);
16014     }
16015 
16016     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16017       return rebuildSugarExpr(E);
16018     }
16019 
16020     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16021       ExprResult SubResult = Visit(E->getSubExpr());
16022       if (SubResult.isInvalid()) return ExprError();
16023 
16024       Expr *SubExpr = SubResult.get();
16025       E->setSubExpr(SubExpr);
16026       E->setType(S.Context.getPointerType(SubExpr->getType()));
16027       assert(E->getValueKind() == VK_RValue);
16028       assert(E->getObjectKind() == OK_Ordinary);
16029       return E;
16030     }
16031 
16032     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16033       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16034 
16035       E->setType(VD->getType());
16036 
16037       assert(E->getValueKind() == VK_RValue);
16038       if (S.getLangOpts().CPlusPlus &&
16039           !(isa<CXXMethodDecl>(VD) &&
16040             cast<CXXMethodDecl>(VD)->isInstance()))
16041         E->setValueKind(VK_LValue);
16042 
16043       return E;
16044     }
16045 
16046     ExprResult VisitMemberExpr(MemberExpr *E) {
16047       return resolveDecl(E, E->getMemberDecl());
16048     }
16049 
16050     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16051       return resolveDecl(E, E->getDecl());
16052     }
16053   };
16054 }
16055 
16056 /// Given a function expression of unknown-any type, try to rebuild it
16057 /// to have a function type.
16058 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16059   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16060   if (Result.isInvalid()) return ExprError();
16061   return S.DefaultFunctionArrayConversion(Result.get());
16062 }
16063 
16064 namespace {
16065   /// A visitor for rebuilding an expression of type __unknown_anytype
16066   /// into one which resolves the type directly on the referring
16067   /// expression.  Strict preservation of the original source
16068   /// structure is not a goal.
16069   struct RebuildUnknownAnyExpr
16070     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16071 
16072     Sema &S;
16073 
16074     /// The current destination type.
16075     QualType DestType;
16076 
16077     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16078       : S(S), DestType(CastType) {}
16079 
16080     ExprResult VisitStmt(Stmt *S) {
16081       llvm_unreachable("unexpected statement!");
16082     }
16083 
16084     ExprResult VisitExpr(Expr *E) {
16085       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16086         << E->getSourceRange();
16087       return ExprError();
16088     }
16089 
16090     ExprResult VisitCallExpr(CallExpr *E);
16091     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16092 
16093     /// Rebuild an expression which simply semantically wraps another
16094     /// expression which it shares the type and value kind of.
16095     template <class T> ExprResult rebuildSugarExpr(T *E) {
16096       ExprResult SubResult = Visit(E->getSubExpr());
16097       if (SubResult.isInvalid()) return ExprError();
16098       Expr *SubExpr = SubResult.get();
16099       E->setSubExpr(SubExpr);
16100       E->setType(SubExpr->getType());
16101       E->setValueKind(SubExpr->getValueKind());
16102       assert(E->getObjectKind() == OK_Ordinary);
16103       return E;
16104     }
16105 
16106     ExprResult VisitParenExpr(ParenExpr *E) {
16107       return rebuildSugarExpr(E);
16108     }
16109 
16110     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16111       return rebuildSugarExpr(E);
16112     }
16113 
16114     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16115       const PointerType *Ptr = DestType->getAs<PointerType>();
16116       if (!Ptr) {
16117         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16118           << E->getSourceRange();
16119         return ExprError();
16120       }
16121 
16122       if (isa<CallExpr>(E->getSubExpr())) {
16123         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16124           << E->getSourceRange();
16125         return ExprError();
16126       }
16127 
16128       assert(E->getValueKind() == VK_RValue);
16129       assert(E->getObjectKind() == OK_Ordinary);
16130       E->setType(DestType);
16131 
16132       // Build the sub-expression as if it were an object of the pointee type.
16133       DestType = Ptr->getPointeeType();
16134       ExprResult SubResult = Visit(E->getSubExpr());
16135       if (SubResult.isInvalid()) return ExprError();
16136       E->setSubExpr(SubResult.get());
16137       return E;
16138     }
16139 
16140     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16141 
16142     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16143 
16144     ExprResult VisitMemberExpr(MemberExpr *E) {
16145       return resolveDecl(E, E->getMemberDecl());
16146     }
16147 
16148     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16149       return resolveDecl(E, E->getDecl());
16150     }
16151   };
16152 }
16153 
16154 /// Rebuilds a call expression which yielded __unknown_anytype.
16155 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16156   Expr *CalleeExpr = E->getCallee();
16157 
16158   enum FnKind {
16159     FK_MemberFunction,
16160     FK_FunctionPointer,
16161     FK_BlockPointer
16162   };
16163 
16164   FnKind Kind;
16165   QualType CalleeType = CalleeExpr->getType();
16166   if (CalleeType == S.Context.BoundMemberTy) {
16167     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16168     Kind = FK_MemberFunction;
16169     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16170   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16171     CalleeType = Ptr->getPointeeType();
16172     Kind = FK_FunctionPointer;
16173   } else {
16174     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16175     Kind = FK_BlockPointer;
16176   }
16177   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16178 
16179   // Verify that this is a legal result type of a function.
16180   if (DestType->isArrayType() || DestType->isFunctionType()) {
16181     unsigned diagID = diag::err_func_returning_array_function;
16182     if (Kind == FK_BlockPointer)
16183       diagID = diag::err_block_returning_array_function;
16184 
16185     S.Diag(E->getExprLoc(), diagID)
16186       << DestType->isFunctionType() << DestType;
16187     return ExprError();
16188   }
16189 
16190   // Otherwise, go ahead and set DestType as the call's result.
16191   E->setType(DestType.getNonLValueExprType(S.Context));
16192   E->setValueKind(Expr::getValueKindForType(DestType));
16193   assert(E->getObjectKind() == OK_Ordinary);
16194 
16195   // Rebuild the function type, replacing the result type with DestType.
16196   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16197   if (Proto) {
16198     // __unknown_anytype(...) is a special case used by the debugger when
16199     // it has no idea what a function's signature is.
16200     //
16201     // We want to build this call essentially under the K&R
16202     // unprototyped rules, but making a FunctionNoProtoType in C++
16203     // would foul up all sorts of assumptions.  However, we cannot
16204     // simply pass all arguments as variadic arguments, nor can we
16205     // portably just call the function under a non-variadic type; see
16206     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16207     // However, it turns out that in practice it is generally safe to
16208     // call a function declared as "A foo(B,C,D);" under the prototype
16209     // "A foo(B,C,D,...);".  The only known exception is with the
16210     // Windows ABI, where any variadic function is implicitly cdecl
16211     // regardless of its normal CC.  Therefore we change the parameter
16212     // types to match the types of the arguments.
16213     //
16214     // This is a hack, but it is far superior to moving the
16215     // corresponding target-specific code from IR-gen to Sema/AST.
16216 
16217     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16218     SmallVector<QualType, 8> ArgTypes;
16219     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16220       ArgTypes.reserve(E->getNumArgs());
16221       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16222         Expr *Arg = E->getArg(i);
16223         QualType ArgType = Arg->getType();
16224         if (E->isLValue()) {
16225           ArgType = S.Context.getLValueReferenceType(ArgType);
16226         } else if (E->isXValue()) {
16227           ArgType = S.Context.getRValueReferenceType(ArgType);
16228         }
16229         ArgTypes.push_back(ArgType);
16230       }
16231       ParamTypes = ArgTypes;
16232     }
16233     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16234                                          Proto->getExtProtoInfo());
16235   } else {
16236     DestType = S.Context.getFunctionNoProtoType(DestType,
16237                                                 FnType->getExtInfo());
16238   }
16239 
16240   // Rebuild the appropriate pointer-to-function type.
16241   switch (Kind) {
16242   case FK_MemberFunction:
16243     // Nothing to do.
16244     break;
16245 
16246   case FK_FunctionPointer:
16247     DestType = S.Context.getPointerType(DestType);
16248     break;
16249 
16250   case FK_BlockPointer:
16251     DestType = S.Context.getBlockPointerType(DestType);
16252     break;
16253   }
16254 
16255   // Finally, we can recurse.
16256   ExprResult CalleeResult = Visit(CalleeExpr);
16257   if (!CalleeResult.isUsable()) return ExprError();
16258   E->setCallee(CalleeResult.get());
16259 
16260   // Bind a temporary if necessary.
16261   return S.MaybeBindToTemporary(E);
16262 }
16263 
16264 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16265   // Verify that this is a legal result type of a call.
16266   if (DestType->isArrayType() || DestType->isFunctionType()) {
16267     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16268       << DestType->isFunctionType() << DestType;
16269     return ExprError();
16270   }
16271 
16272   // Rewrite the method result type if available.
16273   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16274     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16275     Method->setReturnType(DestType);
16276   }
16277 
16278   // Change the type of the message.
16279   E->setType(DestType.getNonReferenceType());
16280   E->setValueKind(Expr::getValueKindForType(DestType));
16281 
16282   return S.MaybeBindToTemporary(E);
16283 }
16284 
16285 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16286   // The only case we should ever see here is a function-to-pointer decay.
16287   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16288     assert(E->getValueKind() == VK_RValue);
16289     assert(E->getObjectKind() == OK_Ordinary);
16290 
16291     E->setType(DestType);
16292 
16293     // Rebuild the sub-expression as the pointee (function) type.
16294     DestType = DestType->castAs<PointerType>()->getPointeeType();
16295 
16296     ExprResult Result = Visit(E->getSubExpr());
16297     if (!Result.isUsable()) return ExprError();
16298 
16299     E->setSubExpr(Result.get());
16300     return E;
16301   } else if (E->getCastKind() == CK_LValueToRValue) {
16302     assert(E->getValueKind() == VK_RValue);
16303     assert(E->getObjectKind() == OK_Ordinary);
16304 
16305     assert(isa<BlockPointerType>(E->getType()));
16306 
16307     E->setType(DestType);
16308 
16309     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16310     DestType = S.Context.getLValueReferenceType(DestType);
16311 
16312     ExprResult Result = Visit(E->getSubExpr());
16313     if (!Result.isUsable()) return ExprError();
16314 
16315     E->setSubExpr(Result.get());
16316     return E;
16317   } else {
16318     llvm_unreachable("Unhandled cast type!");
16319   }
16320 }
16321 
16322 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16323   ExprValueKind ValueKind = VK_LValue;
16324   QualType Type = DestType;
16325 
16326   // We know how to make this work for certain kinds of decls:
16327 
16328   //  - functions
16329   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16330     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16331       DestType = Ptr->getPointeeType();
16332       ExprResult Result = resolveDecl(E, VD);
16333       if (Result.isInvalid()) return ExprError();
16334       return S.ImpCastExprToType(Result.get(), Type,
16335                                  CK_FunctionToPointerDecay, VK_RValue);
16336     }
16337 
16338     if (!Type->isFunctionType()) {
16339       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16340         << VD << E->getSourceRange();
16341       return ExprError();
16342     }
16343     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16344       // We must match the FunctionDecl's type to the hack introduced in
16345       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16346       // type. See the lengthy commentary in that routine.
16347       QualType FDT = FD->getType();
16348       const FunctionType *FnType = FDT->castAs<FunctionType>();
16349       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16350       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16351       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16352         SourceLocation Loc = FD->getLocation();
16353         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16354                                       FD->getDeclContext(),
16355                                       Loc, Loc, FD->getNameInfo().getName(),
16356                                       DestType, FD->getTypeSourceInfo(),
16357                                       SC_None, false/*isInlineSpecified*/,
16358                                       FD->hasPrototype(),
16359                                       false/*isConstexprSpecified*/);
16360 
16361         if (FD->getQualifier())
16362           NewFD->setQualifierInfo(FD->getQualifierLoc());
16363 
16364         SmallVector<ParmVarDecl*, 16> Params;
16365         for (const auto &AI : FT->param_types()) {
16366           ParmVarDecl *Param =
16367             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16368           Param->setScopeInfo(0, Params.size());
16369           Params.push_back(Param);
16370         }
16371         NewFD->setParams(Params);
16372         DRE->setDecl(NewFD);
16373         VD = DRE->getDecl();
16374       }
16375     }
16376 
16377     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16378       if (MD->isInstance()) {
16379         ValueKind = VK_RValue;
16380         Type = S.Context.BoundMemberTy;
16381       }
16382 
16383     // Function references aren't l-values in C.
16384     if (!S.getLangOpts().CPlusPlus)
16385       ValueKind = VK_RValue;
16386 
16387   //  - variables
16388   } else if (isa<VarDecl>(VD)) {
16389     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16390       Type = RefTy->getPointeeType();
16391     } else if (Type->isFunctionType()) {
16392       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16393         << VD << E->getSourceRange();
16394       return ExprError();
16395     }
16396 
16397   //  - nothing else
16398   } else {
16399     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16400       << VD << E->getSourceRange();
16401     return ExprError();
16402   }
16403 
16404   // Modifying the declaration like this is friendly to IR-gen but
16405   // also really dangerous.
16406   VD->setType(DestType);
16407   E->setType(Type);
16408   E->setValueKind(ValueKind);
16409   return E;
16410 }
16411 
16412 /// Check a cast of an unknown-any type.  We intentionally only
16413 /// trigger this for C-style casts.
16414 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16415                                      Expr *CastExpr, CastKind &CastKind,
16416                                      ExprValueKind &VK, CXXCastPath &Path) {
16417   // The type we're casting to must be either void or complete.
16418   if (!CastType->isVoidType() &&
16419       RequireCompleteType(TypeRange.getBegin(), CastType,
16420                           diag::err_typecheck_cast_to_incomplete))
16421     return ExprError();
16422 
16423   // Rewrite the casted expression from scratch.
16424   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16425   if (!result.isUsable()) return ExprError();
16426 
16427   CastExpr = result.get();
16428   VK = CastExpr->getValueKind();
16429   CastKind = CK_NoOp;
16430 
16431   return CastExpr;
16432 }
16433 
16434 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16435   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16436 }
16437 
16438 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16439                                     Expr *arg, QualType &paramType) {
16440   // If the syntactic form of the argument is not an explicit cast of
16441   // any sort, just do default argument promotion.
16442   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16443   if (!castArg) {
16444     ExprResult result = DefaultArgumentPromotion(arg);
16445     if (result.isInvalid()) return ExprError();
16446     paramType = result.get()->getType();
16447     return result;
16448   }
16449 
16450   // Otherwise, use the type that was written in the explicit cast.
16451   assert(!arg->hasPlaceholderType());
16452   paramType = castArg->getTypeAsWritten();
16453 
16454   // Copy-initialize a parameter of that type.
16455   InitializedEntity entity =
16456     InitializedEntity::InitializeParameter(Context, paramType,
16457                                            /*consumed*/ false);
16458   return PerformCopyInitialization(entity, callLoc, arg);
16459 }
16460 
16461 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16462   Expr *orig = E;
16463   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16464   while (true) {
16465     E = E->IgnoreParenImpCasts();
16466     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16467       E = call->getCallee();
16468       diagID = diag::err_uncasted_call_of_unknown_any;
16469     } else {
16470       break;
16471     }
16472   }
16473 
16474   SourceLocation loc;
16475   NamedDecl *d;
16476   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16477     loc = ref->getLocation();
16478     d = ref->getDecl();
16479   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16480     loc = mem->getMemberLoc();
16481     d = mem->getMemberDecl();
16482   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16483     diagID = diag::err_uncasted_call_of_unknown_any;
16484     loc = msg->getSelectorStartLoc();
16485     d = msg->getMethodDecl();
16486     if (!d) {
16487       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16488         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16489         << orig->getSourceRange();
16490       return ExprError();
16491     }
16492   } else {
16493     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16494       << E->getSourceRange();
16495     return ExprError();
16496   }
16497 
16498   S.Diag(loc, diagID) << d << orig->getSourceRange();
16499 
16500   // Never recoverable.
16501   return ExprError();
16502 }
16503 
16504 /// Check for operands with placeholder types and complain if found.
16505 /// Returns ExprError() if there was an error and no recovery was possible.
16506 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16507   if (!getLangOpts().CPlusPlus) {
16508     // C cannot handle TypoExpr nodes on either side of a binop because it
16509     // doesn't handle dependent types properly, so make sure any TypoExprs have
16510     // been dealt with before checking the operands.
16511     ExprResult Result = CorrectDelayedTyposInExpr(E);
16512     if (!Result.isUsable()) return ExprError();
16513     E = Result.get();
16514   }
16515 
16516   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16517   if (!placeholderType) return E;
16518 
16519   switch (placeholderType->getKind()) {
16520 
16521   // Overloaded expressions.
16522   case BuiltinType::Overload: {
16523     // Try to resolve a single function template specialization.
16524     // This is obligatory.
16525     ExprResult Result = E;
16526     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16527       return Result;
16528 
16529     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16530     // leaves Result unchanged on failure.
16531     Result = E;
16532     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16533       return Result;
16534 
16535     // If that failed, try to recover with a call.
16536     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16537                          /*complain*/ true);
16538     return Result;
16539   }
16540 
16541   // Bound member functions.
16542   case BuiltinType::BoundMember: {
16543     ExprResult result = E;
16544     const Expr *BME = E->IgnoreParens();
16545     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16546     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16547     if (isa<CXXPseudoDestructorExpr>(BME)) {
16548       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16549     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16550       if (ME->getMemberNameInfo().getName().getNameKind() ==
16551           DeclarationName::CXXDestructorName)
16552         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16553     }
16554     tryToRecoverWithCall(result, PD,
16555                          /*complain*/ true);
16556     return result;
16557   }
16558 
16559   // ARC unbridged casts.
16560   case BuiltinType::ARCUnbridgedCast: {
16561     Expr *realCast = stripARCUnbridgedCast(E);
16562     diagnoseARCUnbridgedCast(realCast);
16563     return realCast;
16564   }
16565 
16566   // Expressions of unknown type.
16567   case BuiltinType::UnknownAny:
16568     return diagnoseUnknownAnyExpr(*this, E);
16569 
16570   // Pseudo-objects.
16571   case BuiltinType::PseudoObject:
16572     return checkPseudoObjectRValue(E);
16573 
16574   case BuiltinType::BuiltinFn: {
16575     // Accept __noop without parens by implicitly converting it to a call expr.
16576     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16577     if (DRE) {
16578       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16579       if (FD->getBuiltinID() == Builtin::BI__noop) {
16580         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16581                               CK_BuiltinFnToFnPtr).get();
16582         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16583                                       VK_RValue, SourceLocation());
16584       }
16585     }
16586 
16587     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16588     return ExprError();
16589   }
16590 
16591   // Expressions of unknown type.
16592   case BuiltinType::OMPArraySection:
16593     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16594     return ExprError();
16595 
16596   // Everything else should be impossible.
16597 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16598   case BuiltinType::Id:
16599 #include "clang/Basic/OpenCLImageTypes.def"
16600 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16601   case BuiltinType::Id:
16602 #include "clang/Basic/OpenCLExtensionTypes.def"
16603 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16604 #define PLACEHOLDER_TYPE(Id, SingletonId)
16605 #include "clang/AST/BuiltinTypes.def"
16606     break;
16607   }
16608 
16609   llvm_unreachable("invalid placeholder type!");
16610 }
16611 
16612 bool Sema::CheckCaseExpression(Expr *E) {
16613   if (E->isTypeDependent())
16614     return true;
16615   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16616     return E->getType()->isIntegralOrEnumerationType();
16617   return false;
16618 }
16619 
16620 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16621 ExprResult
16622 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16623   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16624          "Unknown Objective-C Boolean value!");
16625   QualType BoolT = Context.ObjCBuiltinBoolTy;
16626   if (!Context.getBOOLDecl()) {
16627     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16628                         Sema::LookupOrdinaryName);
16629     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16630       NamedDecl *ND = Result.getFoundDecl();
16631       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16632         Context.setBOOLDecl(TD);
16633     }
16634   }
16635   if (Context.getBOOLDecl())
16636     BoolT = Context.getBOOLType();
16637   return new (Context)
16638       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16639 }
16640 
16641 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16642     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16643     SourceLocation RParen) {
16644 
16645   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16646 
16647   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16648                            [&](const AvailabilitySpec &Spec) {
16649                              return Spec.getPlatform() == Platform;
16650                            });
16651 
16652   VersionTuple Version;
16653   if (Spec != AvailSpecs.end())
16654     Version = Spec->getVersion();
16655 
16656   // The use of `@available` in the enclosing function should be analyzed to
16657   // warn when it's used inappropriately (i.e. not if(@available)).
16658   if (getCurFunctionOrMethodDecl())
16659     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16660   else if (getCurBlock() || getCurLambda())
16661     getCurFunction()->HasPotentialAvailabilityViolations = true;
16662 
16663   return new (Context)
16664       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16665 }
16666