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   SourceLocation Loc = Locs.front();
211   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
212     // If there were any diagnostics suppressed by template argument deduction,
213     // emit them now.
214     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
215     if (Pos != SuppressedDiagnostics.end()) {
216       for (const PartialDiagnosticAt &Suppressed : Pos->second)
217         Diag(Suppressed.first, Suppressed.second);
218 
219       // Clear out the list of suppressed diagnostics, so that we don't emit
220       // them again for this specialization. However, we don't obsolete this
221       // entry from the table, because we want to avoid ever emitting these
222       // diagnostics again.
223       Pos->second.clear();
224     }
225 
226     // C++ [basic.start.main]p3:
227     //   The function 'main' shall not be used within a program.
228     if (cast<FunctionDecl>(D)->isMain())
229       Diag(Loc, diag::ext_main_used);
230   }
231 
232   // See if this is an auto-typed variable whose initializer we are parsing.
233   if (ParsingInitForAutoVars.count(D)) {
234     if (isa<BindingDecl>(D)) {
235       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
236         << D->getDeclName();
237     } else {
238       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
239         << D->getDeclName() << cast<VarDecl>(D)->getType();
240     }
241     return true;
242   }
243 
244   // See if this is a deleted function.
245   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
246     if (FD->isDeleted()) {
247       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
248       if (Ctor && Ctor->isInheritingConstructor())
249         Diag(Loc, diag::err_deleted_inherited_ctor_use)
250             << Ctor->getParent()
251             << Ctor->getInheritedConstructor().getConstructor()->getParent();
252       else
253         Diag(Loc, diag::err_deleted_function_use);
254       NoteDeletedFunction(FD);
255       return true;
256     }
257 
258     // If the function has a deduced return type, and we can't deduce it,
259     // then we can't use it either.
260     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
261         DeduceReturnType(FD, Loc))
262       return true;
263 
264     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
265       return true;
266   }
267 
268   auto getReferencedObjCProp = [](const NamedDecl *D) ->
269                                       const ObjCPropertyDecl * {
270     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
271       return MD->findPropertyDecl();
272     return nullptr;
273   };
274   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
275     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
276       return true;
277   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
278       return true;
279   }
280 
281   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
282   // Only the variables omp_in and omp_out are allowed in the combiner.
283   // Only the variables omp_priv and omp_orig are allowed in the
284   // initializer-clause.
285   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
286   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
287       isa<VarDecl>(D)) {
288     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
289         << getCurFunction()->HasOMPDeclareReductionCombiner;
290     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
291     return true;
292   }
293 
294   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
295                              AvoidPartialAvailabilityChecks);
296 
297   DiagnoseUnusedOfDecl(*this, D, Loc);
298 
299   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
300 
301   return false;
302 }
303 
304 /// Retrieve the message suffix that should be added to a
305 /// diagnostic complaining about the given function being deleted or
306 /// unavailable.
307 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
308   std::string Message;
309   if (FD->getAvailability(&Message))
310     return ": " + Message;
311 
312   return std::string();
313 }
314 
315 /// DiagnoseSentinelCalls - This routine checks whether a call or
316 /// message-send is to a declaration with the sentinel attribute, and
317 /// if so, it checks that the requirements of the sentinel are
318 /// satisfied.
319 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
320                                  ArrayRef<Expr *> Args) {
321   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
322   if (!attr)
323     return;
324 
325   // The number of formal parameters of the declaration.
326   unsigned numFormalParams;
327 
328   // The kind of declaration.  This is also an index into a %select in
329   // the diagnostic.
330   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
331 
332   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
333     numFormalParams = MD->param_size();
334     calleeType = CT_Method;
335   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
336     numFormalParams = FD->param_size();
337     calleeType = CT_Function;
338   } else if (isa<VarDecl>(D)) {
339     QualType type = cast<ValueDecl>(D)->getType();
340     const FunctionType *fn = nullptr;
341     if (const PointerType *ptr = type->getAs<PointerType>()) {
342       fn = ptr->getPointeeType()->getAs<FunctionType>();
343       if (!fn) return;
344       calleeType = CT_Function;
345     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
346       fn = ptr->getPointeeType()->castAs<FunctionType>();
347       calleeType = CT_Block;
348     } else {
349       return;
350     }
351 
352     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
353       numFormalParams = proto->getNumParams();
354     } else {
355       numFormalParams = 0;
356     }
357   } else {
358     return;
359   }
360 
361   // "nullPos" is the number of formal parameters at the end which
362   // effectively count as part of the variadic arguments.  This is
363   // useful if you would prefer to not have *any* formal parameters,
364   // but the language forces you to have at least one.
365   unsigned nullPos = attr->getNullPos();
366   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
367   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
368 
369   // The number of arguments which should follow the sentinel.
370   unsigned numArgsAfterSentinel = attr->getSentinel();
371 
372   // If there aren't enough arguments for all the formal parameters,
373   // the sentinel, and the args after the sentinel, complain.
374   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
375     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
376     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
377     return;
378   }
379 
380   // Otherwise, find the sentinel expression.
381   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
382   if (!sentinelExpr) return;
383   if (sentinelExpr->isValueDependent()) return;
384   if (Context.isSentinelNullExpr(sentinelExpr)) return;
385 
386   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
387   // or 'NULL' if those are actually defined in the context.  Only use
388   // 'nil' for ObjC methods, where it's much more likely that the
389   // variadic arguments form a list of object pointers.
390   SourceLocation MissingNilLoc
391     = getLocForEndOfToken(sentinelExpr->getLocEnd());
392   std::string NullValue;
393   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
394     NullValue = "nil";
395   else if (getLangOpts().CPlusPlus11)
396     NullValue = "nullptr";
397   else if (PP.isMacroDefined("NULL"))
398     NullValue = "NULL";
399   else
400     NullValue = "(void*) 0";
401 
402   if (MissingNilLoc.isInvalid())
403     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
404   else
405     Diag(MissingNilLoc, diag::warn_missing_sentinel)
406       << int(calleeType)
407       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
408   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
409 }
410 
411 SourceRange Sema::getExprRange(Expr *E) const {
412   return E ? E->getSourceRange() : SourceRange();
413 }
414 
415 //===----------------------------------------------------------------------===//
416 //  Standard Promotions and Conversions
417 //===----------------------------------------------------------------------===//
418 
419 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
420 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
421   // Handle any placeholder expressions which made it here.
422   if (E->getType()->isPlaceholderType()) {
423     ExprResult result = CheckPlaceholderExpr(E);
424     if (result.isInvalid()) return ExprError();
425     E = result.get();
426   }
427 
428   QualType Ty = E->getType();
429   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
430 
431   if (Ty->isFunctionType()) {
432     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
433       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
434         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
435           return ExprError();
436 
437     E = ImpCastExprToType(E, Context.getPointerType(Ty),
438                           CK_FunctionToPointerDecay).get();
439   } else if (Ty->isArrayType()) {
440     // In C90 mode, arrays only promote to pointers if the array expression is
441     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
442     // type 'array of type' is converted to an expression that has type 'pointer
443     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
444     // that has type 'array of type' ...".  The relevant change is "an lvalue"
445     // (C90) to "an expression" (C99).
446     //
447     // C++ 4.2p1:
448     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
449     // T" can be converted to an rvalue of type "pointer to T".
450     //
451     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
452       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
453                             CK_ArrayToPointerDecay).get();
454   }
455   return E;
456 }
457 
458 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
459   // Check to see if we are dereferencing a null pointer.  If so,
460   // and if not volatile-qualified, this is undefined behavior that the
461   // optimizer will delete, so warn about it.  People sometimes try to use this
462   // to get a deterministic trap and are surprised by clang's behavior.  This
463   // only handles the pattern "*null", which is a very syntactic check.
464   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
465     if (UO->getOpcode() == UO_Deref &&
466         UO->getSubExpr()->IgnoreParenCasts()->
467           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
468         !UO->getType().isVolatileQualified()) {
469     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
470                           S.PDiag(diag::warn_indirection_through_null)
471                             << UO->getSubExpr()->getSourceRange());
472     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
473                         S.PDiag(diag::note_indirection_through_null));
474   }
475 }
476 
477 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
478                                     SourceLocation AssignLoc,
479                                     const Expr* RHS) {
480   const ObjCIvarDecl *IV = OIRE->getDecl();
481   if (!IV)
482     return;
483 
484   DeclarationName MemberName = IV->getDeclName();
485   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
486   if (!Member || !Member->isStr("isa"))
487     return;
488 
489   const Expr *Base = OIRE->getBase();
490   QualType BaseType = Base->getType();
491   if (OIRE->isArrow())
492     BaseType = BaseType->getPointeeType();
493   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
494     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
495       ObjCInterfaceDecl *ClassDeclared = nullptr;
496       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
497       if (!ClassDeclared->getSuperClass()
498           && (*ClassDeclared->ivar_begin()) == IV) {
499         if (RHS) {
500           NamedDecl *ObjectSetClass =
501             S.LookupSingleName(S.TUScope,
502                                &S.Context.Idents.get("object_setClass"),
503                                SourceLocation(), S.LookupOrdinaryName);
504           if (ObjectSetClass) {
505             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
506             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
507             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
508             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
509                                                      AssignLoc), ",") <<
510             FixItHint::CreateInsertion(RHSLocEnd, ")");
511           }
512           else
513             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
514         } else {
515           NamedDecl *ObjectGetClass =
516             S.LookupSingleName(S.TUScope,
517                                &S.Context.Idents.get("object_getClass"),
518                                SourceLocation(), S.LookupOrdinaryName);
519           if (ObjectGetClass)
520             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
521             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
522             FixItHint::CreateReplacement(
523                                          SourceRange(OIRE->getOpLoc(),
524                                                      OIRE->getLocEnd()), ")");
525           else
526             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
527         }
528         S.Diag(IV->getLocation(), diag::note_ivar_decl);
529       }
530     }
531 }
532 
533 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
534   // Handle any placeholder expressions which made it here.
535   if (E->getType()->isPlaceholderType()) {
536     ExprResult result = CheckPlaceholderExpr(E);
537     if (result.isInvalid()) return ExprError();
538     E = result.get();
539   }
540 
541   // C++ [conv.lval]p1:
542   //   A glvalue of a non-function, non-array type T can be
543   //   converted to a prvalue.
544   if (!E->isGLValue()) return E;
545 
546   QualType T = E->getType();
547   assert(!T.isNull() && "r-value conversion on typeless expression?");
548 
549   // We don't want to throw lvalue-to-rvalue casts on top of
550   // expressions of certain types in C++.
551   if (getLangOpts().CPlusPlus &&
552       (E->getType() == Context.OverloadTy ||
553        T->isDependentType() ||
554        T->isRecordType()))
555     return E;
556 
557   // The C standard is actually really unclear on this point, and
558   // DR106 tells us what the result should be but not why.  It's
559   // generally best to say that void types just doesn't undergo
560   // lvalue-to-rvalue at all.  Note that expressions of unqualified
561   // 'void' type are never l-values, but qualified void can be.
562   if (T->isVoidType())
563     return E;
564 
565   // OpenCL usually rejects direct accesses to values of 'half' type.
566   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
567       T->isHalfType()) {
568     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
569       << 0 << T;
570     return ExprError();
571   }
572 
573   CheckForNullPointerDereference(*this, E);
574   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
575     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
576                                      &Context.Idents.get("object_getClass"),
577                                      SourceLocation(), LookupOrdinaryName);
578     if (ObjectGetClass)
579       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
580         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
581         FixItHint::CreateReplacement(
582                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
583     else
584       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
585   }
586   else if (const ObjCIvarRefExpr *OIRE =
587             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
588     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
589 
590   // C++ [conv.lval]p1:
591   //   [...] If T is a non-class type, the type of the prvalue is the
592   //   cv-unqualified version of T. Otherwise, the type of the
593   //   rvalue is T.
594   //
595   // C99 6.3.2.1p2:
596   //   If the lvalue has qualified type, the value has the unqualified
597   //   version of the type of the lvalue; otherwise, the value has the
598   //   type of the lvalue.
599   if (T.hasQualifiers())
600     T = T.getUnqualifiedType();
601 
602   // Under the MS ABI, lock down the inheritance model now.
603   if (T->isMemberPointerType() &&
604       Context.getTargetInfo().getCXXABI().isMicrosoft())
605     (void)isCompleteType(E->getExprLoc(), T);
606 
607   UpdateMarkingForLValueToRValue(E);
608 
609   // Loading a __weak object implicitly retains the value, so we need a cleanup to
610   // balance that.
611   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
612     Cleanup.setExprNeedsCleanups(true);
613 
614   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
615                                             nullptr, VK_RValue);
616 
617   // C11 6.3.2.1p2:
618   //   ... if the lvalue has atomic type, the value has the non-atomic version
619   //   of the type of the lvalue ...
620   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
621     T = Atomic->getValueType().getUnqualifiedType();
622     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
623                                    nullptr, VK_RValue);
624   }
625 
626   return Res;
627 }
628 
629 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
630   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
631   if (Res.isInvalid())
632     return ExprError();
633   Res = DefaultLvalueConversion(Res.get());
634   if (Res.isInvalid())
635     return ExprError();
636   return Res;
637 }
638 
639 /// CallExprUnaryConversions - a special case of an unary conversion
640 /// performed on a function designator of a call expression.
641 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
642   QualType Ty = E->getType();
643   ExprResult Res = E;
644   // Only do implicit cast for a function type, but not for a pointer
645   // to function type.
646   if (Ty->isFunctionType()) {
647     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
648                             CK_FunctionToPointerDecay).get();
649     if (Res.isInvalid())
650       return ExprError();
651   }
652   Res = DefaultLvalueConversion(Res.get());
653   if (Res.isInvalid())
654     return ExprError();
655   return Res.get();
656 }
657 
658 /// UsualUnaryConversions - Performs various conversions that are common to most
659 /// operators (C99 6.3). The conversions of array and function types are
660 /// sometimes suppressed. For example, the array->pointer conversion doesn't
661 /// apply if the array is an argument to the sizeof or address (&) operators.
662 /// In these instances, this routine should *not* be called.
663 ExprResult Sema::UsualUnaryConversions(Expr *E) {
664   // First, convert to an r-value.
665   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
666   if (Res.isInvalid())
667     return ExprError();
668   E = Res.get();
669 
670   QualType Ty = E->getType();
671   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
672 
673   // Half FP have to be promoted to float unless it is natively supported
674   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
675     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
676 
677   // Try to perform integral promotions if the object has a theoretically
678   // promotable type.
679   if (Ty->isIntegralOrUnscopedEnumerationType()) {
680     // C99 6.3.1.1p2:
681     //
682     //   The following may be used in an expression wherever an int or
683     //   unsigned int may be used:
684     //     - an object or expression with an integer type whose integer
685     //       conversion rank is less than or equal to the rank of int
686     //       and unsigned int.
687     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
688     //
689     //   If an int can represent all values of the original type, the
690     //   value is converted to an int; otherwise, it is converted to an
691     //   unsigned int. These are called the integer promotions. All
692     //   other types are unchanged by the integer promotions.
693 
694     QualType PTy = Context.isPromotableBitField(E);
695     if (!PTy.isNull()) {
696       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
697       return E;
698     }
699     if (Ty->isPromotableIntegerType()) {
700       QualType PT = Context.getPromotedIntegerType(Ty);
701       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
702       return E;
703     }
704   }
705   return E;
706 }
707 
708 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
709 /// do not have a prototype. Arguments that have type float or __fp16
710 /// are promoted to double. All other argument types are converted by
711 /// UsualUnaryConversions().
712 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
713   QualType Ty = E->getType();
714   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
715 
716   ExprResult Res = UsualUnaryConversions(E);
717   if (Res.isInvalid())
718     return ExprError();
719   E = Res.get();
720 
721   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
722   // promote to double.
723   // Note that default argument promotion applies only to float (and
724   // half/fp16); it does not apply to _Float16.
725   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
726   if (BTy && (BTy->getKind() == BuiltinType::Half ||
727               BTy->getKind() == BuiltinType::Float)) {
728     if (getLangOpts().OpenCL &&
729         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
730         if (BTy->getKind() == BuiltinType::Half) {
731             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
732         }
733     } else {
734       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
735     }
736   }
737 
738   // C++ performs lvalue-to-rvalue conversion as a default argument
739   // promotion, even on class types, but note:
740   //   C++11 [conv.lval]p2:
741   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
742   //     operand or a subexpression thereof the value contained in the
743   //     referenced object is not accessed. Otherwise, if the glvalue
744   //     has a class type, the conversion copy-initializes a temporary
745   //     of type T from the glvalue and the result of the conversion
746   //     is a prvalue for the temporary.
747   // FIXME: add some way to gate this entire thing for correctness in
748   // potentially potentially evaluated contexts.
749   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
750     ExprResult Temp = PerformCopyInitialization(
751                        InitializedEntity::InitializeTemporary(E->getType()),
752                                                 E->getExprLoc(), E);
753     if (Temp.isInvalid())
754       return ExprError();
755     E = Temp.get();
756   }
757 
758   return E;
759 }
760 
761 /// Determine the degree of POD-ness for an expression.
762 /// Incomplete types are considered POD, since this check can be performed
763 /// when we're in an unevaluated context.
764 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
765   if (Ty->isIncompleteType()) {
766     // C++11 [expr.call]p7:
767     //   After these conversions, if the argument does not have arithmetic,
768     //   enumeration, pointer, pointer to member, or class type, the program
769     //   is ill-formed.
770     //
771     // Since we've already performed array-to-pointer and function-to-pointer
772     // decay, the only such type in C++ is cv void. This also handles
773     // initializer lists as variadic arguments.
774     if (Ty->isVoidType())
775       return VAK_Invalid;
776 
777     if (Ty->isObjCObjectType())
778       return VAK_Invalid;
779     return VAK_Valid;
780   }
781 
782   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
783     return VAK_Invalid;
784 
785   if (Ty.isCXX98PODType(Context))
786     return VAK_Valid;
787 
788   // C++11 [expr.call]p7:
789   //   Passing a potentially-evaluated argument of class type (Clause 9)
790   //   having a non-trivial copy constructor, a non-trivial move constructor,
791   //   or a non-trivial destructor, with no corresponding parameter,
792   //   is conditionally-supported with implementation-defined semantics.
793   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
794     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
795       if (!Record->hasNonTrivialCopyConstructor() &&
796           !Record->hasNonTrivialMoveConstructor() &&
797           !Record->hasNonTrivialDestructor())
798         return VAK_ValidInCXX11;
799 
800   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
801     return VAK_Valid;
802 
803   if (Ty->isObjCObjectType())
804     return VAK_Invalid;
805 
806   if (getLangOpts().MSVCCompat)
807     return VAK_MSVCUndefined;
808 
809   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
810   // permitted to reject them. We should consider doing so.
811   return VAK_Undefined;
812 }
813 
814 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
815   // Don't allow one to pass an Objective-C interface to a vararg.
816   const QualType &Ty = E->getType();
817   VarArgKind VAK = isValidVarArgType(Ty);
818 
819   // Complain about passing non-POD types through varargs.
820   switch (VAK) {
821   case VAK_ValidInCXX11:
822     DiagRuntimeBehavior(
823         E->getLocStart(), nullptr,
824         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
825           << Ty << CT);
826     LLVM_FALLTHROUGH;
827   case VAK_Valid:
828     if (Ty->isRecordType()) {
829       // This is unlikely to be what the user intended. If the class has a
830       // 'c_str' member function, the user probably meant to call that.
831       DiagRuntimeBehavior(E->getLocStart(), nullptr,
832                           PDiag(diag::warn_pass_class_arg_to_vararg)
833                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
834     }
835     break;
836 
837   case VAK_Undefined:
838   case VAK_MSVCUndefined:
839     DiagRuntimeBehavior(
840         E->getLocStart(), nullptr,
841         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
842           << getLangOpts().CPlusPlus11 << Ty << CT);
843     break;
844 
845   case VAK_Invalid:
846     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
847       Diag(E->getLocStart(),
848            diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
849     else if (Ty->isObjCObjectType())
850       DiagRuntimeBehavior(
851           E->getLocStart(), nullptr,
852           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
853             << Ty << CT);
854     else
855       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
856         << isa<InitListExpr>(E) << Ty << CT;
857     break;
858   }
859 }
860 
861 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
862 /// will create a trap if the resulting type is not a POD type.
863 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
864                                                   FunctionDecl *FDecl) {
865   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
866     // Strip the unbridged-cast placeholder expression off, if applicable.
867     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
868         (CT == VariadicMethod ||
869          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
870       E = stripARCUnbridgedCast(E);
871 
872     // Otherwise, do normal placeholder checking.
873     } else {
874       ExprResult ExprRes = CheckPlaceholderExpr(E);
875       if (ExprRes.isInvalid())
876         return ExprError();
877       E = ExprRes.get();
878     }
879   }
880 
881   ExprResult ExprRes = DefaultArgumentPromotion(E);
882   if (ExprRes.isInvalid())
883     return ExprError();
884   E = ExprRes.get();
885 
886   // Diagnostics regarding non-POD argument types are
887   // emitted along with format string checking in Sema::CheckFunctionCall().
888   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
889     // Turn this into a trap.
890     CXXScopeSpec SS;
891     SourceLocation TemplateKWLoc;
892     UnqualifiedId Name;
893     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
894                        E->getLocStart());
895     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
896                                           Name, true, false);
897     if (TrapFn.isInvalid())
898       return ExprError();
899 
900     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
901                                     E->getLocStart(), None,
902                                     E->getLocEnd());
903     if (Call.isInvalid())
904       return ExprError();
905 
906     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
907                                   Call.get(), E);
908     if (Comma.isInvalid())
909       return ExprError();
910     return Comma.get();
911   }
912 
913   if (!getLangOpts().CPlusPlus &&
914       RequireCompleteType(E->getExprLoc(), E->getType(),
915                           diag::err_call_incomplete_argument))
916     return ExprError();
917 
918   return E;
919 }
920 
921 /// Converts an integer to complex float type.  Helper function of
922 /// UsualArithmeticConversions()
923 ///
924 /// \return false if the integer expression is an integer type and is
925 /// successfully converted to the complex type.
926 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
927                                                   ExprResult &ComplexExpr,
928                                                   QualType IntTy,
929                                                   QualType ComplexTy,
930                                                   bool SkipCast) {
931   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
932   if (SkipCast) return false;
933   if (IntTy->isIntegerType()) {
934     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
935     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
936     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
937                                   CK_FloatingRealToComplex);
938   } else {
939     assert(IntTy->isComplexIntegerType());
940     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
941                                   CK_IntegralComplexToFloatingComplex);
942   }
943   return false;
944 }
945 
946 /// Handle arithmetic conversion with complex types.  Helper function of
947 /// UsualArithmeticConversions()
948 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
949                                              ExprResult &RHS, QualType LHSType,
950                                              QualType RHSType,
951                                              bool IsCompAssign) {
952   // if we have an integer operand, the result is the complex type.
953   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
954                                              /*skipCast*/false))
955     return LHSType;
956   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
957                                              /*skipCast*/IsCompAssign))
958     return RHSType;
959 
960   // This handles complex/complex, complex/float, or float/complex.
961   // When both operands are complex, the shorter operand is converted to the
962   // type of the longer, and that is the type of the result. This corresponds
963   // to what is done when combining two real floating-point operands.
964   // The fun begins when size promotion occur across type domains.
965   // From H&S 6.3.4: When one operand is complex and the other is a real
966   // floating-point type, the less precise type is converted, within it's
967   // real or complex domain, to the precision of the other type. For example,
968   // when combining a "long double" with a "double _Complex", the
969   // "double _Complex" is promoted to "long double _Complex".
970 
971   // Compute the rank of the two types, regardless of whether they are complex.
972   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
973 
974   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
975   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
976   QualType LHSElementType =
977       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
978   QualType RHSElementType =
979       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
980 
981   QualType ResultType = S.Context.getComplexType(LHSElementType);
982   if (Order < 0) {
983     // Promote the precision of the LHS if not an assignment.
984     ResultType = S.Context.getComplexType(RHSElementType);
985     if (!IsCompAssign) {
986       if (LHSComplexType)
987         LHS =
988             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
989       else
990         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
991     }
992   } else if (Order > 0) {
993     // Promote the precision of the RHS.
994     if (RHSComplexType)
995       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
996     else
997       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
998   }
999   return ResultType;
1000 }
1001 
1002 /// Handle arithmetic conversion from integer to float.  Helper function
1003 /// of UsualArithmeticConversions()
1004 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1005                                            ExprResult &IntExpr,
1006                                            QualType FloatTy, QualType IntTy,
1007                                            bool ConvertFloat, bool ConvertInt) {
1008   if (IntTy->isIntegerType()) {
1009     if (ConvertInt)
1010       // Convert intExpr to the lhs floating point type.
1011       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1012                                     CK_IntegralToFloating);
1013     return FloatTy;
1014   }
1015 
1016   // Convert both sides to the appropriate complex float.
1017   assert(IntTy->isComplexIntegerType());
1018   QualType result = S.Context.getComplexType(FloatTy);
1019 
1020   // _Complex int -> _Complex float
1021   if (ConvertInt)
1022     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1023                                   CK_IntegralComplexToFloatingComplex);
1024 
1025   // float -> _Complex float
1026   if (ConvertFloat)
1027     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1028                                     CK_FloatingRealToComplex);
1029 
1030   return result;
1031 }
1032 
1033 /// Handle arithmethic conversion with floating point types.  Helper
1034 /// function of UsualArithmeticConversions()
1035 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1036                                       ExprResult &RHS, QualType LHSType,
1037                                       QualType RHSType, bool IsCompAssign) {
1038   bool LHSFloat = LHSType->isRealFloatingType();
1039   bool RHSFloat = RHSType->isRealFloatingType();
1040 
1041   // If we have two real floating types, convert the smaller operand
1042   // to the bigger result.
1043   if (LHSFloat && RHSFloat) {
1044     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1045     if (order > 0) {
1046       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1047       return LHSType;
1048     }
1049 
1050     assert(order < 0 && "illegal float comparison");
1051     if (!IsCompAssign)
1052       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1053     return RHSType;
1054   }
1055 
1056   if (LHSFloat) {
1057     // Half FP has to be promoted to float unless it is natively supported
1058     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1059       LHSType = S.Context.FloatTy;
1060 
1061     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1062                                       /*convertFloat=*/!IsCompAssign,
1063                                       /*convertInt=*/ true);
1064   }
1065   assert(RHSFloat);
1066   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1067                                     /*convertInt=*/ true,
1068                                     /*convertFloat=*/!IsCompAssign);
1069 }
1070 
1071 /// Diagnose attempts to convert between __float128 and long double if
1072 /// there is no support for such conversion. Helper function of
1073 /// UsualArithmeticConversions().
1074 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1075                                       QualType RHSType) {
1076   /*  No issue converting if at least one of the types is not a floating point
1077       type or the two types have the same rank.
1078   */
1079   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1080       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1081     return false;
1082 
1083   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1084          "The remaining types must be floating point types.");
1085 
1086   auto *LHSComplex = LHSType->getAs<ComplexType>();
1087   auto *RHSComplex = RHSType->getAs<ComplexType>();
1088 
1089   QualType LHSElemType = LHSComplex ?
1090     LHSComplex->getElementType() : LHSType;
1091   QualType RHSElemType = RHSComplex ?
1092     RHSComplex->getElementType() : RHSType;
1093 
1094   // No issue if the two types have the same representation
1095   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1096       &S.Context.getFloatTypeSemantics(RHSElemType))
1097     return false;
1098 
1099   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1100                                 RHSElemType == S.Context.LongDoubleTy);
1101   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1102                             RHSElemType == S.Context.Float128Ty);
1103 
1104   // We've handled the situation where __float128 and long double have the same
1105   // representation. We allow all conversions for all possible long double types
1106   // except PPC's double double.
1107   return Float128AndLongDouble &&
1108     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1109      &llvm::APFloat::PPCDoubleDouble());
1110 }
1111 
1112 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1113 
1114 namespace {
1115 /// These helper callbacks are placed in an anonymous namespace to
1116 /// permit their use as function template parameters.
1117 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1118   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1119 }
1120 
1121 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1122   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1123                              CK_IntegralComplexCast);
1124 }
1125 }
1126 
1127 /// Handle integer arithmetic conversions.  Helper function of
1128 /// UsualArithmeticConversions()
1129 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1130 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1131                                         ExprResult &RHS, QualType LHSType,
1132                                         QualType RHSType, bool IsCompAssign) {
1133   // The rules for this case are in C99 6.3.1.8
1134   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1135   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1136   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1137   if (LHSSigned == RHSSigned) {
1138     // Same signedness; use the higher-ranked type
1139     if (order >= 0) {
1140       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1141       return LHSType;
1142     } else if (!IsCompAssign)
1143       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1144     return RHSType;
1145   } else if (order != (LHSSigned ? 1 : -1)) {
1146     // The unsigned type has greater than or equal rank to the
1147     // signed type, so use the unsigned type
1148     if (RHSSigned) {
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 (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1155     // The two types are different widths; if we are here, that
1156     // means the signed type is larger than the unsigned type, so
1157     // use the signed type.
1158     if (LHSSigned) {
1159       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1160       return LHSType;
1161     } else if (!IsCompAssign)
1162       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1163     return RHSType;
1164   } else {
1165     // The signed type is higher-ranked than the unsigned type,
1166     // but isn't actually any bigger (like unsigned int and long
1167     // on most 32-bit systems).  Use the unsigned type corresponding
1168     // to the signed type.
1169     QualType result =
1170       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1171     RHS = (*doRHSCast)(S, RHS.get(), result);
1172     if (!IsCompAssign)
1173       LHS = (*doLHSCast)(S, LHS.get(), result);
1174     return result;
1175   }
1176 }
1177 
1178 /// Handle conversions with GCC complex int extension.  Helper function
1179 /// of UsualArithmeticConversions()
1180 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1181                                            ExprResult &RHS, QualType LHSType,
1182                                            QualType RHSType,
1183                                            bool IsCompAssign) {
1184   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1185   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1186 
1187   if (LHSComplexInt && RHSComplexInt) {
1188     QualType LHSEltType = LHSComplexInt->getElementType();
1189     QualType RHSEltType = RHSComplexInt->getElementType();
1190     QualType ScalarType =
1191       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1192         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1193 
1194     return S.Context.getComplexType(ScalarType);
1195   }
1196 
1197   if (LHSComplexInt) {
1198     QualType LHSEltType = LHSComplexInt->getElementType();
1199     QualType ScalarType =
1200       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1201         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1202     QualType ComplexType = S.Context.getComplexType(ScalarType);
1203     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1204                               CK_IntegralRealToComplex);
1205 
1206     return ComplexType;
1207   }
1208 
1209   assert(RHSComplexInt);
1210 
1211   QualType RHSEltType = RHSComplexInt->getElementType();
1212   QualType ScalarType =
1213     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1214       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1215   QualType ComplexType = S.Context.getComplexType(ScalarType);
1216 
1217   if (!IsCompAssign)
1218     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1219                               CK_IntegralRealToComplex);
1220   return ComplexType;
1221 }
1222 
1223 /// UsualArithmeticConversions - Performs various conversions that are common to
1224 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1225 /// routine returns the first non-arithmetic type found. The client is
1226 /// responsible for emitting appropriate error diagnostics.
1227 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1228                                           bool IsCompAssign) {
1229   if (!IsCompAssign) {
1230     LHS = UsualUnaryConversions(LHS.get());
1231     if (LHS.isInvalid())
1232       return QualType();
1233   }
1234 
1235   RHS = UsualUnaryConversions(RHS.get());
1236   if (RHS.isInvalid())
1237     return QualType();
1238 
1239   // For conversion purposes, we ignore any qualifiers.
1240   // For example, "const float" and "float" are equivalent.
1241   QualType LHSType =
1242     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1243   QualType RHSType =
1244     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1245 
1246   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1247   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1248     LHSType = AtomicLHS->getValueType();
1249 
1250   // If both types are identical, no conversion is needed.
1251   if (LHSType == RHSType)
1252     return LHSType;
1253 
1254   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1255   // The caller can deal with this (e.g. pointer + int).
1256   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1257     return QualType();
1258 
1259   // Apply unary and bitfield promotions to the LHS's type.
1260   QualType LHSUnpromotedType = LHSType;
1261   if (LHSType->isPromotableIntegerType())
1262     LHSType = Context.getPromotedIntegerType(LHSType);
1263   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1264   if (!LHSBitfieldPromoteTy.isNull())
1265     LHSType = LHSBitfieldPromoteTy;
1266   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1267     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1268 
1269   // If both types are identical, no conversion is needed.
1270   if (LHSType == RHSType)
1271     return LHSType;
1272 
1273   // At this point, we have two different arithmetic types.
1274 
1275   // Diagnose attempts to convert between __float128 and long double where
1276   // such conversions currently can't be handled.
1277   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1278     return QualType();
1279 
1280   // Handle complex types first (C99 6.3.1.8p1).
1281   if (LHSType->isComplexType() || RHSType->isComplexType())
1282     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1283                                         IsCompAssign);
1284 
1285   // Now handle "real" floating types (i.e. float, double, long double).
1286   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1287     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1288                                  IsCompAssign);
1289 
1290   // Handle GCC complex int extension.
1291   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1292     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1293                                       IsCompAssign);
1294 
1295   // Finally, we have two differing integer types.
1296   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1297            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1298 }
1299 
1300 
1301 //===----------------------------------------------------------------------===//
1302 //  Semantic Analysis for various Expression Types
1303 //===----------------------------------------------------------------------===//
1304 
1305 
1306 ExprResult
1307 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1308                                 SourceLocation DefaultLoc,
1309                                 SourceLocation RParenLoc,
1310                                 Expr *ControllingExpr,
1311                                 ArrayRef<ParsedType> ArgTypes,
1312                                 ArrayRef<Expr *> ArgExprs) {
1313   unsigned NumAssocs = ArgTypes.size();
1314   assert(NumAssocs == ArgExprs.size());
1315 
1316   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1317   for (unsigned i = 0; i < NumAssocs; ++i) {
1318     if (ArgTypes[i])
1319       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1320     else
1321       Types[i] = nullptr;
1322   }
1323 
1324   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1325                                              ControllingExpr,
1326                                              llvm::makeArrayRef(Types, NumAssocs),
1327                                              ArgExprs);
1328   delete [] Types;
1329   return ER;
1330 }
1331 
1332 ExprResult
1333 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1334                                  SourceLocation DefaultLoc,
1335                                  SourceLocation RParenLoc,
1336                                  Expr *ControllingExpr,
1337                                  ArrayRef<TypeSourceInfo *> Types,
1338                                  ArrayRef<Expr *> Exprs) {
1339   unsigned NumAssocs = Types.size();
1340   assert(NumAssocs == Exprs.size());
1341 
1342   // Decay and strip qualifiers for the controlling expression type, and handle
1343   // placeholder type replacement. See committee discussion from WG14 DR423.
1344   {
1345     EnterExpressionEvaluationContext Unevaluated(
1346         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1347     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1348     if (R.isInvalid())
1349       return ExprError();
1350     ControllingExpr = R.get();
1351   }
1352 
1353   // The controlling expression is an unevaluated operand, so side effects are
1354   // likely unintended.
1355   if (!inTemplateInstantiation() &&
1356       ControllingExpr->HasSideEffects(Context, false))
1357     Diag(ControllingExpr->getExprLoc(),
1358          diag::warn_side_effects_unevaluated_context);
1359 
1360   bool TypeErrorFound = false,
1361        IsResultDependent = ControllingExpr->isTypeDependent(),
1362        ContainsUnexpandedParameterPack
1363          = ControllingExpr->containsUnexpandedParameterPack();
1364 
1365   for (unsigned i = 0; i < NumAssocs; ++i) {
1366     if (Exprs[i]->containsUnexpandedParameterPack())
1367       ContainsUnexpandedParameterPack = true;
1368 
1369     if (Types[i]) {
1370       if (Types[i]->getType()->containsUnexpandedParameterPack())
1371         ContainsUnexpandedParameterPack = true;
1372 
1373       if (Types[i]->getType()->isDependentType()) {
1374         IsResultDependent = true;
1375       } else {
1376         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1377         // complete object type other than a variably modified type."
1378         unsigned D = 0;
1379         if (Types[i]->getType()->isIncompleteType())
1380           D = diag::err_assoc_type_incomplete;
1381         else if (!Types[i]->getType()->isObjectType())
1382           D = diag::err_assoc_type_nonobject;
1383         else if (Types[i]->getType()->isVariablyModifiedType())
1384           D = diag::err_assoc_type_variably_modified;
1385 
1386         if (D != 0) {
1387           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1388             << Types[i]->getTypeLoc().getSourceRange()
1389             << Types[i]->getType();
1390           TypeErrorFound = true;
1391         }
1392 
1393         // C11 6.5.1.1p2 "No two generic associations in the same generic
1394         // selection shall specify compatible types."
1395         for (unsigned j = i+1; j < NumAssocs; ++j)
1396           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1397               Context.typesAreCompatible(Types[i]->getType(),
1398                                          Types[j]->getType())) {
1399             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1400                  diag::err_assoc_compatible_types)
1401               << Types[j]->getTypeLoc().getSourceRange()
1402               << Types[j]->getType()
1403               << Types[i]->getType();
1404             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1405                  diag::note_compat_assoc)
1406               << Types[i]->getTypeLoc().getSourceRange()
1407               << Types[i]->getType();
1408             TypeErrorFound = true;
1409           }
1410       }
1411     }
1412   }
1413   if (TypeErrorFound)
1414     return ExprError();
1415 
1416   // If we determined that the generic selection is result-dependent, don't
1417   // try to compute the result expression.
1418   if (IsResultDependent)
1419     return new (Context) GenericSelectionExpr(
1420         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1421         ContainsUnexpandedParameterPack);
1422 
1423   SmallVector<unsigned, 1> CompatIndices;
1424   unsigned DefaultIndex = -1U;
1425   for (unsigned i = 0; i < NumAssocs; ++i) {
1426     if (!Types[i])
1427       DefaultIndex = i;
1428     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1429                                         Types[i]->getType()))
1430       CompatIndices.push_back(i);
1431   }
1432 
1433   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1434   // type compatible with at most one of the types named in its generic
1435   // association list."
1436   if (CompatIndices.size() > 1) {
1437     // We strip parens here because the controlling expression is typically
1438     // parenthesized in macro definitions.
1439     ControllingExpr = ControllingExpr->IgnoreParens();
1440     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1441       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1442       << (unsigned) CompatIndices.size();
1443     for (unsigned I : CompatIndices) {
1444       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1445            diag::note_compat_assoc)
1446         << Types[I]->getTypeLoc().getSourceRange()
1447         << Types[I]->getType();
1448     }
1449     return ExprError();
1450   }
1451 
1452   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1453   // its controlling expression shall have type compatible with exactly one of
1454   // the types named in its generic association list."
1455   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1456     // We strip parens here because the controlling expression is typically
1457     // parenthesized in macro definitions.
1458     ControllingExpr = ControllingExpr->IgnoreParens();
1459     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1460       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1461     return ExprError();
1462   }
1463 
1464   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1465   // type name that is compatible with the type of the controlling expression,
1466   // then the result expression of the generic selection is the expression
1467   // in that generic association. Otherwise, the result expression of the
1468   // generic selection is the expression in the default generic association."
1469   unsigned ResultIndex =
1470     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1471 
1472   return new (Context) GenericSelectionExpr(
1473       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1474       ContainsUnexpandedParameterPack, ResultIndex);
1475 }
1476 
1477 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1478 /// location of the token and the offset of the ud-suffix within it.
1479 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1480                                      unsigned Offset) {
1481   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1482                                         S.getLangOpts());
1483 }
1484 
1485 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1486 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1487 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1488                                                  IdentifierInfo *UDSuffix,
1489                                                  SourceLocation UDSuffixLoc,
1490                                                  ArrayRef<Expr*> Args,
1491                                                  SourceLocation LitEndLoc) {
1492   assert(Args.size() <= 2 && "too many arguments for literal operator");
1493 
1494   QualType ArgTy[2];
1495   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1496     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1497     if (ArgTy[ArgIdx]->isArrayType())
1498       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1499   }
1500 
1501   DeclarationName OpName =
1502     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1503   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1504   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1505 
1506   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1507   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1508                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1509                               /*AllowStringTemplate*/ false,
1510                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1511     return ExprError();
1512 
1513   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1514 }
1515 
1516 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1517 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1518 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1519 /// multiple tokens.  However, the common case is that StringToks points to one
1520 /// string.
1521 ///
1522 ExprResult
1523 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1524   assert(!StringToks.empty() && "Must have at least one string!");
1525 
1526   StringLiteralParser Literal(StringToks, PP);
1527   if (Literal.hadError)
1528     return ExprError();
1529 
1530   SmallVector<SourceLocation, 4> StringTokLocs;
1531   for (const Token &Tok : StringToks)
1532     StringTokLocs.push_back(Tok.getLocation());
1533 
1534   QualType CharTy = Context.CharTy;
1535   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1536   if (Literal.isWide()) {
1537     CharTy = Context.getWideCharType();
1538     Kind = StringLiteral::Wide;
1539   } else if (Literal.isUTF8()) {
1540     if (getLangOpts().Char8)
1541       CharTy = Context.Char8Ty;
1542     Kind = StringLiteral::UTF8;
1543   } else if (Literal.isUTF16()) {
1544     CharTy = Context.Char16Ty;
1545     Kind = StringLiteral::UTF16;
1546   } else if (Literal.isUTF32()) {
1547     CharTy = Context.Char32Ty;
1548     Kind = StringLiteral::UTF32;
1549   } else if (Literal.isPascal()) {
1550     CharTy = Context.UnsignedCharTy;
1551   }
1552 
1553   QualType CharTyConst = CharTy;
1554   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1555   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1556     CharTyConst.addConst();
1557 
1558   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1559 
1560   // Get an array type for the string, according to C99 6.4.5.  This includes
1561   // the nul terminator character as well as the string length for pascal
1562   // strings.
1563   QualType StrTy = Context.getConstantArrayType(
1564       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1565       ArrayType::Normal, 0);
1566 
1567   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1568   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1569                                              Kind, Literal.Pascal, StrTy,
1570                                              &StringTokLocs[0],
1571                                              StringTokLocs.size());
1572   if (Literal.getUDSuffix().empty())
1573     return Lit;
1574 
1575   // We're building a user-defined literal.
1576   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1577   SourceLocation UDSuffixLoc =
1578     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1579                    Literal.getUDSuffixOffset());
1580 
1581   // Make sure we're allowed user-defined literals here.
1582   if (!UDLScope)
1583     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1584 
1585   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1586   //   operator "" X (str, len)
1587   QualType SizeType = Context.getSizeType();
1588 
1589   DeclarationName OpName =
1590     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1591   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1592   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1593 
1594   QualType ArgTy[] = {
1595     Context.getArrayDecayedType(StrTy), SizeType
1596   };
1597 
1598   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1599   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1600                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1601                                 /*AllowStringTemplate*/ true,
1602                                 /*DiagnoseMissing*/ true)) {
1603 
1604   case LOLR_Cooked: {
1605     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1606     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1607                                                     StringTokLocs[0]);
1608     Expr *Args[] = { Lit, LenArg };
1609 
1610     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1611   }
1612 
1613   case LOLR_StringTemplate: {
1614     TemplateArgumentListInfo ExplicitArgs;
1615 
1616     unsigned CharBits = Context.getIntWidth(CharTy);
1617     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1618     llvm::APSInt Value(CharBits, CharIsUnsigned);
1619 
1620     TemplateArgument TypeArg(CharTy);
1621     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1622     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1623 
1624     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1625       Value = Lit->getCodeUnit(I);
1626       TemplateArgument Arg(Context, Value, CharTy);
1627       TemplateArgumentLocInfo ArgInfo;
1628       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1629     }
1630     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1631                                     &ExplicitArgs);
1632   }
1633   case LOLR_Raw:
1634   case LOLR_Template:
1635   case LOLR_ErrorNoDiagnostic:
1636     llvm_unreachable("unexpected literal operator lookup result");
1637   case LOLR_Error:
1638     return ExprError();
1639   }
1640   llvm_unreachable("unexpected literal operator lookup result");
1641 }
1642 
1643 ExprResult
1644 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1645                        SourceLocation Loc,
1646                        const CXXScopeSpec *SS) {
1647   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1648   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1649 }
1650 
1651 /// BuildDeclRefExpr - Build an expression that references a
1652 /// declaration that does not require a closure capture.
1653 ExprResult
1654 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1655                        const DeclarationNameInfo &NameInfo,
1656                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1657                        const TemplateArgumentListInfo *TemplateArgs) {
1658   bool RefersToCapturedVariable =
1659       isa<VarDecl>(D) &&
1660       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1661 
1662   DeclRefExpr *E;
1663   if (isa<VarTemplateSpecializationDecl>(D)) {
1664     VarTemplateSpecializationDecl *VarSpec =
1665         cast<VarTemplateSpecializationDecl>(D);
1666 
1667     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1668                                         : NestedNameSpecifierLoc(),
1669                             VarSpec->getTemplateKeywordLoc(), D,
1670                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1671                             FoundD, TemplateArgs);
1672   } else {
1673     assert(!TemplateArgs && "No template arguments for non-variable"
1674                             " template specialization references");
1675     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1676                                         : NestedNameSpecifierLoc(),
1677                             SourceLocation(), D, RefersToCapturedVariable,
1678                             NameInfo, Ty, VK, FoundD);
1679   }
1680 
1681   MarkDeclRefReferenced(E);
1682 
1683   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1684       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1685       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1686     getCurFunction()->recordUseOfWeak(E);
1687 
1688   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1689   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1690     FD = IFD->getAnonField();
1691   if (FD) {
1692     UnusedPrivateFields.remove(FD);
1693     // Just in case we're building an illegal pointer-to-member.
1694     if (FD->isBitField())
1695       E->setObjectKind(OK_BitField);
1696   }
1697 
1698   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1699   // designates a bit-field.
1700   if (auto *BD = dyn_cast<BindingDecl>(D))
1701     if (auto *BE = BD->getBinding())
1702       E->setObjectKind(BE->getObjectKind());
1703 
1704   return E;
1705 }
1706 
1707 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1708 /// possibly a list of template arguments.
1709 ///
1710 /// If this produces template arguments, it is permitted to call
1711 /// DecomposeTemplateName.
1712 ///
1713 /// This actually loses a lot of source location information for
1714 /// non-standard name kinds; we should consider preserving that in
1715 /// some way.
1716 void
1717 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1718                              TemplateArgumentListInfo &Buffer,
1719                              DeclarationNameInfo &NameInfo,
1720                              const TemplateArgumentListInfo *&TemplateArgs) {
1721   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1722     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1723     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1724 
1725     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1726                                        Id.TemplateId->NumArgs);
1727     translateTemplateArguments(TemplateArgsPtr, Buffer);
1728 
1729     TemplateName TName = Id.TemplateId->Template.get();
1730     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1731     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1732     TemplateArgs = &Buffer;
1733   } else {
1734     NameInfo = GetNameFromUnqualifiedId(Id);
1735     TemplateArgs = nullptr;
1736   }
1737 }
1738 
1739 static void emitEmptyLookupTypoDiagnostic(
1740     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1741     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1742     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1743   DeclContext *Ctx =
1744       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1745   if (!TC) {
1746     // Emit a special diagnostic for failed member lookups.
1747     // FIXME: computing the declaration context might fail here (?)
1748     if (Ctx)
1749       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1750                                                  << SS.getRange();
1751     else
1752       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1753     return;
1754   }
1755 
1756   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1757   bool DroppedSpecifier =
1758       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1759   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1760                         ? diag::note_implicit_param_decl
1761                         : diag::note_previous_decl;
1762   if (!Ctx)
1763     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1764                          SemaRef.PDiag(NoteID));
1765   else
1766     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1767                                  << Typo << Ctx << DroppedSpecifier
1768                                  << SS.getRange(),
1769                          SemaRef.PDiag(NoteID));
1770 }
1771 
1772 /// Diagnose an empty lookup.
1773 ///
1774 /// \return false if new lookup candidates were found
1775 bool
1776 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1777                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1778                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1779                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1780   DeclarationName Name = R.getLookupName();
1781 
1782   unsigned diagnostic = diag::err_undeclared_var_use;
1783   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1784   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1785       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1786       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1787     diagnostic = diag::err_undeclared_use;
1788     diagnostic_suggest = diag::err_undeclared_use_suggest;
1789   }
1790 
1791   // If the original lookup was an unqualified lookup, fake an
1792   // unqualified lookup.  This is useful when (for example) the
1793   // original lookup would not have found something because it was a
1794   // dependent name.
1795   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1796   while (DC) {
1797     if (isa<CXXRecordDecl>(DC)) {
1798       LookupQualifiedName(R, DC);
1799 
1800       if (!R.empty()) {
1801         // Don't give errors about ambiguities in this lookup.
1802         R.suppressDiagnostics();
1803 
1804         // During a default argument instantiation the CurContext points
1805         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1806         // function parameter list, hence add an explicit check.
1807         bool isDefaultArgument =
1808             !CodeSynthesisContexts.empty() &&
1809             CodeSynthesisContexts.back().Kind ==
1810                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1811         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1812         bool isInstance = CurMethod &&
1813                           CurMethod->isInstance() &&
1814                           DC == CurMethod->getParent() && !isDefaultArgument;
1815 
1816         // Give a code modification hint to insert 'this->'.
1817         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1818         // Actually quite difficult!
1819         if (getLangOpts().MSVCCompat)
1820           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1821         if (isInstance) {
1822           Diag(R.getNameLoc(), diagnostic) << Name
1823             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1824           CheckCXXThisCapture(R.getNameLoc());
1825         } else {
1826           Diag(R.getNameLoc(), diagnostic) << Name;
1827         }
1828 
1829         // Do we really want to note all of these?
1830         for (NamedDecl *D : R)
1831           Diag(D->getLocation(), diag::note_dependent_var_use);
1832 
1833         // Return true if we are inside a default argument instantiation
1834         // and the found name refers to an instance member function, otherwise
1835         // the function calling DiagnoseEmptyLookup will try to create an
1836         // implicit member call and this is wrong for default argument.
1837         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1838           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1839           return true;
1840         }
1841 
1842         // Tell the callee to try to recover.
1843         return false;
1844       }
1845 
1846       R.clear();
1847     }
1848 
1849     // In Microsoft mode, if we are performing lookup from within a friend
1850     // function definition declared at class scope then we must set
1851     // DC to the lexical parent to be able to search into the parent
1852     // class.
1853     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1854         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1855         DC->getLexicalParent()->isRecord())
1856       DC = DC->getLexicalParent();
1857     else
1858       DC = DC->getParent();
1859   }
1860 
1861   // We didn't find anything, so try to correct for a typo.
1862   TypoCorrection Corrected;
1863   if (S && Out) {
1864     SourceLocation TypoLoc = R.getNameLoc();
1865     assert(!ExplicitTemplateArgs &&
1866            "Diagnosing an empty lookup with explicit template args!");
1867     *Out = CorrectTypoDelayed(
1868         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1869         [=](const TypoCorrection &TC) {
1870           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1871                                         diagnostic, diagnostic_suggest);
1872         },
1873         nullptr, CTK_ErrorRecovery);
1874     if (*Out)
1875       return true;
1876   } else if (S && (Corrected =
1877                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1878                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1879     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1880     bool DroppedSpecifier =
1881         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1882     R.setLookupName(Corrected.getCorrection());
1883 
1884     bool AcceptableWithRecovery = false;
1885     bool AcceptableWithoutRecovery = false;
1886     NamedDecl *ND = Corrected.getFoundDecl();
1887     if (ND) {
1888       if (Corrected.isOverloaded()) {
1889         OverloadCandidateSet OCS(R.getNameLoc(),
1890                                  OverloadCandidateSet::CSK_Normal);
1891         OverloadCandidateSet::iterator Best;
1892         for (NamedDecl *CD : Corrected) {
1893           if (FunctionTemplateDecl *FTD =
1894                    dyn_cast<FunctionTemplateDecl>(CD))
1895             AddTemplateOverloadCandidate(
1896                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1897                 Args, OCS);
1898           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1899             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1900               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1901                                    Args, OCS);
1902         }
1903         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1904         case OR_Success:
1905           ND = Best->FoundDecl;
1906           Corrected.setCorrectionDecl(ND);
1907           break;
1908         default:
1909           // FIXME: Arbitrarily pick the first declaration for the note.
1910           Corrected.setCorrectionDecl(ND);
1911           break;
1912         }
1913       }
1914       R.addDecl(ND);
1915       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1916         CXXRecordDecl *Record = nullptr;
1917         if (Corrected.getCorrectionSpecifier()) {
1918           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1919           Record = Ty->getAsCXXRecordDecl();
1920         }
1921         if (!Record)
1922           Record = cast<CXXRecordDecl>(
1923               ND->getDeclContext()->getRedeclContext());
1924         R.setNamingClass(Record);
1925       }
1926 
1927       auto *UnderlyingND = ND->getUnderlyingDecl();
1928       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1929                                isa<FunctionTemplateDecl>(UnderlyingND);
1930       // FIXME: If we ended up with a typo for a type name or
1931       // Objective-C class name, we're in trouble because the parser
1932       // is in the wrong place to recover. Suggest the typo
1933       // correction, but don't make it a fix-it since we're not going
1934       // to recover well anyway.
1935       AcceptableWithoutRecovery =
1936           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1937     } else {
1938       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1939       // because we aren't able to recover.
1940       AcceptableWithoutRecovery = true;
1941     }
1942 
1943     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1944       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1945                             ? diag::note_implicit_param_decl
1946                             : diag::note_previous_decl;
1947       if (SS.isEmpty())
1948         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1949                      PDiag(NoteID), AcceptableWithRecovery);
1950       else
1951         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1952                                   << Name << computeDeclContext(SS, false)
1953                                   << DroppedSpecifier << SS.getRange(),
1954                      PDiag(NoteID), AcceptableWithRecovery);
1955 
1956       // Tell the callee whether to try to recover.
1957       return !AcceptableWithRecovery;
1958     }
1959   }
1960   R.clear();
1961 
1962   // Emit a special diagnostic for failed member lookups.
1963   // FIXME: computing the declaration context might fail here (?)
1964   if (!SS.isEmpty()) {
1965     Diag(R.getNameLoc(), diag::err_no_member)
1966       << Name << computeDeclContext(SS, false)
1967       << SS.getRange();
1968     return true;
1969   }
1970 
1971   // Give up, we can't recover.
1972   Diag(R.getNameLoc(), diagnostic) << Name;
1973   return true;
1974 }
1975 
1976 /// In Microsoft mode, if we are inside a template class whose parent class has
1977 /// dependent base classes, and we can't resolve an unqualified identifier, then
1978 /// assume the identifier is a member of a dependent base class.  We can only
1979 /// recover successfully in static methods, instance methods, and other contexts
1980 /// where 'this' is available.  This doesn't precisely match MSVC's
1981 /// instantiation model, but it's close enough.
1982 static Expr *
1983 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1984                                DeclarationNameInfo &NameInfo,
1985                                SourceLocation TemplateKWLoc,
1986                                const TemplateArgumentListInfo *TemplateArgs) {
1987   // Only try to recover from lookup into dependent bases in static methods or
1988   // contexts where 'this' is available.
1989   QualType ThisType = S.getCurrentThisType();
1990   const CXXRecordDecl *RD = nullptr;
1991   if (!ThisType.isNull())
1992     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1993   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1994     RD = MD->getParent();
1995   if (!RD || !RD->hasAnyDependentBases())
1996     return nullptr;
1997 
1998   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1999   // is available, suggest inserting 'this->' as a fixit.
2000   SourceLocation Loc = NameInfo.getLoc();
2001   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2002   DB << NameInfo.getName() << RD;
2003 
2004   if (!ThisType.isNull()) {
2005     DB << FixItHint::CreateInsertion(Loc, "this->");
2006     return CXXDependentScopeMemberExpr::Create(
2007         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2008         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2009         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2010   }
2011 
2012   // Synthesize a fake NNS that points to the derived class.  This will
2013   // perform name lookup during template instantiation.
2014   CXXScopeSpec SS;
2015   auto *NNS =
2016       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2017   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2018   return DependentScopeDeclRefExpr::Create(
2019       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2020       TemplateArgs);
2021 }
2022 
2023 ExprResult
2024 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2025                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2026                         bool HasTrailingLParen, bool IsAddressOfOperand,
2027                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2028                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2029   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2030          "cannot be direct & operand and have a trailing lparen");
2031   if (SS.isInvalid())
2032     return ExprError();
2033 
2034   TemplateArgumentListInfo TemplateArgsBuffer;
2035 
2036   // Decompose the UnqualifiedId into the following data.
2037   DeclarationNameInfo NameInfo;
2038   const TemplateArgumentListInfo *TemplateArgs;
2039   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2040 
2041   DeclarationName Name = NameInfo.getName();
2042   IdentifierInfo *II = Name.getAsIdentifierInfo();
2043   SourceLocation NameLoc = NameInfo.getLoc();
2044 
2045   if (II && II->isEditorPlaceholder()) {
2046     // FIXME: When typed placeholders are supported we can create a typed
2047     // placeholder expression node.
2048     return ExprError();
2049   }
2050 
2051   // C++ [temp.dep.expr]p3:
2052   //   An id-expression is type-dependent if it contains:
2053   //     -- an identifier that was declared with a dependent type,
2054   //        (note: handled after lookup)
2055   //     -- a template-id that is dependent,
2056   //        (note: handled in BuildTemplateIdExpr)
2057   //     -- a conversion-function-id that specifies a dependent type,
2058   //     -- a nested-name-specifier that contains a class-name that
2059   //        names a dependent type.
2060   // Determine whether this is a member of an unknown specialization;
2061   // we need to handle these differently.
2062   bool DependentID = false;
2063   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2064       Name.getCXXNameType()->isDependentType()) {
2065     DependentID = true;
2066   } else if (SS.isSet()) {
2067     if (DeclContext *DC = computeDeclContext(SS, false)) {
2068       if (RequireCompleteDeclContext(SS, DC))
2069         return ExprError();
2070     } else {
2071       DependentID = true;
2072     }
2073   }
2074 
2075   if (DependentID)
2076     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2077                                       IsAddressOfOperand, TemplateArgs);
2078 
2079   // Perform the required lookup.
2080   LookupResult R(*this, NameInfo,
2081                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2082                      ? LookupObjCImplicitSelfParam
2083                      : LookupOrdinaryName);
2084   if (TemplateKWLoc.isValid() || TemplateArgs) {
2085     // Lookup the template name again to correctly establish the context in
2086     // which it was found. This is really unfortunate as we already did the
2087     // lookup to determine that it was a template name in the first place. If
2088     // this becomes a performance hit, we can work harder to preserve those
2089     // results until we get here but it's likely not worth it.
2090     bool MemberOfUnknownSpecialization;
2091     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2092                            MemberOfUnknownSpecialization, TemplateKWLoc))
2093       return ExprError();
2094 
2095     if (MemberOfUnknownSpecialization ||
2096         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2097       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2098                                         IsAddressOfOperand, TemplateArgs);
2099   } else {
2100     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2101     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2102 
2103     // If the result might be in a dependent base class, this is a dependent
2104     // id-expression.
2105     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2106       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2107                                         IsAddressOfOperand, TemplateArgs);
2108 
2109     // If this reference is in an Objective-C method, then we need to do
2110     // some special Objective-C lookup, too.
2111     if (IvarLookupFollowUp) {
2112       ExprResult E(LookupInObjCMethod(R, S, II, true));
2113       if (E.isInvalid())
2114         return ExprError();
2115 
2116       if (Expr *Ex = E.getAs<Expr>())
2117         return Ex;
2118     }
2119   }
2120 
2121   if (R.isAmbiguous())
2122     return ExprError();
2123 
2124   // This could be an implicitly declared function reference (legal in C90,
2125   // extension in C99, forbidden in C++).
2126   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2127     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2128     if (D) R.addDecl(D);
2129   }
2130 
2131   // Determine whether this name might be a candidate for
2132   // argument-dependent lookup.
2133   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2134 
2135   if (R.empty() && !ADL) {
2136     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2137       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2138                                                    TemplateKWLoc, TemplateArgs))
2139         return E;
2140     }
2141 
2142     // Don't diagnose an empty lookup for inline assembly.
2143     if (IsInlineAsmIdentifier)
2144       return ExprError();
2145 
2146     // If this name wasn't predeclared and if this is not a function
2147     // call, diagnose the problem.
2148     TypoExpr *TE = nullptr;
2149     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2150         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2151     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2152     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2153            "Typo correction callback misconfigured");
2154     if (CCC) {
2155       // Make sure the callback knows what the typo being diagnosed is.
2156       CCC->setTypoName(II);
2157       if (SS.isValid())
2158         CCC->setTypoNNS(SS.getScopeRep());
2159     }
2160     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2161     // a template name, but we happen to have always already looked up the name
2162     // before we get here if it must be a template name.
2163     if (DiagnoseEmptyLookup(S, SS, R,
2164                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2165                             nullptr, None, &TE)) {
2166       if (TE && KeywordReplacement) {
2167         auto &State = getTypoExprState(TE);
2168         auto BestTC = State.Consumer->getNextCorrection();
2169         if (BestTC.isKeyword()) {
2170           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2171           if (State.DiagHandler)
2172             State.DiagHandler(BestTC);
2173           KeywordReplacement->startToken();
2174           KeywordReplacement->setKind(II->getTokenID());
2175           KeywordReplacement->setIdentifierInfo(II);
2176           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2177           // Clean up the state associated with the TypoExpr, since it has
2178           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2179           clearDelayedTypo(TE);
2180           // Signal that a correction to a keyword was performed by returning a
2181           // valid-but-null ExprResult.
2182           return (Expr*)nullptr;
2183         }
2184         State.Consumer->resetCorrectionStream();
2185       }
2186       return TE ? TE : ExprError();
2187     }
2188 
2189     assert(!R.empty() &&
2190            "DiagnoseEmptyLookup returned false but added no results");
2191 
2192     // If we found an Objective-C instance variable, let
2193     // LookupInObjCMethod build the appropriate expression to
2194     // reference the ivar.
2195     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2196       R.clear();
2197       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2198       // In a hopelessly buggy code, Objective-C instance variable
2199       // lookup fails and no expression will be built to reference it.
2200       if (!E.isInvalid() && !E.get())
2201         return ExprError();
2202       return E;
2203     }
2204   }
2205 
2206   // This is guaranteed from this point on.
2207   assert(!R.empty() || ADL);
2208 
2209   // Check whether this might be a C++ implicit instance member access.
2210   // C++ [class.mfct.non-static]p3:
2211   //   When an id-expression that is not part of a class member access
2212   //   syntax and not used to form a pointer to member is used in the
2213   //   body of a non-static member function of class X, if name lookup
2214   //   resolves the name in the id-expression to a non-static non-type
2215   //   member of some class C, the id-expression is transformed into a
2216   //   class member access expression using (*this) as the
2217   //   postfix-expression to the left of the . operator.
2218   //
2219   // But we don't actually need to do this for '&' operands if R
2220   // resolved to a function or overloaded function set, because the
2221   // expression is ill-formed if it actually works out to be a
2222   // non-static member function:
2223   //
2224   // C++ [expr.ref]p4:
2225   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2226   //   [t]he expression can be used only as the left-hand operand of a
2227   //   member function call.
2228   //
2229   // There are other safeguards against such uses, but it's important
2230   // to get this right here so that we don't end up making a
2231   // spuriously dependent expression if we're inside a dependent
2232   // instance method.
2233   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2234     bool MightBeImplicitMember;
2235     if (!IsAddressOfOperand)
2236       MightBeImplicitMember = true;
2237     else if (!SS.isEmpty())
2238       MightBeImplicitMember = false;
2239     else if (R.isOverloadedResult())
2240       MightBeImplicitMember = false;
2241     else if (R.isUnresolvableResult())
2242       MightBeImplicitMember = true;
2243     else
2244       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2245                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2246                               isa<MSPropertyDecl>(R.getFoundDecl());
2247 
2248     if (MightBeImplicitMember)
2249       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2250                                              R, TemplateArgs, S);
2251   }
2252 
2253   if (TemplateArgs || TemplateKWLoc.isValid()) {
2254 
2255     // In C++1y, if this is a variable template id, then check it
2256     // in BuildTemplateIdExpr().
2257     // The single lookup result must be a variable template declaration.
2258     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2259         Id.TemplateId->Kind == TNK_Var_template) {
2260       assert(R.getAsSingle<VarTemplateDecl>() &&
2261              "There should only be one declaration found.");
2262     }
2263 
2264     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2265   }
2266 
2267   return BuildDeclarationNameExpr(SS, R, ADL);
2268 }
2269 
2270 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2271 /// declaration name, generally during template instantiation.
2272 /// There's a large number of things which don't need to be done along
2273 /// this path.
2274 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2275     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2276     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2277   DeclContext *DC = computeDeclContext(SS, false);
2278   if (!DC)
2279     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2280                                      NameInfo, /*TemplateArgs=*/nullptr);
2281 
2282   if (RequireCompleteDeclContext(SS, DC))
2283     return ExprError();
2284 
2285   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2286   LookupQualifiedName(R, DC);
2287 
2288   if (R.isAmbiguous())
2289     return ExprError();
2290 
2291   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2292     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2293                                      NameInfo, /*TemplateArgs=*/nullptr);
2294 
2295   if (R.empty()) {
2296     Diag(NameInfo.getLoc(), diag::err_no_member)
2297       << NameInfo.getName() << DC << SS.getRange();
2298     return ExprError();
2299   }
2300 
2301   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2302     // Diagnose a missing typename if this resolved unambiguously to a type in
2303     // a dependent context.  If we can recover with a type, downgrade this to
2304     // a warning in Microsoft compatibility mode.
2305     unsigned DiagID = diag::err_typename_missing;
2306     if (RecoveryTSI && getLangOpts().MSVCCompat)
2307       DiagID = diag::ext_typename_missing;
2308     SourceLocation Loc = SS.getBeginLoc();
2309     auto D = Diag(Loc, DiagID);
2310     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2311       << SourceRange(Loc, NameInfo.getEndLoc());
2312 
2313     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2314     // context.
2315     if (!RecoveryTSI)
2316       return ExprError();
2317 
2318     // Only issue the fixit if we're prepared to recover.
2319     D << FixItHint::CreateInsertion(Loc, "typename ");
2320 
2321     // Recover by pretending this was an elaborated type.
2322     QualType Ty = Context.getTypeDeclType(TD);
2323     TypeLocBuilder TLB;
2324     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2325 
2326     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2327     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2328     QTL.setElaboratedKeywordLoc(SourceLocation());
2329     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2330 
2331     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2332 
2333     return ExprEmpty();
2334   }
2335 
2336   // Defend against this resolving to an implicit member access. We usually
2337   // won't get here if this might be a legitimate a class member (we end up in
2338   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2339   // a pointer-to-member or in an unevaluated context in C++11.
2340   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2341     return BuildPossibleImplicitMemberExpr(SS,
2342                                            /*TemplateKWLoc=*/SourceLocation(),
2343                                            R, /*TemplateArgs=*/nullptr, S);
2344 
2345   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2346 }
2347 
2348 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2349 /// detected that we're currently inside an ObjC method.  Perform some
2350 /// additional lookup.
2351 ///
2352 /// Ideally, most of this would be done by lookup, but there's
2353 /// actually quite a lot of extra work involved.
2354 ///
2355 /// Returns a null sentinel to indicate trivial success.
2356 ExprResult
2357 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2358                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2359   SourceLocation Loc = Lookup.getNameLoc();
2360   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2361 
2362   // Check for error condition which is already reported.
2363   if (!CurMethod)
2364     return ExprError();
2365 
2366   // There are two cases to handle here.  1) scoped lookup could have failed,
2367   // in which case we should look for an ivar.  2) scoped lookup could have
2368   // found a decl, but that decl is outside the current instance method (i.e.
2369   // a global variable).  In these two cases, we do a lookup for an ivar with
2370   // this name, if the lookup sucedes, we replace it our current decl.
2371 
2372   // If we're in a class method, we don't normally want to look for
2373   // ivars.  But if we don't find anything else, and there's an
2374   // ivar, that's an error.
2375   bool IsClassMethod = CurMethod->isClassMethod();
2376 
2377   bool LookForIvars;
2378   if (Lookup.empty())
2379     LookForIvars = true;
2380   else if (IsClassMethod)
2381     LookForIvars = false;
2382   else
2383     LookForIvars = (Lookup.isSingleResult() &&
2384                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2385   ObjCInterfaceDecl *IFace = nullptr;
2386   if (LookForIvars) {
2387     IFace = CurMethod->getClassInterface();
2388     ObjCInterfaceDecl *ClassDeclared;
2389     ObjCIvarDecl *IV = nullptr;
2390     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2391       // Diagnose using an ivar in a class method.
2392       if (IsClassMethod)
2393         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2394                          << IV->getDeclName());
2395 
2396       // If we're referencing an invalid decl, just return this as a silent
2397       // error node.  The error diagnostic was already emitted on the decl.
2398       if (IV->isInvalidDecl())
2399         return ExprError();
2400 
2401       // Check if referencing a field with __attribute__((deprecated)).
2402       if (DiagnoseUseOfDecl(IV, Loc))
2403         return ExprError();
2404 
2405       // Diagnose the use of an ivar outside of the declaring class.
2406       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2407           !declaresSameEntity(ClassDeclared, IFace) &&
2408           !getLangOpts().DebuggerSupport)
2409         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2410 
2411       // FIXME: This should use a new expr for a direct reference, don't
2412       // turn this into Self->ivar, just return a BareIVarExpr or something.
2413       IdentifierInfo &II = Context.Idents.get("self");
2414       UnqualifiedId SelfName;
2415       SelfName.setIdentifier(&II, SourceLocation());
2416       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2417       CXXScopeSpec SelfScopeSpec;
2418       SourceLocation TemplateKWLoc;
2419       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2420                                               SelfName, false, false);
2421       if (SelfExpr.isInvalid())
2422         return ExprError();
2423 
2424       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2425       if (SelfExpr.isInvalid())
2426         return ExprError();
2427 
2428       MarkAnyDeclReferenced(Loc, IV, true);
2429 
2430       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2431       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2432           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2433         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2434 
2435       ObjCIvarRefExpr *Result = new (Context)
2436           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2437                           IV->getLocation(), SelfExpr.get(), true, true);
2438 
2439       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2440         if (!isUnevaluatedContext() &&
2441             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2442           getCurFunction()->recordUseOfWeak(Result);
2443       }
2444       if (getLangOpts().ObjCAutoRefCount) {
2445         if (CurContext->isClosure())
2446           Diag(Loc, diag::warn_implicitly_retains_self)
2447             << FixItHint::CreateInsertion(Loc, "self->");
2448       }
2449 
2450       return Result;
2451     }
2452   } else if (CurMethod->isInstanceMethod()) {
2453     // We should warn if a local variable hides an ivar.
2454     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2455       ObjCInterfaceDecl *ClassDeclared;
2456       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2457         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2458             declaresSameEntity(IFace, ClassDeclared))
2459           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2460       }
2461     }
2462   } else if (Lookup.isSingleResult() &&
2463              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2464     // If accessing a stand-alone ivar in a class method, this is an error.
2465     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2466       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2467                        << IV->getDeclName());
2468   }
2469 
2470   if (Lookup.empty() && II && AllowBuiltinCreation) {
2471     // FIXME. Consolidate this with similar code in LookupName.
2472     if (unsigned BuiltinID = II->getBuiltinID()) {
2473       if (!(getLangOpts().CPlusPlus &&
2474             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2475         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2476                                            S, Lookup.isForRedeclaration(),
2477                                            Lookup.getNameLoc());
2478         if (D) Lookup.addDecl(D);
2479       }
2480     }
2481   }
2482   // Sentinel value saying that we didn't do anything special.
2483   return ExprResult((Expr *)nullptr);
2484 }
2485 
2486 /// Cast a base object to a member's actual type.
2487 ///
2488 /// Logically this happens in three phases:
2489 ///
2490 /// * First we cast from the base type to the naming class.
2491 ///   The naming class is the class into which we were looking
2492 ///   when we found the member;  it's the qualifier type if a
2493 ///   qualifier was provided, and otherwise it's the base type.
2494 ///
2495 /// * Next we cast from the naming class to the declaring class.
2496 ///   If the member we found was brought into a class's scope by
2497 ///   a using declaration, this is that class;  otherwise it's
2498 ///   the class declaring the member.
2499 ///
2500 /// * Finally we cast from the declaring class to the "true"
2501 ///   declaring class of the member.  This conversion does not
2502 ///   obey access control.
2503 ExprResult
2504 Sema::PerformObjectMemberConversion(Expr *From,
2505                                     NestedNameSpecifier *Qualifier,
2506                                     NamedDecl *FoundDecl,
2507                                     NamedDecl *Member) {
2508   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2509   if (!RD)
2510     return From;
2511 
2512   QualType DestRecordType;
2513   QualType DestType;
2514   QualType FromRecordType;
2515   QualType FromType = From->getType();
2516   bool PointerConversions = false;
2517   if (isa<FieldDecl>(Member)) {
2518     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2519 
2520     if (FromType->getAs<PointerType>()) {
2521       DestType = Context.getPointerType(DestRecordType);
2522       FromRecordType = FromType->getPointeeType();
2523       PointerConversions = true;
2524     } else {
2525       DestType = DestRecordType;
2526       FromRecordType = FromType;
2527     }
2528   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2529     if (Method->isStatic())
2530       return From;
2531 
2532     DestType = Method->getThisType(Context);
2533     DestRecordType = DestType->getPointeeType();
2534 
2535     if (FromType->getAs<PointerType>()) {
2536       FromRecordType = FromType->getPointeeType();
2537       PointerConversions = true;
2538     } else {
2539       FromRecordType = FromType;
2540       DestType = DestRecordType;
2541     }
2542   } else {
2543     // No conversion necessary.
2544     return From;
2545   }
2546 
2547   if (DestType->isDependentType() || FromType->isDependentType())
2548     return From;
2549 
2550   // If the unqualified types are the same, no conversion is necessary.
2551   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2552     return From;
2553 
2554   SourceRange FromRange = From->getSourceRange();
2555   SourceLocation FromLoc = FromRange.getBegin();
2556 
2557   ExprValueKind VK = From->getValueKind();
2558 
2559   // C++ [class.member.lookup]p8:
2560   //   [...] Ambiguities can often be resolved by qualifying a name with its
2561   //   class name.
2562   //
2563   // If the member was a qualified name and the qualified referred to a
2564   // specific base subobject type, we'll cast to that intermediate type
2565   // first and then to the object in which the member is declared. That allows
2566   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2567   //
2568   //   class Base { public: int x; };
2569   //   class Derived1 : public Base { };
2570   //   class Derived2 : public Base { };
2571   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2572   //
2573   //   void VeryDerived::f() {
2574   //     x = 17; // error: ambiguous base subobjects
2575   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2576   //   }
2577   if (Qualifier && Qualifier->getAsType()) {
2578     QualType QType = QualType(Qualifier->getAsType(), 0);
2579     assert(QType->isRecordType() && "lookup done with non-record type");
2580 
2581     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2582 
2583     // In C++98, the qualifier type doesn't actually have to be a base
2584     // type of the object type, in which case we just ignore it.
2585     // Otherwise build the appropriate casts.
2586     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2587       CXXCastPath BasePath;
2588       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2589                                        FromLoc, FromRange, &BasePath))
2590         return ExprError();
2591 
2592       if (PointerConversions)
2593         QType = Context.getPointerType(QType);
2594       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2595                                VK, &BasePath).get();
2596 
2597       FromType = QType;
2598       FromRecordType = QRecordType;
2599 
2600       // If the qualifier type was the same as the destination type,
2601       // we're done.
2602       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2603         return From;
2604     }
2605   }
2606 
2607   bool IgnoreAccess = false;
2608 
2609   // If we actually found the member through a using declaration, cast
2610   // down to the using declaration's type.
2611   //
2612   // Pointer equality is fine here because only one declaration of a
2613   // class ever has member declarations.
2614   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2615     assert(isa<UsingShadowDecl>(FoundDecl));
2616     QualType URecordType = Context.getTypeDeclType(
2617                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2618 
2619     // We only need to do this if the naming-class to declaring-class
2620     // conversion is non-trivial.
2621     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2622       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2623       CXXCastPath BasePath;
2624       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2625                                        FromLoc, FromRange, &BasePath))
2626         return ExprError();
2627 
2628       QualType UType = URecordType;
2629       if (PointerConversions)
2630         UType = Context.getPointerType(UType);
2631       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2632                                VK, &BasePath).get();
2633       FromType = UType;
2634       FromRecordType = URecordType;
2635     }
2636 
2637     // We don't do access control for the conversion from the
2638     // declaring class to the true declaring class.
2639     IgnoreAccess = true;
2640   }
2641 
2642   CXXCastPath BasePath;
2643   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2644                                    FromLoc, FromRange, &BasePath,
2645                                    IgnoreAccess))
2646     return ExprError();
2647 
2648   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2649                            VK, &BasePath);
2650 }
2651 
2652 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2653                                       const LookupResult &R,
2654                                       bool HasTrailingLParen) {
2655   // Only when used directly as the postfix-expression of a call.
2656   if (!HasTrailingLParen)
2657     return false;
2658 
2659   // Never if a scope specifier was provided.
2660   if (SS.isSet())
2661     return false;
2662 
2663   // Only in C++ or ObjC++.
2664   if (!getLangOpts().CPlusPlus)
2665     return false;
2666 
2667   // Turn off ADL when we find certain kinds of declarations during
2668   // normal lookup:
2669   for (NamedDecl *D : R) {
2670     // C++0x [basic.lookup.argdep]p3:
2671     //     -- a declaration of a class member
2672     // Since using decls preserve this property, we check this on the
2673     // original decl.
2674     if (D->isCXXClassMember())
2675       return false;
2676 
2677     // C++0x [basic.lookup.argdep]p3:
2678     //     -- a block-scope function declaration that is not a
2679     //        using-declaration
2680     // NOTE: we also trigger this for function templates (in fact, we
2681     // don't check the decl type at all, since all other decl types
2682     // turn off ADL anyway).
2683     if (isa<UsingShadowDecl>(D))
2684       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2685     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2686       return false;
2687 
2688     // C++0x [basic.lookup.argdep]p3:
2689     //     -- a declaration that is neither a function or a function
2690     //        template
2691     // And also for builtin functions.
2692     if (isa<FunctionDecl>(D)) {
2693       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2694 
2695       // But also builtin functions.
2696       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2697         return false;
2698     } else if (!isa<FunctionTemplateDecl>(D))
2699       return false;
2700   }
2701 
2702   return true;
2703 }
2704 
2705 
2706 /// Diagnoses obvious problems with the use of the given declaration
2707 /// as an expression.  This is only actually called for lookups that
2708 /// were not overloaded, and it doesn't promise that the declaration
2709 /// will in fact be used.
2710 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2711   if (D->isInvalidDecl())
2712     return true;
2713 
2714   if (isa<TypedefNameDecl>(D)) {
2715     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2716     return true;
2717   }
2718 
2719   if (isa<ObjCInterfaceDecl>(D)) {
2720     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2721     return true;
2722   }
2723 
2724   if (isa<NamespaceDecl>(D)) {
2725     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2726     return true;
2727   }
2728 
2729   return false;
2730 }
2731 
2732 // Certain multiversion types should be treated as overloaded even when there is
2733 // only one result.
2734 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2735   assert(R.isSingleResult() && "Expected only a single result");
2736   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2737   return FD &&
2738          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2739 }
2740 
2741 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2742                                           LookupResult &R, bool NeedsADL,
2743                                           bool AcceptInvalidDecl) {
2744   // If this is a single, fully-resolved result and we don't need ADL,
2745   // just build an ordinary singleton decl ref.
2746   if (!NeedsADL && R.isSingleResult() &&
2747       !R.getAsSingle<FunctionTemplateDecl>() &&
2748       !ShouldLookupResultBeMultiVersionOverload(R))
2749     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2750                                     R.getRepresentativeDecl(), nullptr,
2751                                     AcceptInvalidDecl);
2752 
2753   // We only need to check the declaration if there's exactly one
2754   // result, because in the overloaded case the results can only be
2755   // functions and function templates.
2756   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2757       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2758     return ExprError();
2759 
2760   // Otherwise, just build an unresolved lookup expression.  Suppress
2761   // any lookup-related diagnostics; we'll hash these out later, when
2762   // we've picked a target.
2763   R.suppressDiagnostics();
2764 
2765   UnresolvedLookupExpr *ULE
2766     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2767                                    SS.getWithLocInContext(Context),
2768                                    R.getLookupNameInfo(),
2769                                    NeedsADL, R.isOverloadedResult(),
2770                                    R.begin(), R.end());
2771 
2772   return ULE;
2773 }
2774 
2775 static void
2776 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2777                                    ValueDecl *var, DeclContext *DC);
2778 
2779 /// Complete semantic analysis for a reference to the given declaration.
2780 ExprResult Sema::BuildDeclarationNameExpr(
2781     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2782     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2783     bool AcceptInvalidDecl) {
2784   assert(D && "Cannot refer to a NULL declaration");
2785   assert(!isa<FunctionTemplateDecl>(D) &&
2786          "Cannot refer unambiguously to a function template");
2787 
2788   SourceLocation Loc = NameInfo.getLoc();
2789   if (CheckDeclInExpr(*this, Loc, D))
2790     return ExprError();
2791 
2792   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2793     // Specifically diagnose references to class templates that are missing
2794     // a template argument list.
2795     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2796     return ExprError();
2797   }
2798 
2799   // Make sure that we're referring to a value.
2800   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2801   if (!VD) {
2802     Diag(Loc, diag::err_ref_non_value)
2803       << D << SS.getRange();
2804     Diag(D->getLocation(), diag::note_declared_at);
2805     return ExprError();
2806   }
2807 
2808   // Check whether this declaration can be used. Note that we suppress
2809   // this check when we're going to perform argument-dependent lookup
2810   // on this function name, because this might not be the function
2811   // that overload resolution actually selects.
2812   if (DiagnoseUseOfDecl(VD, Loc))
2813     return ExprError();
2814 
2815   // Only create DeclRefExpr's for valid Decl's.
2816   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2817     return ExprError();
2818 
2819   // Handle members of anonymous structs and unions.  If we got here,
2820   // and the reference is to a class member indirect field, then this
2821   // must be the subject of a pointer-to-member expression.
2822   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2823     if (!indirectField->isCXXClassMember())
2824       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2825                                                       indirectField);
2826 
2827   {
2828     QualType type = VD->getType();
2829     if (type.isNull())
2830       return ExprError();
2831     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2832       // C++ [except.spec]p17:
2833       //   An exception-specification is considered to be needed when:
2834       //   - in an expression, the function is the unique lookup result or
2835       //     the selected member of a set of overloaded functions.
2836       ResolveExceptionSpec(Loc, FPT);
2837       type = VD->getType();
2838     }
2839     ExprValueKind valueKind = VK_RValue;
2840 
2841     switch (D->getKind()) {
2842     // Ignore all the non-ValueDecl kinds.
2843 #define ABSTRACT_DECL(kind)
2844 #define VALUE(type, base)
2845 #define DECL(type, base) \
2846     case Decl::type:
2847 #include "clang/AST/DeclNodes.inc"
2848       llvm_unreachable("invalid value decl kind");
2849 
2850     // These shouldn't make it here.
2851     case Decl::ObjCAtDefsField:
2852     case Decl::ObjCIvar:
2853       llvm_unreachable("forming non-member reference to ivar?");
2854 
2855     // Enum constants are always r-values and never references.
2856     // Unresolved using declarations are dependent.
2857     case Decl::EnumConstant:
2858     case Decl::UnresolvedUsingValue:
2859     case Decl::OMPDeclareReduction:
2860       valueKind = VK_RValue;
2861       break;
2862 
2863     // Fields and indirect fields that got here must be for
2864     // pointer-to-member expressions; we just call them l-values for
2865     // internal consistency, because this subexpression doesn't really
2866     // exist in the high-level semantics.
2867     case Decl::Field:
2868     case Decl::IndirectField:
2869       assert(getLangOpts().CPlusPlus &&
2870              "building reference to field in C?");
2871 
2872       // These can't have reference type in well-formed programs, but
2873       // for internal consistency we do this anyway.
2874       type = type.getNonReferenceType();
2875       valueKind = VK_LValue;
2876       break;
2877 
2878     // Non-type template parameters are either l-values or r-values
2879     // depending on the type.
2880     case Decl::NonTypeTemplateParm: {
2881       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2882         type = reftype->getPointeeType();
2883         valueKind = VK_LValue; // even if the parameter is an r-value reference
2884         break;
2885       }
2886 
2887       // For non-references, we need to strip qualifiers just in case
2888       // the template parameter was declared as 'const int' or whatever.
2889       valueKind = VK_RValue;
2890       type = type.getUnqualifiedType();
2891       break;
2892     }
2893 
2894     case Decl::Var:
2895     case Decl::VarTemplateSpecialization:
2896     case Decl::VarTemplatePartialSpecialization:
2897     case Decl::Decomposition:
2898     case Decl::OMPCapturedExpr:
2899       // In C, "extern void blah;" is valid and is an r-value.
2900       if (!getLangOpts().CPlusPlus &&
2901           !type.hasQualifiers() &&
2902           type->isVoidType()) {
2903         valueKind = VK_RValue;
2904         break;
2905       }
2906       LLVM_FALLTHROUGH;
2907 
2908     case Decl::ImplicitParam:
2909     case Decl::ParmVar: {
2910       // These are always l-values.
2911       valueKind = VK_LValue;
2912       type = type.getNonReferenceType();
2913 
2914       // FIXME: Does the addition of const really only apply in
2915       // potentially-evaluated contexts? Since the variable isn't actually
2916       // captured in an unevaluated context, it seems that the answer is no.
2917       if (!isUnevaluatedContext()) {
2918         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2919         if (!CapturedType.isNull())
2920           type = CapturedType;
2921       }
2922 
2923       break;
2924     }
2925 
2926     case Decl::Binding: {
2927       // These are always lvalues.
2928       valueKind = VK_LValue;
2929       type = type.getNonReferenceType();
2930       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2931       // decides how that's supposed to work.
2932       auto *BD = cast<BindingDecl>(VD);
2933       if (BD->getDeclContext()->isFunctionOrMethod() &&
2934           BD->getDeclContext() != CurContext)
2935         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2936       break;
2937     }
2938 
2939     case Decl::Function: {
2940       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2941         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2942           type = Context.BuiltinFnTy;
2943           valueKind = VK_RValue;
2944           break;
2945         }
2946       }
2947 
2948       const FunctionType *fty = type->castAs<FunctionType>();
2949 
2950       // If we're referring to a function with an __unknown_anytype
2951       // result type, make the entire expression __unknown_anytype.
2952       if (fty->getReturnType() == Context.UnknownAnyTy) {
2953         type = Context.UnknownAnyTy;
2954         valueKind = VK_RValue;
2955         break;
2956       }
2957 
2958       // Functions are l-values in C++.
2959       if (getLangOpts().CPlusPlus) {
2960         valueKind = VK_LValue;
2961         break;
2962       }
2963 
2964       // C99 DR 316 says that, if a function type comes from a
2965       // function definition (without a prototype), that type is only
2966       // used for checking compatibility. Therefore, when referencing
2967       // the function, we pretend that we don't have the full function
2968       // type.
2969       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2970           isa<FunctionProtoType>(fty))
2971         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2972                                               fty->getExtInfo());
2973 
2974       // Functions are r-values in C.
2975       valueKind = VK_RValue;
2976       break;
2977     }
2978 
2979     case Decl::CXXDeductionGuide:
2980       llvm_unreachable("building reference to deduction guide");
2981 
2982     case Decl::MSProperty:
2983       valueKind = VK_LValue;
2984       break;
2985 
2986     case Decl::CXXMethod:
2987       // If we're referring to a method with an __unknown_anytype
2988       // result type, make the entire expression __unknown_anytype.
2989       // This should only be possible with a type written directly.
2990       if (const FunctionProtoType *proto
2991             = dyn_cast<FunctionProtoType>(VD->getType()))
2992         if (proto->getReturnType() == Context.UnknownAnyTy) {
2993           type = Context.UnknownAnyTy;
2994           valueKind = VK_RValue;
2995           break;
2996         }
2997 
2998       // C++ methods are l-values if static, r-values if non-static.
2999       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3000         valueKind = VK_LValue;
3001         break;
3002       }
3003       LLVM_FALLTHROUGH;
3004 
3005     case Decl::CXXConversion:
3006     case Decl::CXXDestructor:
3007     case Decl::CXXConstructor:
3008       valueKind = VK_RValue;
3009       break;
3010     }
3011 
3012     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3013                             TemplateArgs);
3014   }
3015 }
3016 
3017 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3018                                     SmallString<32> &Target) {
3019   Target.resize(CharByteWidth * (Source.size() + 1));
3020   char *ResultPtr = &Target[0];
3021   const llvm::UTF8 *ErrorPtr;
3022   bool success =
3023       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3024   (void)success;
3025   assert(success);
3026   Target.resize(ResultPtr - &Target[0]);
3027 }
3028 
3029 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3030                                      PredefinedExpr::IdentType IT) {
3031   // Pick the current block, lambda, captured statement or function.
3032   Decl *currentDecl = nullptr;
3033   if (const BlockScopeInfo *BSI = getCurBlock())
3034     currentDecl = BSI->TheDecl;
3035   else if (const LambdaScopeInfo *LSI = getCurLambda())
3036     currentDecl = LSI->CallOperator;
3037   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3038     currentDecl = CSI->TheCapturedDecl;
3039   else
3040     currentDecl = getCurFunctionOrMethodDecl();
3041 
3042   if (!currentDecl) {
3043     Diag(Loc, diag::ext_predef_outside_function);
3044     currentDecl = Context.getTranslationUnitDecl();
3045   }
3046 
3047   QualType ResTy;
3048   StringLiteral *SL = nullptr;
3049   if (cast<DeclContext>(currentDecl)->isDependentContext())
3050     ResTy = Context.DependentTy;
3051   else {
3052     // Pre-defined identifiers are of type char[x], where x is the length of
3053     // the string.
3054     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3055     unsigned Length = Str.length();
3056 
3057     llvm::APInt LengthI(32, Length + 1);
3058     if (IT == PredefinedExpr::LFunction || IT == PredefinedExpr::LFuncSig) {
3059       ResTy =
3060           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3061       SmallString<32> RawChars;
3062       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3063                               Str, RawChars);
3064       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3065                                            /*IndexTypeQuals*/ 0);
3066       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3067                                  /*Pascal*/ false, ResTy, Loc);
3068     } else {
3069       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3070       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3071                                            /*IndexTypeQuals*/ 0);
3072       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3073                                  /*Pascal*/ false, ResTy, Loc);
3074     }
3075   }
3076 
3077   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3078 }
3079 
3080 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3081   PredefinedExpr::IdentType IT;
3082 
3083   switch (Kind) {
3084   default: llvm_unreachable("Unknown simple primary expr!");
3085   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3086   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3087   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3088   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3089   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; // [MS]
3090   case tok::kw_L__FUNCSIG__: IT = PredefinedExpr::LFuncSig; break; // [MS]
3091   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3092   }
3093 
3094   return BuildPredefinedExpr(Loc, IT);
3095 }
3096 
3097 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3098   SmallString<16> CharBuffer;
3099   bool Invalid = false;
3100   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3101   if (Invalid)
3102     return ExprError();
3103 
3104   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3105                             PP, Tok.getKind());
3106   if (Literal.hadError())
3107     return ExprError();
3108 
3109   QualType Ty;
3110   if (Literal.isWide())
3111     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3112   else if (Literal.isUTF8() && getLangOpts().Char8)
3113     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3114   else if (Literal.isUTF16())
3115     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3116   else if (Literal.isUTF32())
3117     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3118   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3119     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3120   else
3121     Ty = Context.CharTy;  // 'x' -> char in C++
3122 
3123   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3124   if (Literal.isWide())
3125     Kind = CharacterLiteral::Wide;
3126   else if (Literal.isUTF16())
3127     Kind = CharacterLiteral::UTF16;
3128   else if (Literal.isUTF32())
3129     Kind = CharacterLiteral::UTF32;
3130   else if (Literal.isUTF8())
3131     Kind = CharacterLiteral::UTF8;
3132 
3133   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3134                                              Tok.getLocation());
3135 
3136   if (Literal.getUDSuffix().empty())
3137     return Lit;
3138 
3139   // We're building a user-defined literal.
3140   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3141   SourceLocation UDSuffixLoc =
3142     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3143 
3144   // Make sure we're allowed user-defined literals here.
3145   if (!UDLScope)
3146     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3147 
3148   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3149   //   operator "" X (ch)
3150   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3151                                         Lit, Tok.getLocation());
3152 }
3153 
3154 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3155   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3156   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3157                                 Context.IntTy, Loc);
3158 }
3159 
3160 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3161                                   QualType Ty, SourceLocation Loc) {
3162   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3163 
3164   using llvm::APFloat;
3165   APFloat Val(Format);
3166 
3167   APFloat::opStatus result = Literal.GetFloatValue(Val);
3168 
3169   // Overflow is always an error, but underflow is only an error if
3170   // we underflowed to zero (APFloat reports denormals as underflow).
3171   if ((result & APFloat::opOverflow) ||
3172       ((result & APFloat::opUnderflow) && Val.isZero())) {
3173     unsigned diagnostic;
3174     SmallString<20> buffer;
3175     if (result & APFloat::opOverflow) {
3176       diagnostic = diag::warn_float_overflow;
3177       APFloat::getLargest(Format).toString(buffer);
3178     } else {
3179       diagnostic = diag::warn_float_underflow;
3180       APFloat::getSmallest(Format).toString(buffer);
3181     }
3182 
3183     S.Diag(Loc, diagnostic)
3184       << Ty
3185       << StringRef(buffer.data(), buffer.size());
3186   }
3187 
3188   bool isExact = (result == APFloat::opOK);
3189   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3190 }
3191 
3192 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3193   assert(E && "Invalid expression");
3194 
3195   if (E->isValueDependent())
3196     return false;
3197 
3198   QualType QT = E->getType();
3199   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3200     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3201     return true;
3202   }
3203 
3204   llvm::APSInt ValueAPS;
3205   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3206 
3207   if (R.isInvalid())
3208     return true;
3209 
3210   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3211   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3212     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3213         << ValueAPS.toString(10) << ValueIsPositive;
3214     return true;
3215   }
3216 
3217   return false;
3218 }
3219 
3220 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3221   // Fast path for a single digit (which is quite common).  A single digit
3222   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3223   if (Tok.getLength() == 1) {
3224     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3225     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3226   }
3227 
3228   SmallString<128> SpellingBuffer;
3229   // NumericLiteralParser wants to overread by one character.  Add padding to
3230   // the buffer in case the token is copied to the buffer.  If getSpelling()
3231   // returns a StringRef to the memory buffer, it should have a null char at
3232   // the EOF, so it is also safe.
3233   SpellingBuffer.resize(Tok.getLength() + 1);
3234 
3235   // Get the spelling of the token, which eliminates trigraphs, etc.
3236   bool Invalid = false;
3237   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3238   if (Invalid)
3239     return ExprError();
3240 
3241   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3242   if (Literal.hadError)
3243     return ExprError();
3244 
3245   if (Literal.hasUDSuffix()) {
3246     // We're building a user-defined literal.
3247     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3248     SourceLocation UDSuffixLoc =
3249       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3250 
3251     // Make sure we're allowed user-defined literals here.
3252     if (!UDLScope)
3253       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3254 
3255     QualType CookedTy;
3256     if (Literal.isFloatingLiteral()) {
3257       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3258       // long double, the literal is treated as a call of the form
3259       //   operator "" X (f L)
3260       CookedTy = Context.LongDoubleTy;
3261     } else {
3262       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3263       // unsigned long long, the literal is treated as a call of the form
3264       //   operator "" X (n ULL)
3265       CookedTy = Context.UnsignedLongLongTy;
3266     }
3267 
3268     DeclarationName OpName =
3269       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3270     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3271     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3272 
3273     SourceLocation TokLoc = Tok.getLocation();
3274 
3275     // Perform literal operator lookup to determine if we're building a raw
3276     // literal or a cooked one.
3277     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3278     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3279                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3280                                   /*AllowStringTemplate*/ false,
3281                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3282     case LOLR_ErrorNoDiagnostic:
3283       // Lookup failure for imaginary constants isn't fatal, there's still the
3284       // GNU extension producing _Complex types.
3285       break;
3286     case LOLR_Error:
3287       return ExprError();
3288     case LOLR_Cooked: {
3289       Expr *Lit;
3290       if (Literal.isFloatingLiteral()) {
3291         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3292       } else {
3293         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3294         if (Literal.GetIntegerValue(ResultVal))
3295           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3296               << /* Unsigned */ 1;
3297         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3298                                      Tok.getLocation());
3299       }
3300       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3301     }
3302 
3303     case LOLR_Raw: {
3304       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3305       // literal is treated as a call of the form
3306       //   operator "" X ("n")
3307       unsigned Length = Literal.getUDSuffixOffset();
3308       QualType StrTy = Context.getConstantArrayType(
3309           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3310           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3311       Expr *Lit = StringLiteral::Create(
3312           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3313           /*Pascal*/false, StrTy, &TokLoc, 1);
3314       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3315     }
3316 
3317     case LOLR_Template: {
3318       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3319       // template), L is treated as a call fo the form
3320       //   operator "" X <'c1', 'c2', ... 'ck'>()
3321       // where n is the source character sequence c1 c2 ... ck.
3322       TemplateArgumentListInfo ExplicitArgs;
3323       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3324       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3325       llvm::APSInt Value(CharBits, CharIsUnsigned);
3326       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3327         Value = TokSpelling[I];
3328         TemplateArgument Arg(Context, Value, Context.CharTy);
3329         TemplateArgumentLocInfo ArgInfo;
3330         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3331       }
3332       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3333                                       &ExplicitArgs);
3334     }
3335     case LOLR_StringTemplate:
3336       llvm_unreachable("unexpected literal operator lookup result");
3337     }
3338   }
3339 
3340   Expr *Res;
3341 
3342   if (Literal.isFixedPointLiteral()) {
3343     QualType Ty;
3344 
3345     if (Literal.isAccum) {
3346       if (Literal.isHalf) {
3347         Ty = Context.ShortAccumTy;
3348       } else if (Literal.isLong) {
3349         Ty = Context.LongAccumTy;
3350       } else {
3351         Ty = Context.AccumTy;
3352       }
3353     } else if (Literal.isFract) {
3354       if (Literal.isHalf) {
3355         Ty = Context.ShortFractTy;
3356       } else if (Literal.isLong) {
3357         Ty = Context.LongFractTy;
3358       } else {
3359         Ty = Context.FractTy;
3360       }
3361     }
3362 
3363     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3364 
3365     bool isSigned = !Literal.isUnsigned;
3366     unsigned scale = Context.getFixedPointScale(Ty);
3367     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3368 
3369     llvm::APInt Val(bit_width, 0, isSigned);
3370     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3371     bool ValIsZero = Val.isNullValue() && !Overflowed;
3372 
3373     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3374     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3375       // Clause 6.4.4 - The value of a constant shall be in the range of
3376       // representable values for its type, with exception for constants of a
3377       // fract type with a value of exactly 1; such a constant shall denote
3378       // the maximal value for the type.
3379       --Val;
3380     else if (Val.ugt(MaxVal) || Overflowed)
3381       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3382 
3383     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3384                                               Tok.getLocation(), scale);
3385   } else if (Literal.isFloatingLiteral()) {
3386     QualType Ty;
3387     if (Literal.isHalf){
3388       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3389         Ty = Context.HalfTy;
3390       else {
3391         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3392         return ExprError();
3393       }
3394     } else if (Literal.isFloat)
3395       Ty = Context.FloatTy;
3396     else if (Literal.isLong)
3397       Ty = Context.LongDoubleTy;
3398     else if (Literal.isFloat16)
3399       Ty = Context.Float16Ty;
3400     else if (Literal.isFloat128)
3401       Ty = Context.Float128Ty;
3402     else
3403       Ty = Context.DoubleTy;
3404 
3405     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3406 
3407     if (Ty == Context.DoubleTy) {
3408       if (getLangOpts().SinglePrecisionConstants) {
3409         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3410         if (BTy->getKind() != BuiltinType::Float) {
3411           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3412         }
3413       } else if (getLangOpts().OpenCL &&
3414                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3415         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3416         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3417         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3418       }
3419     }
3420   } else if (!Literal.isIntegerLiteral()) {
3421     return ExprError();
3422   } else {
3423     QualType Ty;
3424 
3425     // 'long long' is a C99 or C++11 feature.
3426     if (!getLangOpts().C99 && Literal.isLongLong) {
3427       if (getLangOpts().CPlusPlus)
3428         Diag(Tok.getLocation(),
3429              getLangOpts().CPlusPlus11 ?
3430              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3431       else
3432         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3433     }
3434 
3435     // Get the value in the widest-possible width.
3436     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3437     llvm::APInt ResultVal(MaxWidth, 0);
3438 
3439     if (Literal.GetIntegerValue(ResultVal)) {
3440       // If this value didn't fit into uintmax_t, error and force to ull.
3441       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3442           << /* Unsigned */ 1;
3443       Ty = Context.UnsignedLongLongTy;
3444       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3445              "long long is not intmax_t?");
3446     } else {
3447       // If this value fits into a ULL, try to figure out what else it fits into
3448       // according to the rules of C99 6.4.4.1p5.
3449 
3450       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3451       // be an unsigned int.
3452       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3453 
3454       // Check from smallest to largest, picking the smallest type we can.
3455       unsigned Width = 0;
3456 
3457       // Microsoft specific integer suffixes are explicitly sized.
3458       if (Literal.MicrosoftInteger) {
3459         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3460           Width = 8;
3461           Ty = Context.CharTy;
3462         } else {
3463           Width = Literal.MicrosoftInteger;
3464           Ty = Context.getIntTypeForBitwidth(Width,
3465                                              /*Signed=*/!Literal.isUnsigned);
3466         }
3467       }
3468 
3469       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3470         // Are int/unsigned possibilities?
3471         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3472 
3473         // Does it fit in a unsigned int?
3474         if (ResultVal.isIntN(IntSize)) {
3475           // Does it fit in a signed int?
3476           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3477             Ty = Context.IntTy;
3478           else if (AllowUnsigned)
3479             Ty = Context.UnsignedIntTy;
3480           Width = IntSize;
3481         }
3482       }
3483 
3484       // Are long/unsigned long possibilities?
3485       if (Ty.isNull() && !Literal.isLongLong) {
3486         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3487 
3488         // Does it fit in a unsigned long?
3489         if (ResultVal.isIntN(LongSize)) {
3490           // Does it fit in a signed long?
3491           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3492             Ty = Context.LongTy;
3493           else if (AllowUnsigned)
3494             Ty = Context.UnsignedLongTy;
3495           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3496           // is compatible.
3497           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3498             const unsigned LongLongSize =
3499                 Context.getTargetInfo().getLongLongWidth();
3500             Diag(Tok.getLocation(),
3501                  getLangOpts().CPlusPlus
3502                      ? Literal.isLong
3503                            ? diag::warn_old_implicitly_unsigned_long_cxx
3504                            : /*C++98 UB*/ diag::
3505                                  ext_old_implicitly_unsigned_long_cxx
3506                      : diag::warn_old_implicitly_unsigned_long)
3507                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3508                                             : /*will be ill-formed*/ 1);
3509             Ty = Context.UnsignedLongTy;
3510           }
3511           Width = LongSize;
3512         }
3513       }
3514 
3515       // Check long long if needed.
3516       if (Ty.isNull()) {
3517         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3518 
3519         // Does it fit in a unsigned long long?
3520         if (ResultVal.isIntN(LongLongSize)) {
3521           // Does it fit in a signed long long?
3522           // To be compatible with MSVC, hex integer literals ending with the
3523           // LL or i64 suffix are always signed in Microsoft mode.
3524           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3525               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3526             Ty = Context.LongLongTy;
3527           else if (AllowUnsigned)
3528             Ty = Context.UnsignedLongLongTy;
3529           Width = LongLongSize;
3530         }
3531       }
3532 
3533       // If we still couldn't decide a type, we probably have something that
3534       // does not fit in a signed long long, but has no U suffix.
3535       if (Ty.isNull()) {
3536         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3537         Ty = Context.UnsignedLongLongTy;
3538         Width = Context.getTargetInfo().getLongLongWidth();
3539       }
3540 
3541       if (ResultVal.getBitWidth() != Width)
3542         ResultVal = ResultVal.trunc(Width);
3543     }
3544     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3545   }
3546 
3547   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3548   if (Literal.isImaginary) {
3549     Res = new (Context) ImaginaryLiteral(Res,
3550                                         Context.getComplexType(Res->getType()));
3551 
3552     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3553   }
3554   return Res;
3555 }
3556 
3557 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3558   assert(E && "ActOnParenExpr() missing expr");
3559   return new (Context) ParenExpr(L, R, E);
3560 }
3561 
3562 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3563                                          SourceLocation Loc,
3564                                          SourceRange ArgRange) {
3565   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3566   // scalar or vector data type argument..."
3567   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3568   // type (C99 6.2.5p18) or void.
3569   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3570     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3571       << T << ArgRange;
3572     return true;
3573   }
3574 
3575   assert((T->isVoidType() || !T->isIncompleteType()) &&
3576          "Scalar types should always be complete");
3577   return false;
3578 }
3579 
3580 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3581                                            SourceLocation Loc,
3582                                            SourceRange ArgRange,
3583                                            UnaryExprOrTypeTrait TraitKind) {
3584   // Invalid types must be hard errors for SFINAE in C++.
3585   if (S.LangOpts.CPlusPlus)
3586     return true;
3587 
3588   // C99 6.5.3.4p1:
3589   if (T->isFunctionType() &&
3590       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3591     // sizeof(function)/alignof(function) is allowed as an extension.
3592     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3593       << TraitKind << ArgRange;
3594     return false;
3595   }
3596 
3597   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3598   // this is an error (OpenCL v1.1 s6.3.k)
3599   if (T->isVoidType()) {
3600     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3601                                         : diag::ext_sizeof_alignof_void_type;
3602     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3603     return false;
3604   }
3605 
3606   return true;
3607 }
3608 
3609 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3610                                              SourceLocation Loc,
3611                                              SourceRange ArgRange,
3612                                              UnaryExprOrTypeTrait TraitKind) {
3613   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3614   // runtime doesn't allow it.
3615   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3616     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3617       << T << (TraitKind == UETT_SizeOf)
3618       << ArgRange;
3619     return true;
3620   }
3621 
3622   return false;
3623 }
3624 
3625 /// Check whether E is a pointer from a decayed array type (the decayed
3626 /// pointer type is equal to T) and emit a warning if it is.
3627 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3628                                      Expr *E) {
3629   // Don't warn if the operation changed the type.
3630   if (T != E->getType())
3631     return;
3632 
3633   // Now look for array decays.
3634   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3635   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3636     return;
3637 
3638   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3639                                              << ICE->getType()
3640                                              << ICE->getSubExpr()->getType();
3641 }
3642 
3643 /// Check the constraints on expression operands to unary type expression
3644 /// and type traits.
3645 ///
3646 /// Completes any types necessary and validates the constraints on the operand
3647 /// expression. The logic mostly mirrors the type-based overload, but may modify
3648 /// the expression as it completes the type for that expression through template
3649 /// instantiation, etc.
3650 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3651                                             UnaryExprOrTypeTrait ExprKind) {
3652   QualType ExprTy = E->getType();
3653   assert(!ExprTy->isReferenceType());
3654 
3655   if (ExprKind == UETT_VecStep)
3656     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3657                                         E->getSourceRange());
3658 
3659   // Whitelist some types as extensions
3660   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3661                                       E->getSourceRange(), ExprKind))
3662     return false;
3663 
3664   // 'alignof' applied to an expression only requires the base element type of
3665   // the expression to be complete. 'sizeof' requires the expression's type to
3666   // be complete (and will attempt to complete it if it's an array of unknown
3667   // bound).
3668   if (ExprKind == UETT_AlignOf) {
3669     if (RequireCompleteType(E->getExprLoc(),
3670                             Context.getBaseElementType(E->getType()),
3671                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3672                             E->getSourceRange()))
3673       return true;
3674   } else {
3675     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3676                                 ExprKind, E->getSourceRange()))
3677       return true;
3678   }
3679 
3680   // Completing the expression's type may have changed it.
3681   ExprTy = E->getType();
3682   assert(!ExprTy->isReferenceType());
3683 
3684   if (ExprTy->isFunctionType()) {
3685     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3686       << ExprKind << E->getSourceRange();
3687     return true;
3688   }
3689 
3690   // The operand for sizeof and alignof is in an unevaluated expression context,
3691   // so side effects could result in unintended consequences.
3692   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3693       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3694     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3695 
3696   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3697                                        E->getSourceRange(), ExprKind))
3698     return true;
3699 
3700   if (ExprKind == UETT_SizeOf) {
3701     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3702       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3703         QualType OType = PVD->getOriginalType();
3704         QualType Type = PVD->getType();
3705         if (Type->isPointerType() && OType->isArrayType()) {
3706           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3707             << Type << OType;
3708           Diag(PVD->getLocation(), diag::note_declared_at);
3709         }
3710       }
3711     }
3712 
3713     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3714     // decays into a pointer and returns an unintended result. This is most
3715     // likely a typo for "sizeof(array) op x".
3716     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3717       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3718                                BO->getLHS());
3719       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3720                                BO->getRHS());
3721     }
3722   }
3723 
3724   return false;
3725 }
3726 
3727 /// Check the constraints on operands to unary expression and type
3728 /// traits.
3729 ///
3730 /// This will complete any types necessary, and validate the various constraints
3731 /// on those operands.
3732 ///
3733 /// The UsualUnaryConversions() function is *not* called by this routine.
3734 /// C99 6.3.2.1p[2-4] all state:
3735 ///   Except when it is the operand of the sizeof operator ...
3736 ///
3737 /// C++ [expr.sizeof]p4
3738 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3739 ///   standard conversions are not applied to the operand of sizeof.
3740 ///
3741 /// This policy is followed for all of the unary trait expressions.
3742 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3743                                             SourceLocation OpLoc,
3744                                             SourceRange ExprRange,
3745                                             UnaryExprOrTypeTrait ExprKind) {
3746   if (ExprType->isDependentType())
3747     return false;
3748 
3749   // C++ [expr.sizeof]p2:
3750   //     When applied to a reference or a reference type, the result
3751   //     is the size of the referenced type.
3752   // C++11 [expr.alignof]p3:
3753   //     When alignof is applied to a reference type, the result
3754   //     shall be the alignment of the referenced type.
3755   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3756     ExprType = Ref->getPointeeType();
3757 
3758   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3759   //   When alignof or _Alignof is applied to an array type, the result
3760   //   is the alignment of the element type.
3761   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3762     ExprType = Context.getBaseElementType(ExprType);
3763 
3764   if (ExprKind == UETT_VecStep)
3765     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3766 
3767   // Whitelist some types as extensions
3768   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3769                                       ExprKind))
3770     return false;
3771 
3772   if (RequireCompleteType(OpLoc, ExprType,
3773                           diag::err_sizeof_alignof_incomplete_type,
3774                           ExprKind, ExprRange))
3775     return true;
3776 
3777   if (ExprType->isFunctionType()) {
3778     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3779       << ExprKind << ExprRange;
3780     return true;
3781   }
3782 
3783   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3784                                        ExprKind))
3785     return true;
3786 
3787   return false;
3788 }
3789 
3790 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3791   E = E->IgnoreParens();
3792 
3793   // Cannot know anything else if the expression is dependent.
3794   if (E->isTypeDependent())
3795     return false;
3796 
3797   if (E->getObjectKind() == OK_BitField) {
3798     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3799        << 1 << E->getSourceRange();
3800     return true;
3801   }
3802 
3803   ValueDecl *D = nullptr;
3804   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3805     D = DRE->getDecl();
3806   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3807     D = ME->getMemberDecl();
3808   }
3809 
3810   // If it's a field, require the containing struct to have a
3811   // complete definition so that we can compute the layout.
3812   //
3813   // This can happen in C++11 onwards, either by naming the member
3814   // in a way that is not transformed into a member access expression
3815   // (in an unevaluated operand, for instance), or by naming the member
3816   // in a trailing-return-type.
3817   //
3818   // For the record, since __alignof__ on expressions is a GCC
3819   // extension, GCC seems to permit this but always gives the
3820   // nonsensical answer 0.
3821   //
3822   // We don't really need the layout here --- we could instead just
3823   // directly check for all the appropriate alignment-lowing
3824   // attributes --- but that would require duplicating a lot of
3825   // logic that just isn't worth duplicating for such a marginal
3826   // use-case.
3827   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3828     // Fast path this check, since we at least know the record has a
3829     // definition if we can find a member of it.
3830     if (!FD->getParent()->isCompleteDefinition()) {
3831       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3832         << E->getSourceRange();
3833       return true;
3834     }
3835 
3836     // Otherwise, if it's a field, and the field doesn't have
3837     // reference type, then it must have a complete type (or be a
3838     // flexible array member, which we explicitly want to
3839     // white-list anyway), which makes the following checks trivial.
3840     if (!FD->getType()->isReferenceType())
3841       return false;
3842   }
3843 
3844   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3845 }
3846 
3847 bool Sema::CheckVecStepExpr(Expr *E) {
3848   E = E->IgnoreParens();
3849 
3850   // Cannot know anything else if the expression is dependent.
3851   if (E->isTypeDependent())
3852     return false;
3853 
3854   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3855 }
3856 
3857 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3858                                         CapturingScopeInfo *CSI) {
3859   assert(T->isVariablyModifiedType());
3860   assert(CSI != nullptr);
3861 
3862   // We're going to walk down into the type and look for VLA expressions.
3863   do {
3864     const Type *Ty = T.getTypePtr();
3865     switch (Ty->getTypeClass()) {
3866 #define TYPE(Class, Base)
3867 #define ABSTRACT_TYPE(Class, Base)
3868 #define NON_CANONICAL_TYPE(Class, Base)
3869 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3870 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3871 #include "clang/AST/TypeNodes.def"
3872       T = QualType();
3873       break;
3874     // These types are never variably-modified.
3875     case Type::Builtin:
3876     case Type::Complex:
3877     case Type::Vector:
3878     case Type::ExtVector:
3879     case Type::Record:
3880     case Type::Enum:
3881     case Type::Elaborated:
3882     case Type::TemplateSpecialization:
3883     case Type::ObjCObject:
3884     case Type::ObjCInterface:
3885     case Type::ObjCObjectPointer:
3886     case Type::ObjCTypeParam:
3887     case Type::Pipe:
3888       llvm_unreachable("type class is never variably-modified!");
3889     case Type::Adjusted:
3890       T = cast<AdjustedType>(Ty)->getOriginalType();
3891       break;
3892     case Type::Decayed:
3893       T = cast<DecayedType>(Ty)->getPointeeType();
3894       break;
3895     case Type::Pointer:
3896       T = cast<PointerType>(Ty)->getPointeeType();
3897       break;
3898     case Type::BlockPointer:
3899       T = cast<BlockPointerType>(Ty)->getPointeeType();
3900       break;
3901     case Type::LValueReference:
3902     case Type::RValueReference:
3903       T = cast<ReferenceType>(Ty)->getPointeeType();
3904       break;
3905     case Type::MemberPointer:
3906       T = cast<MemberPointerType>(Ty)->getPointeeType();
3907       break;
3908     case Type::ConstantArray:
3909     case Type::IncompleteArray:
3910       // Losing element qualification here is fine.
3911       T = cast<ArrayType>(Ty)->getElementType();
3912       break;
3913     case Type::VariableArray: {
3914       // Losing element qualification here is fine.
3915       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3916 
3917       // Unknown size indication requires no size computation.
3918       // Otherwise, evaluate and record it.
3919       if (auto Size = VAT->getSizeExpr()) {
3920         if (!CSI->isVLATypeCaptured(VAT)) {
3921           RecordDecl *CapRecord = nullptr;
3922           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3923             CapRecord = LSI->Lambda;
3924           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3925             CapRecord = CRSI->TheRecordDecl;
3926           }
3927           if (CapRecord) {
3928             auto ExprLoc = Size->getExprLoc();
3929             auto SizeType = Context.getSizeType();
3930             // Build the non-static data member.
3931             auto Field =
3932                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3933                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3934                                   /*BW*/ nullptr, /*Mutable*/ false,
3935                                   /*InitStyle*/ ICIS_NoInit);
3936             Field->setImplicit(true);
3937             Field->setAccess(AS_private);
3938             Field->setCapturedVLAType(VAT);
3939             CapRecord->addDecl(Field);
3940 
3941             CSI->addVLATypeCapture(ExprLoc, SizeType);
3942           }
3943         }
3944       }
3945       T = VAT->getElementType();
3946       break;
3947     }
3948     case Type::FunctionProto:
3949     case Type::FunctionNoProto:
3950       T = cast<FunctionType>(Ty)->getReturnType();
3951       break;
3952     case Type::Paren:
3953     case Type::TypeOf:
3954     case Type::UnaryTransform:
3955     case Type::Attributed:
3956     case Type::SubstTemplateTypeParm:
3957     case Type::PackExpansion:
3958       // Keep walking after single level desugaring.
3959       T = T.getSingleStepDesugaredType(Context);
3960       break;
3961     case Type::Typedef:
3962       T = cast<TypedefType>(Ty)->desugar();
3963       break;
3964     case Type::Decltype:
3965       T = cast<DecltypeType>(Ty)->desugar();
3966       break;
3967     case Type::Auto:
3968     case Type::DeducedTemplateSpecialization:
3969       T = cast<DeducedType>(Ty)->getDeducedType();
3970       break;
3971     case Type::TypeOfExpr:
3972       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3973       break;
3974     case Type::Atomic:
3975       T = cast<AtomicType>(Ty)->getValueType();
3976       break;
3977     }
3978   } while (!T.isNull() && T->isVariablyModifiedType());
3979 }
3980 
3981 /// Build a sizeof or alignof expression given a type operand.
3982 ExprResult
3983 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3984                                      SourceLocation OpLoc,
3985                                      UnaryExprOrTypeTrait ExprKind,
3986                                      SourceRange R) {
3987   if (!TInfo)
3988     return ExprError();
3989 
3990   QualType T = TInfo->getType();
3991 
3992   if (!T->isDependentType() &&
3993       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3994     return ExprError();
3995 
3996   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3997     if (auto *TT = T->getAs<TypedefType>()) {
3998       for (auto I = FunctionScopes.rbegin(),
3999                 E = std::prev(FunctionScopes.rend());
4000            I != E; ++I) {
4001         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4002         if (CSI == nullptr)
4003           break;
4004         DeclContext *DC = nullptr;
4005         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4006           DC = LSI->CallOperator;
4007         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4008           DC = CRSI->TheCapturedDecl;
4009         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4010           DC = BSI->TheDecl;
4011         if (DC) {
4012           if (DC->containsDecl(TT->getDecl()))
4013             break;
4014           captureVariablyModifiedType(Context, T, CSI);
4015         }
4016       }
4017     }
4018   }
4019 
4020   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4021   return new (Context) UnaryExprOrTypeTraitExpr(
4022       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4023 }
4024 
4025 /// Build a sizeof or alignof expression given an expression
4026 /// operand.
4027 ExprResult
4028 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4029                                      UnaryExprOrTypeTrait ExprKind) {
4030   ExprResult PE = CheckPlaceholderExpr(E);
4031   if (PE.isInvalid())
4032     return ExprError();
4033 
4034   E = PE.get();
4035 
4036   // Verify that the operand is valid.
4037   bool isInvalid = false;
4038   if (E->isTypeDependent()) {
4039     // Delay type-checking for type-dependent expressions.
4040   } else if (ExprKind == UETT_AlignOf) {
4041     isInvalid = CheckAlignOfExpr(*this, E);
4042   } else if (ExprKind == UETT_VecStep) {
4043     isInvalid = CheckVecStepExpr(E);
4044   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4045       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4046       isInvalid = true;
4047   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4048     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4049     isInvalid = true;
4050   } else {
4051     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4052   }
4053 
4054   if (isInvalid)
4055     return ExprError();
4056 
4057   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4058     PE = TransformToPotentiallyEvaluated(E);
4059     if (PE.isInvalid()) return ExprError();
4060     E = PE.get();
4061   }
4062 
4063   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4064   return new (Context) UnaryExprOrTypeTraitExpr(
4065       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4066 }
4067 
4068 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4069 /// expr and the same for @c alignof and @c __alignof
4070 /// Note that the ArgRange is invalid if isType is false.
4071 ExprResult
4072 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4073                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4074                                     void *TyOrEx, SourceRange ArgRange) {
4075   // If error parsing type, ignore.
4076   if (!TyOrEx) return ExprError();
4077 
4078   if (IsType) {
4079     TypeSourceInfo *TInfo;
4080     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4081     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4082   }
4083 
4084   Expr *ArgEx = (Expr *)TyOrEx;
4085   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4086   return Result;
4087 }
4088 
4089 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4090                                      bool IsReal) {
4091   if (V.get()->isTypeDependent())
4092     return S.Context.DependentTy;
4093 
4094   // _Real and _Imag are only l-values for normal l-values.
4095   if (V.get()->getObjectKind() != OK_Ordinary) {
4096     V = S.DefaultLvalueConversion(V.get());
4097     if (V.isInvalid())
4098       return QualType();
4099   }
4100 
4101   // These operators return the element type of a complex type.
4102   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4103     return CT->getElementType();
4104 
4105   // Otherwise they pass through real integer and floating point types here.
4106   if (V.get()->getType()->isArithmeticType())
4107     return V.get()->getType();
4108 
4109   // Test for placeholders.
4110   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4111   if (PR.isInvalid()) return QualType();
4112   if (PR.get() != V.get()) {
4113     V = PR;
4114     return CheckRealImagOperand(S, V, Loc, IsReal);
4115   }
4116 
4117   // Reject anything else.
4118   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4119     << (IsReal ? "__real" : "__imag");
4120   return QualType();
4121 }
4122 
4123 
4124 
4125 ExprResult
4126 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4127                           tok::TokenKind Kind, Expr *Input) {
4128   UnaryOperatorKind Opc;
4129   switch (Kind) {
4130   default: llvm_unreachable("Unknown unary op!");
4131   case tok::plusplus:   Opc = UO_PostInc; break;
4132   case tok::minusminus: Opc = UO_PostDec; break;
4133   }
4134 
4135   // Since this might is a postfix expression, get rid of ParenListExprs.
4136   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4137   if (Result.isInvalid()) return ExprError();
4138   Input = Result.get();
4139 
4140   return BuildUnaryOp(S, OpLoc, Opc, Input);
4141 }
4142 
4143 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4144 ///
4145 /// \return true on error
4146 static bool checkArithmeticOnObjCPointer(Sema &S,
4147                                          SourceLocation opLoc,
4148                                          Expr *op) {
4149   assert(op->getType()->isObjCObjectPointerType());
4150   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4151       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4152     return false;
4153 
4154   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4155     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4156     << op->getSourceRange();
4157   return true;
4158 }
4159 
4160 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4161   auto *BaseNoParens = Base->IgnoreParens();
4162   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4163     return MSProp->getPropertyDecl()->getType()->isArrayType();
4164   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4165 }
4166 
4167 ExprResult
4168 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4169                               Expr *idx, SourceLocation rbLoc) {
4170   if (base && !base->getType().isNull() &&
4171       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4172     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4173                                     /*Length=*/nullptr, rbLoc);
4174 
4175   // Since this might be a postfix expression, get rid of ParenListExprs.
4176   if (isa<ParenListExpr>(base)) {
4177     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4178     if (result.isInvalid()) return ExprError();
4179     base = result.get();
4180   }
4181 
4182   // Handle any non-overload placeholder types in the base and index
4183   // expressions.  We can't handle overloads here because the other
4184   // operand might be an overloadable type, in which case the overload
4185   // resolution for the operator overload should get the first crack
4186   // at the overload.
4187   bool IsMSPropertySubscript = false;
4188   if (base->getType()->isNonOverloadPlaceholderType()) {
4189     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4190     if (!IsMSPropertySubscript) {
4191       ExprResult result = CheckPlaceholderExpr(base);
4192       if (result.isInvalid())
4193         return ExprError();
4194       base = result.get();
4195     }
4196   }
4197   if (idx->getType()->isNonOverloadPlaceholderType()) {
4198     ExprResult result = CheckPlaceholderExpr(idx);
4199     if (result.isInvalid()) return ExprError();
4200     idx = result.get();
4201   }
4202 
4203   // Build an unanalyzed expression if either operand is type-dependent.
4204   if (getLangOpts().CPlusPlus &&
4205       (base->isTypeDependent() || idx->isTypeDependent())) {
4206     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4207                                             VK_LValue, OK_Ordinary, rbLoc);
4208   }
4209 
4210   // MSDN, property (C++)
4211   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4212   // This attribute can also be used in the declaration of an empty array in a
4213   // class or structure definition. For example:
4214   // __declspec(property(get=GetX, put=PutX)) int x[];
4215   // The above statement indicates that x[] can be used with one or more array
4216   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4217   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4218   if (IsMSPropertySubscript) {
4219     // Build MS property subscript expression if base is MS property reference
4220     // or MS property subscript.
4221     return new (Context) MSPropertySubscriptExpr(
4222         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4223   }
4224 
4225   // Use C++ overloaded-operator rules if either operand has record
4226   // type.  The spec says to do this if either type is *overloadable*,
4227   // but enum types can't declare subscript operators or conversion
4228   // operators, so there's nothing interesting for overload resolution
4229   // to do if there aren't any record types involved.
4230   //
4231   // ObjC pointers have their own subscripting logic that is not tied
4232   // to overload resolution and so should not take this path.
4233   if (getLangOpts().CPlusPlus &&
4234       (base->getType()->isRecordType() ||
4235        (!base->getType()->isObjCObjectPointerType() &&
4236         idx->getType()->isRecordType()))) {
4237     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4238   }
4239 
4240   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4241 }
4242 
4243 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4244                                           Expr *LowerBound,
4245                                           SourceLocation ColonLoc, Expr *Length,
4246                                           SourceLocation RBLoc) {
4247   if (Base->getType()->isPlaceholderType() &&
4248       !Base->getType()->isSpecificPlaceholderType(
4249           BuiltinType::OMPArraySection)) {
4250     ExprResult Result = CheckPlaceholderExpr(Base);
4251     if (Result.isInvalid())
4252       return ExprError();
4253     Base = Result.get();
4254   }
4255   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4256     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4257     if (Result.isInvalid())
4258       return ExprError();
4259     Result = DefaultLvalueConversion(Result.get());
4260     if (Result.isInvalid())
4261       return ExprError();
4262     LowerBound = Result.get();
4263   }
4264   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4265     ExprResult Result = CheckPlaceholderExpr(Length);
4266     if (Result.isInvalid())
4267       return ExprError();
4268     Result = DefaultLvalueConversion(Result.get());
4269     if (Result.isInvalid())
4270       return ExprError();
4271     Length = Result.get();
4272   }
4273 
4274   // Build an unanalyzed expression if either operand is type-dependent.
4275   if (Base->isTypeDependent() ||
4276       (LowerBound &&
4277        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4278       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4279     return new (Context)
4280         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4281                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4282   }
4283 
4284   // Perform default conversions.
4285   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4286   QualType ResultTy;
4287   if (OriginalTy->isAnyPointerType()) {
4288     ResultTy = OriginalTy->getPointeeType();
4289   } else if (OriginalTy->isArrayType()) {
4290     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4291   } else {
4292     return ExprError(
4293         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4294         << Base->getSourceRange());
4295   }
4296   // C99 6.5.2.1p1
4297   if (LowerBound) {
4298     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4299                                                       LowerBound);
4300     if (Res.isInvalid())
4301       return ExprError(Diag(LowerBound->getExprLoc(),
4302                             diag::err_omp_typecheck_section_not_integer)
4303                        << 0 << LowerBound->getSourceRange());
4304     LowerBound = Res.get();
4305 
4306     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4307         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4308       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4309           << 0 << LowerBound->getSourceRange();
4310   }
4311   if (Length) {
4312     auto Res =
4313         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4314     if (Res.isInvalid())
4315       return ExprError(Diag(Length->getExprLoc(),
4316                             diag::err_omp_typecheck_section_not_integer)
4317                        << 1 << Length->getSourceRange());
4318     Length = Res.get();
4319 
4320     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4321         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4322       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4323           << 1 << Length->getSourceRange();
4324   }
4325 
4326   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4327   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4328   // type. Note that functions are not objects, and that (in C99 parlance)
4329   // incomplete types are not object types.
4330   if (ResultTy->isFunctionType()) {
4331     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4332         << ResultTy << Base->getSourceRange();
4333     return ExprError();
4334   }
4335 
4336   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4337                           diag::err_omp_section_incomplete_type, Base))
4338     return ExprError();
4339 
4340   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4341     llvm::APSInt LowerBoundValue;
4342     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4343       // OpenMP 4.5, [2.4 Array Sections]
4344       // The array section must be a subset of the original array.
4345       if (LowerBoundValue.isNegative()) {
4346         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4347             << LowerBound->getSourceRange();
4348         return ExprError();
4349       }
4350     }
4351   }
4352 
4353   if (Length) {
4354     llvm::APSInt LengthValue;
4355     if (Length->EvaluateAsInt(LengthValue, Context)) {
4356       // OpenMP 4.5, [2.4 Array Sections]
4357       // The length must evaluate to non-negative integers.
4358       if (LengthValue.isNegative()) {
4359         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4360             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4361             << Length->getSourceRange();
4362         return ExprError();
4363       }
4364     }
4365   } else if (ColonLoc.isValid() &&
4366              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4367                                       !OriginalTy->isVariableArrayType()))) {
4368     // OpenMP 4.5, [2.4 Array Sections]
4369     // When the size of the array dimension is not known, the length must be
4370     // specified explicitly.
4371     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4372         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4373     return ExprError();
4374   }
4375 
4376   if (!Base->getType()->isSpecificPlaceholderType(
4377           BuiltinType::OMPArraySection)) {
4378     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4379     if (Result.isInvalid())
4380       return ExprError();
4381     Base = Result.get();
4382   }
4383   return new (Context)
4384       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4385                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4386 }
4387 
4388 ExprResult
4389 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4390                                       Expr *Idx, SourceLocation RLoc) {
4391   Expr *LHSExp = Base;
4392   Expr *RHSExp = Idx;
4393 
4394   ExprValueKind VK = VK_LValue;
4395   ExprObjectKind OK = OK_Ordinary;
4396 
4397   // Per C++ core issue 1213, the result is an xvalue if either operand is
4398   // a non-lvalue array, and an lvalue otherwise.
4399   if (getLangOpts().CPlusPlus11) {
4400     for (auto *Op : {LHSExp, RHSExp}) {
4401       Op = Op->IgnoreImplicit();
4402       if (Op->getType()->isArrayType() && !Op->isLValue())
4403         VK = VK_XValue;
4404     }
4405   }
4406 
4407   // Perform default conversions.
4408   if (!LHSExp->getType()->getAs<VectorType>()) {
4409     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4410     if (Result.isInvalid())
4411       return ExprError();
4412     LHSExp = Result.get();
4413   }
4414   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4415   if (Result.isInvalid())
4416     return ExprError();
4417   RHSExp = Result.get();
4418 
4419   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4420 
4421   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4422   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4423   // in the subscript position. As a result, we need to derive the array base
4424   // and index from the expression types.
4425   Expr *BaseExpr, *IndexExpr;
4426   QualType ResultType;
4427   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4428     BaseExpr = LHSExp;
4429     IndexExpr = RHSExp;
4430     ResultType = Context.DependentTy;
4431   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4432     BaseExpr = LHSExp;
4433     IndexExpr = RHSExp;
4434     ResultType = PTy->getPointeeType();
4435   } else if (const ObjCObjectPointerType *PTy =
4436                LHSTy->getAs<ObjCObjectPointerType>()) {
4437     BaseExpr = LHSExp;
4438     IndexExpr = RHSExp;
4439 
4440     // Use custom logic if this should be the pseudo-object subscript
4441     // expression.
4442     if (!LangOpts.isSubscriptPointerArithmetic())
4443       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4444                                           nullptr);
4445 
4446     ResultType = PTy->getPointeeType();
4447   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4448      // Handle the uncommon case of "123[Ptr]".
4449     BaseExpr = RHSExp;
4450     IndexExpr = LHSExp;
4451     ResultType = PTy->getPointeeType();
4452   } else if (const ObjCObjectPointerType *PTy =
4453                RHSTy->getAs<ObjCObjectPointerType>()) {
4454      // Handle the uncommon case of "123[Ptr]".
4455     BaseExpr = RHSExp;
4456     IndexExpr = LHSExp;
4457     ResultType = PTy->getPointeeType();
4458     if (!LangOpts.isSubscriptPointerArithmetic()) {
4459       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4460         << ResultType << BaseExpr->getSourceRange();
4461       return ExprError();
4462     }
4463   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4464     BaseExpr = LHSExp;    // vectors: V[123]
4465     IndexExpr = RHSExp;
4466     // We apply C++ DR1213 to vector subscripting too.
4467     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4468       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4469       if (Materialized.isInvalid())
4470         return ExprError();
4471       LHSExp = Materialized.get();
4472     }
4473     VK = LHSExp->getValueKind();
4474     if (VK != VK_RValue)
4475       OK = OK_VectorComponent;
4476 
4477     ResultType = VTy->getElementType();
4478     QualType BaseType = BaseExpr->getType();
4479     Qualifiers BaseQuals = BaseType.getQualifiers();
4480     Qualifiers MemberQuals = ResultType.getQualifiers();
4481     Qualifiers Combined = BaseQuals + MemberQuals;
4482     if (Combined != MemberQuals)
4483       ResultType = Context.getQualifiedType(ResultType, Combined);
4484   } else if (LHSTy->isArrayType()) {
4485     // If we see an array that wasn't promoted by
4486     // DefaultFunctionArrayLvalueConversion, it must be an array that
4487     // wasn't promoted because of the C90 rule that doesn't
4488     // allow promoting non-lvalue arrays.  Warn, then
4489     // force the promotion here.
4490     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4491         LHSExp->getSourceRange();
4492     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4493                                CK_ArrayToPointerDecay).get();
4494     LHSTy = LHSExp->getType();
4495 
4496     BaseExpr = LHSExp;
4497     IndexExpr = RHSExp;
4498     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4499   } else if (RHSTy->isArrayType()) {
4500     // Same as previous, except for 123[f().a] case
4501     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4502         RHSExp->getSourceRange();
4503     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4504                                CK_ArrayToPointerDecay).get();
4505     RHSTy = RHSExp->getType();
4506 
4507     BaseExpr = RHSExp;
4508     IndexExpr = LHSExp;
4509     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4510   } else {
4511     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4512        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4513   }
4514   // C99 6.5.2.1p1
4515   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4516     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4517                      << IndexExpr->getSourceRange());
4518 
4519   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4520        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4521          && !IndexExpr->isTypeDependent())
4522     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4523 
4524   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4525   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4526   // type. Note that Functions are not objects, and that (in C99 parlance)
4527   // incomplete types are not object types.
4528   if (ResultType->isFunctionType()) {
4529     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4530       << ResultType << BaseExpr->getSourceRange();
4531     return ExprError();
4532   }
4533 
4534   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4535     // GNU extension: subscripting on pointer to void
4536     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4537       << BaseExpr->getSourceRange();
4538 
4539     // C forbids expressions of unqualified void type from being l-values.
4540     // See IsCForbiddenLValueType.
4541     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4542   } else if (!ResultType->isDependentType() &&
4543       RequireCompleteType(LLoc, ResultType,
4544                           diag::err_subscript_incomplete_type, BaseExpr))
4545     return ExprError();
4546 
4547   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4548          !ResultType.isCForbiddenLValueType());
4549 
4550   return new (Context)
4551       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4552 }
4553 
4554 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4555                                   ParmVarDecl *Param) {
4556   if (Param->hasUnparsedDefaultArg()) {
4557     Diag(CallLoc,
4558          diag::err_use_of_default_argument_to_function_declared_later) <<
4559       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4560     Diag(UnparsedDefaultArgLocs[Param],
4561          diag::note_default_argument_declared_here);
4562     return true;
4563   }
4564 
4565   if (Param->hasUninstantiatedDefaultArg()) {
4566     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4567 
4568     EnterExpressionEvaluationContext EvalContext(
4569         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4570 
4571     // Instantiate the expression.
4572     //
4573     // FIXME: Pass in a correct Pattern argument, otherwise
4574     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4575     //
4576     // template<typename T>
4577     // struct A {
4578     //   static int FooImpl();
4579     //
4580     //   template<typename Tp>
4581     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4582     //   // template argument list [[T], [Tp]], should be [[Tp]].
4583     //   friend A<Tp> Foo(int a);
4584     // };
4585     //
4586     // template<typename T>
4587     // A<T> Foo(int a = A<T>::FooImpl());
4588     MultiLevelTemplateArgumentList MutiLevelArgList
4589       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4590 
4591     InstantiatingTemplate Inst(*this, CallLoc, Param,
4592                                MutiLevelArgList.getInnermost());
4593     if (Inst.isInvalid())
4594       return true;
4595     if (Inst.isAlreadyInstantiating()) {
4596       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4597       Param->setInvalidDecl();
4598       return true;
4599     }
4600 
4601     ExprResult Result;
4602     {
4603       // C++ [dcl.fct.default]p5:
4604       //   The names in the [default argument] expression are bound, and
4605       //   the semantic constraints are checked, at the point where the
4606       //   default argument expression appears.
4607       ContextRAII SavedContext(*this, FD);
4608       LocalInstantiationScope Local(*this);
4609       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4610                                 /*DirectInit*/false);
4611     }
4612     if (Result.isInvalid())
4613       return true;
4614 
4615     // Check the expression as an initializer for the parameter.
4616     InitializedEntity Entity
4617       = InitializedEntity::InitializeParameter(Context, Param);
4618     InitializationKind Kind
4619       = InitializationKind::CreateCopy(Param->getLocation(),
4620              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4621     Expr *ResultE = Result.getAs<Expr>();
4622 
4623     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4624     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4625     if (Result.isInvalid())
4626       return true;
4627 
4628     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4629                                  Param->getOuterLocStart());
4630     if (Result.isInvalid())
4631       return true;
4632 
4633     // Remember the instantiated default argument.
4634     Param->setDefaultArg(Result.getAs<Expr>());
4635     if (ASTMutationListener *L = getASTMutationListener()) {
4636       L->DefaultArgumentInstantiated(Param);
4637     }
4638   }
4639 
4640   // If the default argument expression is not set yet, we are building it now.
4641   if (!Param->hasInit()) {
4642     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4643     Param->setInvalidDecl();
4644     return true;
4645   }
4646 
4647   // If the default expression creates temporaries, we need to
4648   // push them to the current stack of expression temporaries so they'll
4649   // be properly destroyed.
4650   // FIXME: We should really be rebuilding the default argument with new
4651   // bound temporaries; see the comment in PR5810.
4652   // We don't need to do that with block decls, though, because
4653   // blocks in default argument expression can never capture anything.
4654   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4655     // Set the "needs cleanups" bit regardless of whether there are
4656     // any explicit objects.
4657     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4658 
4659     // Append all the objects to the cleanup list.  Right now, this
4660     // should always be a no-op, because blocks in default argument
4661     // expressions should never be able to capture anything.
4662     assert(!Init->getNumObjects() &&
4663            "default argument expression has capturing blocks?");
4664   }
4665 
4666   // We already type-checked the argument, so we know it works.
4667   // Just mark all of the declarations in this potentially-evaluated expression
4668   // as being "referenced".
4669   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4670                                    /*SkipLocalVariables=*/true);
4671   return false;
4672 }
4673 
4674 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4675                                         FunctionDecl *FD, ParmVarDecl *Param) {
4676   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4677     return ExprError();
4678   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4679 }
4680 
4681 Sema::VariadicCallType
4682 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4683                           Expr *Fn) {
4684   if (Proto && Proto->isVariadic()) {
4685     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4686       return VariadicConstructor;
4687     else if (Fn && Fn->getType()->isBlockPointerType())
4688       return VariadicBlock;
4689     else if (FDecl) {
4690       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4691         if (Method->isInstance())
4692           return VariadicMethod;
4693     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4694       return VariadicMethod;
4695     return VariadicFunction;
4696   }
4697   return VariadicDoesNotApply;
4698 }
4699 
4700 namespace {
4701 class FunctionCallCCC : public FunctionCallFilterCCC {
4702 public:
4703   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4704                   unsigned NumArgs, MemberExpr *ME)
4705       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4706         FunctionName(FuncName) {}
4707 
4708   bool ValidateCandidate(const TypoCorrection &candidate) override {
4709     if (!candidate.getCorrectionSpecifier() ||
4710         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4711       return false;
4712     }
4713 
4714     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4715   }
4716 
4717 private:
4718   const IdentifierInfo *const FunctionName;
4719 };
4720 }
4721 
4722 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4723                                                FunctionDecl *FDecl,
4724                                                ArrayRef<Expr *> Args) {
4725   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4726   DeclarationName FuncName = FDecl->getDeclName();
4727   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4728 
4729   if (TypoCorrection Corrected = S.CorrectTypo(
4730           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4731           S.getScopeForContext(S.CurContext), nullptr,
4732           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4733                                              Args.size(), ME),
4734           Sema::CTK_ErrorRecovery)) {
4735     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4736       if (Corrected.isOverloaded()) {
4737         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4738         OverloadCandidateSet::iterator Best;
4739         for (NamedDecl *CD : Corrected) {
4740           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4741             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4742                                    OCS);
4743         }
4744         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4745         case OR_Success:
4746           ND = Best->FoundDecl;
4747           Corrected.setCorrectionDecl(ND);
4748           break;
4749         default:
4750           break;
4751         }
4752       }
4753       ND = ND->getUnderlyingDecl();
4754       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4755         return Corrected;
4756     }
4757   }
4758   return TypoCorrection();
4759 }
4760 
4761 /// ConvertArgumentsForCall - Converts the arguments specified in
4762 /// Args/NumArgs to the parameter types of the function FDecl with
4763 /// function prototype Proto. Call is the call expression itself, and
4764 /// Fn is the function expression. For a C++ member function, this
4765 /// routine does not attempt to convert the object argument. Returns
4766 /// true if the call is ill-formed.
4767 bool
4768 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4769                               FunctionDecl *FDecl,
4770                               const FunctionProtoType *Proto,
4771                               ArrayRef<Expr *> Args,
4772                               SourceLocation RParenLoc,
4773                               bool IsExecConfig) {
4774   // Bail out early if calling a builtin with custom typechecking.
4775   if (FDecl)
4776     if (unsigned ID = FDecl->getBuiltinID())
4777       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4778         return false;
4779 
4780   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4781   // assignment, to the types of the corresponding parameter, ...
4782   unsigned NumParams = Proto->getNumParams();
4783   bool Invalid = false;
4784   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4785   unsigned FnKind = Fn->getType()->isBlockPointerType()
4786                        ? 1 /* block */
4787                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4788                                        : 0 /* function */);
4789 
4790   // If too few arguments are available (and we don't have default
4791   // arguments for the remaining parameters), don't make the call.
4792   if (Args.size() < NumParams) {
4793     if (Args.size() < MinArgs) {
4794       TypoCorrection TC;
4795       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4796         unsigned diag_id =
4797             MinArgs == NumParams && !Proto->isVariadic()
4798                 ? diag::err_typecheck_call_too_few_args_suggest
4799                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4800         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4801                                         << static_cast<unsigned>(Args.size())
4802                                         << TC.getCorrectionRange());
4803       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4804         Diag(RParenLoc,
4805              MinArgs == NumParams && !Proto->isVariadic()
4806                  ? diag::err_typecheck_call_too_few_args_one
4807                  : diag::err_typecheck_call_too_few_args_at_least_one)
4808             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4809       else
4810         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4811                             ? diag::err_typecheck_call_too_few_args
4812                             : diag::err_typecheck_call_too_few_args_at_least)
4813             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4814             << Fn->getSourceRange();
4815 
4816       // Emit the location of the prototype.
4817       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4818         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4819           << FDecl;
4820 
4821       return true;
4822     }
4823     Call->setNumArgs(Context, NumParams);
4824   }
4825 
4826   // If too many are passed and not variadic, error on the extras and drop
4827   // them.
4828   if (Args.size() > NumParams) {
4829     if (!Proto->isVariadic()) {
4830       TypoCorrection TC;
4831       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4832         unsigned diag_id =
4833             MinArgs == NumParams && !Proto->isVariadic()
4834                 ? diag::err_typecheck_call_too_many_args_suggest
4835                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4836         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4837                                         << static_cast<unsigned>(Args.size())
4838                                         << TC.getCorrectionRange());
4839       } else if (NumParams == 1 && FDecl &&
4840                  FDecl->getParamDecl(0)->getDeclName())
4841         Diag(Args[NumParams]->getLocStart(),
4842              MinArgs == NumParams
4843                  ? diag::err_typecheck_call_too_many_args_one
4844                  : diag::err_typecheck_call_too_many_args_at_most_one)
4845             << FnKind << FDecl->getParamDecl(0)
4846             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4847             << SourceRange(Args[NumParams]->getLocStart(),
4848                            Args.back()->getLocEnd());
4849       else
4850         Diag(Args[NumParams]->getLocStart(),
4851              MinArgs == NumParams
4852                  ? diag::err_typecheck_call_too_many_args
4853                  : diag::err_typecheck_call_too_many_args_at_most)
4854             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4855             << Fn->getSourceRange()
4856             << SourceRange(Args[NumParams]->getLocStart(),
4857                            Args.back()->getLocEnd());
4858 
4859       // Emit the location of the prototype.
4860       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4861         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4862           << FDecl;
4863 
4864       // This deletes the extra arguments.
4865       Call->setNumArgs(Context, NumParams);
4866       return true;
4867     }
4868   }
4869   SmallVector<Expr *, 8> AllArgs;
4870   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4871 
4872   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4873                                    Proto, 0, Args, AllArgs, CallType);
4874   if (Invalid)
4875     return true;
4876   unsigned TotalNumArgs = AllArgs.size();
4877   for (unsigned i = 0; i < TotalNumArgs; ++i)
4878     Call->setArg(i, AllArgs[i]);
4879 
4880   return false;
4881 }
4882 
4883 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4884                                   const FunctionProtoType *Proto,
4885                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4886                                   SmallVectorImpl<Expr *> &AllArgs,
4887                                   VariadicCallType CallType, bool AllowExplicit,
4888                                   bool IsListInitialization) {
4889   unsigned NumParams = Proto->getNumParams();
4890   bool Invalid = false;
4891   size_t ArgIx = 0;
4892   // Continue to check argument types (even if we have too few/many args).
4893   for (unsigned i = FirstParam; i < NumParams; i++) {
4894     QualType ProtoArgType = Proto->getParamType(i);
4895 
4896     Expr *Arg;
4897     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4898     if (ArgIx < Args.size()) {
4899       Arg = Args[ArgIx++];
4900 
4901       if (RequireCompleteType(Arg->getLocStart(),
4902                               ProtoArgType,
4903                               diag::err_call_incomplete_argument, Arg))
4904         return true;
4905 
4906       // Strip the unbridged-cast placeholder expression off, if applicable.
4907       bool CFAudited = false;
4908       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4909           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4910           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4911         Arg = stripARCUnbridgedCast(Arg);
4912       else if (getLangOpts().ObjCAutoRefCount &&
4913                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4914                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4915         CFAudited = true;
4916 
4917       if (Proto->getExtParameterInfo(i).isNoEscape())
4918         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4919           BE->getBlockDecl()->setDoesNotEscape();
4920 
4921       InitializedEntity Entity =
4922           Param ? InitializedEntity::InitializeParameter(Context, Param,
4923                                                          ProtoArgType)
4924                 : InitializedEntity::InitializeParameter(
4925                       Context, ProtoArgType, Proto->isParamConsumed(i));
4926 
4927       // Remember that parameter belongs to a CF audited API.
4928       if (CFAudited)
4929         Entity.setParameterCFAudited();
4930 
4931       ExprResult ArgE = PerformCopyInitialization(
4932           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4933       if (ArgE.isInvalid())
4934         return true;
4935 
4936       Arg = ArgE.getAs<Expr>();
4937     } else {
4938       assert(Param && "can't use default arguments without a known callee");
4939 
4940       ExprResult ArgExpr =
4941         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4942       if (ArgExpr.isInvalid())
4943         return true;
4944 
4945       Arg = ArgExpr.getAs<Expr>();
4946     }
4947 
4948     // Check for array bounds violations for each argument to the call. This
4949     // check only triggers warnings when the argument isn't a more complex Expr
4950     // with its own checking, such as a BinaryOperator.
4951     CheckArrayAccess(Arg);
4952 
4953     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4954     CheckStaticArrayArgument(CallLoc, Param, Arg);
4955 
4956     AllArgs.push_back(Arg);
4957   }
4958 
4959   // If this is a variadic call, handle args passed through "...".
4960   if (CallType != VariadicDoesNotApply) {
4961     // Assume that extern "C" functions with variadic arguments that
4962     // return __unknown_anytype aren't *really* variadic.
4963     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4964         FDecl->isExternC()) {
4965       for (Expr *A : Args.slice(ArgIx)) {
4966         QualType paramType; // ignored
4967         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4968         Invalid |= arg.isInvalid();
4969         AllArgs.push_back(arg.get());
4970       }
4971 
4972     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4973     } else {
4974       for (Expr *A : Args.slice(ArgIx)) {
4975         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4976         Invalid |= Arg.isInvalid();
4977         AllArgs.push_back(Arg.get());
4978       }
4979     }
4980 
4981     // Check for array bounds violations.
4982     for (Expr *A : Args.slice(ArgIx))
4983       CheckArrayAccess(A);
4984   }
4985   return Invalid;
4986 }
4987 
4988 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4989   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4990   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4991     TL = DTL.getOriginalLoc();
4992   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4993     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4994       << ATL.getLocalSourceRange();
4995 }
4996 
4997 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4998 /// array parameter, check that it is non-null, and that if it is formed by
4999 /// array-to-pointer decay, the underlying array is sufficiently large.
5000 ///
5001 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5002 /// array type derivation, then for each call to the function, the value of the
5003 /// corresponding actual argument shall provide access to the first element of
5004 /// an array with at least as many elements as specified by the size expression.
5005 void
5006 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5007                                ParmVarDecl *Param,
5008                                const Expr *ArgExpr) {
5009   // Static array parameters are not supported in C++.
5010   if (!Param || getLangOpts().CPlusPlus)
5011     return;
5012 
5013   QualType OrigTy = Param->getOriginalType();
5014 
5015   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5016   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5017     return;
5018 
5019   if (ArgExpr->isNullPointerConstant(Context,
5020                                      Expr::NPC_NeverValueDependent)) {
5021     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5022     DiagnoseCalleeStaticArrayParam(*this, Param);
5023     return;
5024   }
5025 
5026   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5027   if (!CAT)
5028     return;
5029 
5030   const ConstantArrayType *ArgCAT =
5031     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5032   if (!ArgCAT)
5033     return;
5034 
5035   if (ArgCAT->getSize().ult(CAT->getSize())) {
5036     Diag(CallLoc, diag::warn_static_array_too_small)
5037       << ArgExpr->getSourceRange()
5038       << (unsigned) ArgCAT->getSize().getZExtValue()
5039       << (unsigned) CAT->getSize().getZExtValue();
5040     DiagnoseCalleeStaticArrayParam(*this, Param);
5041   }
5042 }
5043 
5044 /// Given a function expression of unknown-any type, try to rebuild it
5045 /// to have a function type.
5046 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5047 
5048 /// Is the given type a placeholder that we need to lower out
5049 /// immediately during argument processing?
5050 static bool isPlaceholderToRemoveAsArg(QualType type) {
5051   // Placeholders are never sugared.
5052   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5053   if (!placeholder) return false;
5054 
5055   switch (placeholder->getKind()) {
5056   // Ignore all the non-placeholder types.
5057 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5058   case BuiltinType::Id:
5059 #include "clang/Basic/OpenCLImageTypes.def"
5060 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5061 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5062 #include "clang/AST/BuiltinTypes.def"
5063     return false;
5064 
5065   // We cannot lower out overload sets; they might validly be resolved
5066   // by the call machinery.
5067   case BuiltinType::Overload:
5068     return false;
5069 
5070   // Unbridged casts in ARC can be handled in some call positions and
5071   // should be left in place.
5072   case BuiltinType::ARCUnbridgedCast:
5073     return false;
5074 
5075   // Pseudo-objects should be converted as soon as possible.
5076   case BuiltinType::PseudoObject:
5077     return true;
5078 
5079   // The debugger mode could theoretically but currently does not try
5080   // to resolve unknown-typed arguments based on known parameter types.
5081   case BuiltinType::UnknownAny:
5082     return true;
5083 
5084   // These are always invalid as call arguments and should be reported.
5085   case BuiltinType::BoundMember:
5086   case BuiltinType::BuiltinFn:
5087   case BuiltinType::OMPArraySection:
5088     return true;
5089 
5090   }
5091   llvm_unreachable("bad builtin type kind");
5092 }
5093 
5094 /// Check an argument list for placeholders that we won't try to
5095 /// handle later.
5096 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5097   // Apply this processing to all the arguments at once instead of
5098   // dying at the first failure.
5099   bool hasInvalid = false;
5100   for (size_t i = 0, e = args.size(); i != e; i++) {
5101     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5102       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5103       if (result.isInvalid()) hasInvalid = true;
5104       else args[i] = result.get();
5105     } else if (hasInvalid) {
5106       (void)S.CorrectDelayedTyposInExpr(args[i]);
5107     }
5108   }
5109   return hasInvalid;
5110 }
5111 
5112 /// If a builtin function has a pointer argument with no explicit address
5113 /// space, then it should be able to accept a pointer to any address
5114 /// space as input.  In order to do this, we need to replace the
5115 /// standard builtin declaration with one that uses the same address space
5116 /// as the call.
5117 ///
5118 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5119 ///                  it does not contain any pointer arguments without
5120 ///                  an address space qualifer.  Otherwise the rewritten
5121 ///                  FunctionDecl is returned.
5122 /// TODO: Handle pointer return types.
5123 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5124                                                 const FunctionDecl *FDecl,
5125                                                 MultiExprArg ArgExprs) {
5126 
5127   QualType DeclType = FDecl->getType();
5128   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5129 
5130   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5131       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5132     return nullptr;
5133 
5134   bool NeedsNewDecl = false;
5135   unsigned i = 0;
5136   SmallVector<QualType, 8> OverloadParams;
5137 
5138   for (QualType ParamType : FT->param_types()) {
5139 
5140     // Convert array arguments to pointer to simplify type lookup.
5141     ExprResult ArgRes =
5142         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5143     if (ArgRes.isInvalid())
5144       return nullptr;
5145     Expr *Arg = ArgRes.get();
5146     QualType ArgType = Arg->getType();
5147     if (!ParamType->isPointerType() ||
5148         ParamType.getQualifiers().hasAddressSpace() ||
5149         !ArgType->isPointerType() ||
5150         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5151       OverloadParams.push_back(ParamType);
5152       continue;
5153     }
5154 
5155     QualType PointeeType = ParamType->getPointeeType();
5156     if (PointeeType.getQualifiers().hasAddressSpace())
5157       continue;
5158 
5159     NeedsNewDecl = true;
5160     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5161 
5162     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5163     OverloadParams.push_back(Context.getPointerType(PointeeType));
5164   }
5165 
5166   if (!NeedsNewDecl)
5167     return nullptr;
5168 
5169   FunctionProtoType::ExtProtoInfo EPI;
5170   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5171                                                 OverloadParams, EPI);
5172   DeclContext *Parent = Context.getTranslationUnitDecl();
5173   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5174                                                     FDecl->getLocation(),
5175                                                     FDecl->getLocation(),
5176                                                     FDecl->getIdentifier(),
5177                                                     OverloadTy,
5178                                                     /*TInfo=*/nullptr,
5179                                                     SC_Extern, false,
5180                                                     /*hasPrototype=*/true);
5181   SmallVector<ParmVarDecl*, 16> Params;
5182   FT = cast<FunctionProtoType>(OverloadTy);
5183   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5184     QualType ParamType = FT->getParamType(i);
5185     ParmVarDecl *Parm =
5186         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5187                                 SourceLocation(), nullptr, ParamType,
5188                                 /*TInfo=*/nullptr, SC_None, nullptr);
5189     Parm->setScopeInfo(0, i);
5190     Params.push_back(Parm);
5191   }
5192   OverloadDecl->setParams(Params);
5193   return OverloadDecl;
5194 }
5195 
5196 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5197                                     FunctionDecl *Callee,
5198                                     MultiExprArg ArgExprs) {
5199   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5200   // similar attributes) really don't like it when functions are called with an
5201   // invalid number of args.
5202   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5203                          /*PartialOverloading=*/false) &&
5204       !Callee->isVariadic())
5205     return;
5206   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5207     return;
5208 
5209   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5210     S.Diag(Fn->getLocStart(),
5211            isa<CXXMethodDecl>(Callee)
5212                ? diag::err_ovl_no_viable_member_function_in_call
5213                : diag::err_ovl_no_viable_function_in_call)
5214         << Callee << Callee->getSourceRange();
5215     S.Diag(Callee->getLocation(),
5216            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5217         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5218     return;
5219   }
5220 }
5221 
5222 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5223     const UnresolvedMemberExpr *const UME, Sema &S) {
5224 
5225   const auto GetFunctionLevelDCIfCXXClass =
5226       [](Sema &S) -> const CXXRecordDecl * {
5227     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5228     if (!DC || !DC->getParent())
5229       return nullptr;
5230 
5231     // If the call to some member function was made from within a member
5232     // function body 'M' return return 'M's parent.
5233     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5234       return MD->getParent()->getCanonicalDecl();
5235     // else the call was made from within a default member initializer of a
5236     // class, so return the class.
5237     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5238       return RD->getCanonicalDecl();
5239     return nullptr;
5240   };
5241   // If our DeclContext is neither a member function nor a class (in the
5242   // case of a lambda in a default member initializer), we can't have an
5243   // enclosing 'this'.
5244 
5245   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5246   if (!CurParentClass)
5247     return false;
5248 
5249   // The naming class for implicit member functions call is the class in which
5250   // name lookup starts.
5251   const CXXRecordDecl *const NamingClass =
5252       UME->getNamingClass()->getCanonicalDecl();
5253   assert(NamingClass && "Must have naming class even for implicit access");
5254 
5255   // If the unresolved member functions were found in a 'naming class' that is
5256   // related (either the same or derived from) to the class that contains the
5257   // member function that itself contained the implicit member access.
5258 
5259   return CurParentClass == NamingClass ||
5260          CurParentClass->isDerivedFrom(NamingClass);
5261 }
5262 
5263 static void
5264 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5265     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5266 
5267   if (!UME)
5268     return;
5269 
5270   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5271   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5272   // already been captured, or if this is an implicit member function call (if
5273   // it isn't, an attempt to capture 'this' should already have been made).
5274   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5275       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5276     return;
5277 
5278   // Check if the naming class in which the unresolved members were found is
5279   // related (same as or is a base of) to the enclosing class.
5280 
5281   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5282     return;
5283 
5284 
5285   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5286   // If the enclosing function is not dependent, then this lambda is
5287   // capture ready, so if we can capture this, do so.
5288   if (!EnclosingFunctionCtx->isDependentContext()) {
5289     // If the current lambda and all enclosing lambdas can capture 'this' -
5290     // then go ahead and capture 'this' (since our unresolved overload set
5291     // contains at least one non-static member function).
5292     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5293       S.CheckCXXThisCapture(CallLoc);
5294   } else if (S.CurContext->isDependentContext()) {
5295     // ... since this is an implicit member reference, that might potentially
5296     // involve a 'this' capture, mark 'this' for potential capture in
5297     // enclosing lambdas.
5298     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5299       CurLSI->addPotentialThisCapture(CallLoc);
5300   }
5301 }
5302 
5303 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5304 /// This provides the location of the left/right parens and a list of comma
5305 /// locations.
5306 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5307                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5308                                Expr *ExecConfig, bool IsExecConfig) {
5309   // Since this might be a postfix expression, get rid of ParenListExprs.
5310   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5311   if (Result.isInvalid()) return ExprError();
5312   Fn = Result.get();
5313 
5314   if (checkArgsForPlaceholders(*this, ArgExprs))
5315     return ExprError();
5316 
5317   if (getLangOpts().CPlusPlus) {
5318     // If this is a pseudo-destructor expression, build the call immediately.
5319     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5320       if (!ArgExprs.empty()) {
5321         // Pseudo-destructor calls should not have any arguments.
5322         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5323             << FixItHint::CreateRemoval(
5324                    SourceRange(ArgExprs.front()->getLocStart(),
5325                                ArgExprs.back()->getLocEnd()));
5326       }
5327 
5328       return new (Context)
5329           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5330     }
5331     if (Fn->getType() == Context.PseudoObjectTy) {
5332       ExprResult result = CheckPlaceholderExpr(Fn);
5333       if (result.isInvalid()) return ExprError();
5334       Fn = result.get();
5335     }
5336 
5337     // Determine whether this is a dependent call inside a C++ template,
5338     // in which case we won't do any semantic analysis now.
5339     bool Dependent = false;
5340     if (Fn->isTypeDependent())
5341       Dependent = true;
5342     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5343       Dependent = true;
5344 
5345     if (Dependent) {
5346       if (ExecConfig) {
5347         return new (Context) CUDAKernelCallExpr(
5348             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5349             Context.DependentTy, VK_RValue, RParenLoc);
5350       } else {
5351 
5352        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5353             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5354             Fn->getLocStart());
5355 
5356         return new (Context) CallExpr(
5357             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5358       }
5359     }
5360 
5361     // Determine whether this is a call to an object (C++ [over.call.object]).
5362     if (Fn->getType()->isRecordType())
5363       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5364                                           RParenLoc);
5365 
5366     if (Fn->getType() == Context.UnknownAnyTy) {
5367       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5368       if (result.isInvalid()) return ExprError();
5369       Fn = result.get();
5370     }
5371 
5372     if (Fn->getType() == Context.BoundMemberTy) {
5373       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5374                                        RParenLoc);
5375     }
5376   }
5377 
5378   // Check for overloaded calls.  This can happen even in C due to extensions.
5379   if (Fn->getType() == Context.OverloadTy) {
5380     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5381 
5382     // We aren't supposed to apply this logic if there's an '&' involved.
5383     if (!find.HasFormOfMemberPointer) {
5384       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5385         return new (Context) CallExpr(
5386             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5387       OverloadExpr *ovl = find.Expression;
5388       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5389         return BuildOverloadedCallExpr(
5390             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5391             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5392       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5393                                        RParenLoc);
5394     }
5395   }
5396 
5397   // If we're directly calling a function, get the appropriate declaration.
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   Expr *NakedFn = Fn->IgnoreParens();
5405 
5406   bool CallingNDeclIndirectly = false;
5407   NamedDecl *NDecl = nullptr;
5408   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5409     if (UnOp->getOpcode() == UO_AddrOf) {
5410       CallingNDeclIndirectly = true;
5411       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5412     }
5413   }
5414 
5415   if (isa<DeclRefExpr>(NakedFn)) {
5416     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5417 
5418     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5419     if (FDecl && FDecl->getBuiltinID()) {
5420       // Rewrite the function decl for this builtin by replacing parameters
5421       // with no explicit address space with the address space of the arguments
5422       // in ArgExprs.
5423       if ((FDecl =
5424                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5425         NDecl = FDecl;
5426         Fn = DeclRefExpr::Create(
5427             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5428             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5429       }
5430     }
5431   } else if (isa<MemberExpr>(NakedFn))
5432     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5433 
5434   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5435     if (CallingNDeclIndirectly &&
5436         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5437                                            Fn->getLocStart()))
5438       return ExprError();
5439 
5440     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5441       return ExprError();
5442 
5443     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5444   }
5445 
5446   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5447                                ExecConfig, IsExecConfig);
5448 }
5449 
5450 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5451 ///
5452 /// __builtin_astype( value, dst type )
5453 ///
5454 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5455                                  SourceLocation BuiltinLoc,
5456                                  SourceLocation RParenLoc) {
5457   ExprValueKind VK = VK_RValue;
5458   ExprObjectKind OK = OK_Ordinary;
5459   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5460   QualType SrcTy = E->getType();
5461   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5462     return ExprError(Diag(BuiltinLoc,
5463                           diag::err_invalid_astype_of_different_size)
5464                      << DstTy
5465                      << SrcTy
5466                      << E->getSourceRange());
5467   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5468 }
5469 
5470 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5471 /// provided arguments.
5472 ///
5473 /// __builtin_convertvector( value, dst type )
5474 ///
5475 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5476                                         SourceLocation BuiltinLoc,
5477                                         SourceLocation RParenLoc) {
5478   TypeSourceInfo *TInfo;
5479   GetTypeFromParser(ParsedDestTy, &TInfo);
5480   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5481 }
5482 
5483 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5484 /// i.e. an expression not of \p OverloadTy.  The expression should
5485 /// unary-convert to an expression of function-pointer or
5486 /// block-pointer type.
5487 ///
5488 /// \param NDecl the declaration being called, if available
5489 ExprResult
5490 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5491                             SourceLocation LParenLoc,
5492                             ArrayRef<Expr *> Args,
5493                             SourceLocation RParenLoc,
5494                             Expr *Config, bool IsExecConfig) {
5495   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5496   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5497 
5498   // Functions with 'interrupt' attribute cannot be called directly.
5499   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5500     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5501     return ExprError();
5502   }
5503 
5504   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5505   // so there's some risk when calling out to non-interrupt handler functions
5506   // that the callee might not preserve them. This is easy to diagnose here,
5507   // but can be very challenging to debug.
5508   if (auto *Caller = getCurFunctionDecl())
5509     if (Caller->hasAttr<ARMInterruptAttr>()) {
5510       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5511       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5512         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5513     }
5514 
5515   // Promote the function operand.
5516   // We special-case function promotion here because we only allow promoting
5517   // builtin functions to function pointers in the callee of a call.
5518   ExprResult Result;
5519   if (BuiltinID &&
5520       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5521     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5522                                CK_BuiltinFnToFnPtr).get();
5523   } else {
5524     Result = CallExprUnaryConversions(Fn);
5525   }
5526   if (Result.isInvalid())
5527     return ExprError();
5528   Fn = Result.get();
5529 
5530   // Make the call expr early, before semantic checks.  This guarantees cleanup
5531   // of arguments and function on error.
5532   CallExpr *TheCall;
5533   if (Config)
5534     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5535                                                cast<CallExpr>(Config), Args,
5536                                                Context.BoolTy, VK_RValue,
5537                                                RParenLoc);
5538   else
5539     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5540                                      VK_RValue, RParenLoc);
5541 
5542   if (!getLangOpts().CPlusPlus) {
5543     // C cannot always handle TypoExpr nodes in builtin calls and direct
5544     // function calls as their argument checking don't necessarily handle
5545     // dependent types properly, so make sure any TypoExprs have been
5546     // dealt with.
5547     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5548     if (!Result.isUsable()) return ExprError();
5549     TheCall = dyn_cast<CallExpr>(Result.get());
5550     if (!TheCall) return Result;
5551     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5552   }
5553 
5554   // Bail out early if calling a builtin with custom typechecking.
5555   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5556     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5557 
5558  retry:
5559   const FunctionType *FuncT;
5560   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5561     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5562     // have type pointer to function".
5563     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5564     if (!FuncT)
5565       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5566                          << Fn->getType() << Fn->getSourceRange());
5567   } else if (const BlockPointerType *BPT =
5568                Fn->getType()->getAs<BlockPointerType>()) {
5569     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5570   } else {
5571     // Handle calls to expressions of unknown-any type.
5572     if (Fn->getType() == Context.UnknownAnyTy) {
5573       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5574       if (rewrite.isInvalid()) return ExprError();
5575       Fn = rewrite.get();
5576       TheCall->setCallee(Fn);
5577       goto retry;
5578     }
5579 
5580     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5581       << Fn->getType() << Fn->getSourceRange());
5582   }
5583 
5584   if (getLangOpts().CUDA) {
5585     if (Config) {
5586       // CUDA: Kernel calls must be to global functions
5587       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5588         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5589             << FDecl << Fn->getSourceRange());
5590 
5591       // CUDA: Kernel function must have 'void' return type
5592       if (!FuncT->getReturnType()->isVoidType())
5593         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5594             << Fn->getType() << Fn->getSourceRange());
5595     } else {
5596       // CUDA: Calls to global functions must be configured
5597       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5598         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5599             << FDecl << Fn->getSourceRange());
5600     }
5601   }
5602 
5603   // Check for a valid return type
5604   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5605                           FDecl))
5606     return ExprError();
5607 
5608   // We know the result type of the call, set it.
5609   TheCall->setType(FuncT->getCallResultType(Context));
5610   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5611 
5612   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5613   if (Proto) {
5614     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5615                                 IsExecConfig))
5616       return ExprError();
5617   } else {
5618     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5619 
5620     if (FDecl) {
5621       // Check if we have too few/too many template arguments, based
5622       // on our knowledge of the function definition.
5623       const FunctionDecl *Def = nullptr;
5624       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5625         Proto = Def->getType()->getAs<FunctionProtoType>();
5626        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5627           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5628           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5629       }
5630 
5631       // If the function we're calling isn't a function prototype, but we have
5632       // a function prototype from a prior declaratiom, use that prototype.
5633       if (!FDecl->hasPrototype())
5634         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5635     }
5636 
5637     // Promote the arguments (C99 6.5.2.2p6).
5638     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5639       Expr *Arg = Args[i];
5640 
5641       if (Proto && i < Proto->getNumParams()) {
5642         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5643             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5644         ExprResult ArgE =
5645             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5646         if (ArgE.isInvalid())
5647           return true;
5648 
5649         Arg = ArgE.getAs<Expr>();
5650 
5651       } else {
5652         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5653 
5654         if (ArgE.isInvalid())
5655           return true;
5656 
5657         Arg = ArgE.getAs<Expr>();
5658       }
5659 
5660       if (RequireCompleteType(Arg->getLocStart(),
5661                               Arg->getType(),
5662                               diag::err_call_incomplete_argument, Arg))
5663         return ExprError();
5664 
5665       TheCall->setArg(i, Arg);
5666     }
5667   }
5668 
5669   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5670     if (!Method->isStatic())
5671       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5672         << Fn->getSourceRange());
5673 
5674   // Check for sentinels
5675   if (NDecl)
5676     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5677 
5678   // Do special checking on direct calls to functions.
5679   if (FDecl) {
5680     if (CheckFunctionCall(FDecl, TheCall, Proto))
5681       return ExprError();
5682 
5683     if (BuiltinID)
5684       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5685   } else if (NDecl) {
5686     if (CheckPointerCall(NDecl, TheCall, Proto))
5687       return ExprError();
5688   } else {
5689     if (CheckOtherCall(TheCall, Proto))
5690       return ExprError();
5691   }
5692 
5693   return MaybeBindToTemporary(TheCall);
5694 }
5695 
5696 ExprResult
5697 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5698                            SourceLocation RParenLoc, Expr *InitExpr) {
5699   assert(Ty && "ActOnCompoundLiteral(): missing type");
5700   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5701 
5702   TypeSourceInfo *TInfo;
5703   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5704   if (!TInfo)
5705     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5706 
5707   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5708 }
5709 
5710 ExprResult
5711 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5712                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5713   QualType literalType = TInfo->getType();
5714 
5715   if (literalType->isArrayType()) {
5716     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5717           diag::err_illegal_decl_array_incomplete_type,
5718           SourceRange(LParenLoc,
5719                       LiteralExpr->getSourceRange().getEnd())))
5720       return ExprError();
5721     if (literalType->isVariableArrayType())
5722       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5723         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5724   } else if (!literalType->isDependentType() &&
5725              RequireCompleteType(LParenLoc, literalType,
5726                diag::err_typecheck_decl_incomplete_type,
5727                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5728     return ExprError();
5729 
5730   InitializedEntity Entity
5731     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5732   InitializationKind Kind
5733     = InitializationKind::CreateCStyleCast(LParenLoc,
5734                                            SourceRange(LParenLoc, RParenLoc),
5735                                            /*InitList=*/true);
5736   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5737   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5738                                       &literalType);
5739   if (Result.isInvalid())
5740     return ExprError();
5741   LiteralExpr = Result.get();
5742 
5743   bool isFileScope = !CurContext->isFunctionOrMethod();
5744   if (isFileScope &&
5745       !LiteralExpr->isTypeDependent() &&
5746       !LiteralExpr->isValueDependent() &&
5747       !literalType->isDependentType()) { // 6.5.2.5p3
5748     if (CheckForConstantInitializer(LiteralExpr, literalType))
5749       return ExprError();
5750   }
5751 
5752   // In C, compound literals are l-values for some reason.
5753   // For GCC compatibility, in C++, file-scope array compound literals with
5754   // constant initializers are also l-values, and compound literals are
5755   // otherwise prvalues.
5756   //
5757   // (GCC also treats C++ list-initialized file-scope array prvalues with
5758   // constant initializers as l-values, but that's non-conforming, so we don't
5759   // follow it there.)
5760   //
5761   // FIXME: It would be better to handle the lvalue cases as materializing and
5762   // lifetime-extending a temporary object, but our materialized temporaries
5763   // representation only supports lifetime extension from a variable, not "out
5764   // of thin air".
5765   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5766   // is bound to the result of applying array-to-pointer decay to the compound
5767   // literal.
5768   // FIXME: GCC supports compound literals of reference type, which should
5769   // obviously have a value kind derived from the kind of reference involved.
5770   ExprValueKind VK =
5771       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5772           ? VK_RValue
5773           : VK_LValue;
5774 
5775   return MaybeBindToTemporary(
5776       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5777                                         VK, LiteralExpr, isFileScope));
5778 }
5779 
5780 ExprResult
5781 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5782                     SourceLocation RBraceLoc) {
5783   // Immediately handle non-overload placeholders.  Overloads can be
5784   // resolved contextually, but everything else here can't.
5785   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5786     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5787       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5788 
5789       // Ignore failures; dropping the entire initializer list because
5790       // of one failure would be terrible for indexing/etc.
5791       if (result.isInvalid()) continue;
5792 
5793       InitArgList[I] = result.get();
5794     }
5795   }
5796 
5797   // Semantic analysis for initializers is done by ActOnDeclarator() and
5798   // CheckInitializer() - it requires knowledge of the object being initialized.
5799 
5800   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5801                                                RBraceLoc);
5802   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5803   return E;
5804 }
5805 
5806 /// Do an explicit extend of the given block pointer if we're in ARC.
5807 void Sema::maybeExtendBlockObject(ExprResult &E) {
5808   assert(E.get()->getType()->isBlockPointerType());
5809   assert(E.get()->isRValue());
5810 
5811   // Only do this in an r-value context.
5812   if (!getLangOpts().ObjCAutoRefCount) return;
5813 
5814   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5815                                CK_ARCExtendBlockObject, E.get(),
5816                                /*base path*/ nullptr, VK_RValue);
5817   Cleanup.setExprNeedsCleanups(true);
5818 }
5819 
5820 /// Prepare a conversion of the given expression to an ObjC object
5821 /// pointer type.
5822 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5823   QualType type = E.get()->getType();
5824   if (type->isObjCObjectPointerType()) {
5825     return CK_BitCast;
5826   } else if (type->isBlockPointerType()) {
5827     maybeExtendBlockObject(E);
5828     return CK_BlockPointerToObjCPointerCast;
5829   } else {
5830     assert(type->isPointerType());
5831     return CK_CPointerToObjCPointerCast;
5832   }
5833 }
5834 
5835 /// Prepares for a scalar cast, performing all the necessary stages
5836 /// except the final cast and returning the kind required.
5837 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5838   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5839   // Also, callers should have filtered out the invalid cases with
5840   // pointers.  Everything else should be possible.
5841 
5842   QualType SrcTy = Src.get()->getType();
5843   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5844     return CK_NoOp;
5845 
5846   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5847   case Type::STK_MemberPointer:
5848     llvm_unreachable("member pointer type in C");
5849 
5850   case Type::STK_CPointer:
5851   case Type::STK_BlockPointer:
5852   case Type::STK_ObjCObjectPointer:
5853     switch (DestTy->getScalarTypeKind()) {
5854     case Type::STK_CPointer: {
5855       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5856       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5857       if (SrcAS != DestAS)
5858         return CK_AddressSpaceConversion;
5859       return CK_BitCast;
5860     }
5861     case Type::STK_BlockPointer:
5862       return (SrcKind == Type::STK_BlockPointer
5863                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5864     case Type::STK_ObjCObjectPointer:
5865       if (SrcKind == Type::STK_ObjCObjectPointer)
5866         return CK_BitCast;
5867       if (SrcKind == Type::STK_CPointer)
5868         return CK_CPointerToObjCPointerCast;
5869       maybeExtendBlockObject(Src);
5870       return CK_BlockPointerToObjCPointerCast;
5871     case Type::STK_Bool:
5872       return CK_PointerToBoolean;
5873     case Type::STK_Integral:
5874       return CK_PointerToIntegral;
5875     case Type::STK_Floating:
5876     case Type::STK_FloatingComplex:
5877     case Type::STK_IntegralComplex:
5878     case Type::STK_MemberPointer:
5879       llvm_unreachable("illegal cast from pointer");
5880     }
5881     llvm_unreachable("Should have returned before this");
5882 
5883   case Type::STK_Bool: // casting from bool is like casting from an integer
5884   case Type::STK_Integral:
5885     switch (DestTy->getScalarTypeKind()) {
5886     case Type::STK_CPointer:
5887     case Type::STK_ObjCObjectPointer:
5888     case Type::STK_BlockPointer:
5889       if (Src.get()->isNullPointerConstant(Context,
5890                                            Expr::NPC_ValueDependentIsNull))
5891         return CK_NullToPointer;
5892       return CK_IntegralToPointer;
5893     case Type::STK_Bool:
5894       return CK_IntegralToBoolean;
5895     case Type::STK_Integral:
5896       return CK_IntegralCast;
5897     case Type::STK_Floating:
5898       return CK_IntegralToFloating;
5899     case Type::STK_IntegralComplex:
5900       Src = ImpCastExprToType(Src.get(),
5901                       DestTy->castAs<ComplexType>()->getElementType(),
5902                       CK_IntegralCast);
5903       return CK_IntegralRealToComplex;
5904     case Type::STK_FloatingComplex:
5905       Src = ImpCastExprToType(Src.get(),
5906                       DestTy->castAs<ComplexType>()->getElementType(),
5907                       CK_IntegralToFloating);
5908       return CK_FloatingRealToComplex;
5909     case Type::STK_MemberPointer:
5910       llvm_unreachable("member pointer type in C");
5911     }
5912     llvm_unreachable("Should have returned before this");
5913 
5914   case Type::STK_Floating:
5915     switch (DestTy->getScalarTypeKind()) {
5916     case Type::STK_Floating:
5917       return CK_FloatingCast;
5918     case Type::STK_Bool:
5919       return CK_FloatingToBoolean;
5920     case Type::STK_Integral:
5921       return CK_FloatingToIntegral;
5922     case Type::STK_FloatingComplex:
5923       Src = ImpCastExprToType(Src.get(),
5924                               DestTy->castAs<ComplexType>()->getElementType(),
5925                               CK_FloatingCast);
5926       return CK_FloatingRealToComplex;
5927     case Type::STK_IntegralComplex:
5928       Src = ImpCastExprToType(Src.get(),
5929                               DestTy->castAs<ComplexType>()->getElementType(),
5930                               CK_FloatingToIntegral);
5931       return CK_IntegralRealToComplex;
5932     case Type::STK_CPointer:
5933     case Type::STK_ObjCObjectPointer:
5934     case Type::STK_BlockPointer:
5935       llvm_unreachable("valid float->pointer cast?");
5936     case Type::STK_MemberPointer:
5937       llvm_unreachable("member pointer type in C");
5938     }
5939     llvm_unreachable("Should have returned before this");
5940 
5941   case Type::STK_FloatingComplex:
5942     switch (DestTy->getScalarTypeKind()) {
5943     case Type::STK_FloatingComplex:
5944       return CK_FloatingComplexCast;
5945     case Type::STK_IntegralComplex:
5946       return CK_FloatingComplexToIntegralComplex;
5947     case Type::STK_Floating: {
5948       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5949       if (Context.hasSameType(ET, DestTy))
5950         return CK_FloatingComplexToReal;
5951       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5952       return CK_FloatingCast;
5953     }
5954     case Type::STK_Bool:
5955       return CK_FloatingComplexToBoolean;
5956     case Type::STK_Integral:
5957       Src = ImpCastExprToType(Src.get(),
5958                               SrcTy->castAs<ComplexType>()->getElementType(),
5959                               CK_FloatingComplexToReal);
5960       return CK_FloatingToIntegral;
5961     case Type::STK_CPointer:
5962     case Type::STK_ObjCObjectPointer:
5963     case Type::STK_BlockPointer:
5964       llvm_unreachable("valid complex float->pointer cast?");
5965     case Type::STK_MemberPointer:
5966       llvm_unreachable("member pointer type in C");
5967     }
5968     llvm_unreachable("Should have returned before this");
5969 
5970   case Type::STK_IntegralComplex:
5971     switch (DestTy->getScalarTypeKind()) {
5972     case Type::STK_FloatingComplex:
5973       return CK_IntegralComplexToFloatingComplex;
5974     case Type::STK_IntegralComplex:
5975       return CK_IntegralComplexCast;
5976     case Type::STK_Integral: {
5977       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5978       if (Context.hasSameType(ET, DestTy))
5979         return CK_IntegralComplexToReal;
5980       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5981       return CK_IntegralCast;
5982     }
5983     case Type::STK_Bool:
5984       return CK_IntegralComplexToBoolean;
5985     case Type::STK_Floating:
5986       Src = ImpCastExprToType(Src.get(),
5987                               SrcTy->castAs<ComplexType>()->getElementType(),
5988                               CK_IntegralComplexToReal);
5989       return CK_IntegralToFloating;
5990     case Type::STK_CPointer:
5991     case Type::STK_ObjCObjectPointer:
5992     case Type::STK_BlockPointer:
5993       llvm_unreachable("valid complex int->pointer cast?");
5994     case Type::STK_MemberPointer:
5995       llvm_unreachable("member pointer type in C");
5996     }
5997     llvm_unreachable("Should have returned before this");
5998   }
5999 
6000   llvm_unreachable("Unhandled scalar cast");
6001 }
6002 
6003 static bool breakDownVectorType(QualType type, uint64_t &len,
6004                                 QualType &eltType) {
6005   // Vectors are simple.
6006   if (const VectorType *vecType = type->getAs<VectorType>()) {
6007     len = vecType->getNumElements();
6008     eltType = vecType->getElementType();
6009     assert(eltType->isScalarType());
6010     return true;
6011   }
6012 
6013   // We allow lax conversion to and from non-vector types, but only if
6014   // they're real types (i.e. non-complex, non-pointer scalar types).
6015   if (!type->isRealType()) return false;
6016 
6017   len = 1;
6018   eltType = type;
6019   return true;
6020 }
6021 
6022 /// Are the two types lax-compatible vector types?  That is, given
6023 /// that one of them is a vector, do they have equal storage sizes,
6024 /// where the storage size is the number of elements times the element
6025 /// size?
6026 ///
6027 /// This will also return false if either of the types is neither a
6028 /// vector nor a real type.
6029 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6030   assert(destTy->isVectorType() || srcTy->isVectorType());
6031 
6032   // Disallow lax conversions between scalars and ExtVectors (these
6033   // conversions are allowed for other vector types because common headers
6034   // depend on them).  Most scalar OP ExtVector cases are handled by the
6035   // splat path anyway, which does what we want (convert, not bitcast).
6036   // What this rules out for ExtVectors is crazy things like char4*float.
6037   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6038   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6039 
6040   uint64_t srcLen, destLen;
6041   QualType srcEltTy, destEltTy;
6042   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6043   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6044 
6045   // ASTContext::getTypeSize will return the size rounded up to a
6046   // power of 2, so instead of using that, we need to use the raw
6047   // element size multiplied by the element count.
6048   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6049   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6050 
6051   return (srcLen * srcEltSize == destLen * destEltSize);
6052 }
6053 
6054 /// Is this a legal conversion between two types, one of which is
6055 /// known to be a vector type?
6056 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6057   assert(destTy->isVectorType() || srcTy->isVectorType());
6058 
6059   if (!Context.getLangOpts().LaxVectorConversions)
6060     return false;
6061   return areLaxCompatibleVectorTypes(srcTy, destTy);
6062 }
6063 
6064 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6065                            CastKind &Kind) {
6066   assert(VectorTy->isVectorType() && "Not a vector type!");
6067 
6068   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6069     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6070       return Diag(R.getBegin(),
6071                   Ty->isVectorType() ?
6072                   diag::err_invalid_conversion_between_vectors :
6073                   diag::err_invalid_conversion_between_vector_and_integer)
6074         << VectorTy << Ty << R;
6075   } else
6076     return Diag(R.getBegin(),
6077                 diag::err_invalid_conversion_between_vector_and_scalar)
6078       << VectorTy << Ty << R;
6079 
6080   Kind = CK_BitCast;
6081   return false;
6082 }
6083 
6084 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6085   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6086 
6087   if (DestElemTy == SplattedExpr->getType())
6088     return SplattedExpr;
6089 
6090   assert(DestElemTy->isFloatingType() ||
6091          DestElemTy->isIntegralOrEnumerationType());
6092 
6093   CastKind CK;
6094   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6095     // OpenCL requires that we convert `true` boolean expressions to -1, but
6096     // only when splatting vectors.
6097     if (DestElemTy->isFloatingType()) {
6098       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6099       // in two steps: boolean to signed integral, then to floating.
6100       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6101                                                  CK_BooleanToSignedIntegral);
6102       SplattedExpr = CastExprRes.get();
6103       CK = CK_IntegralToFloating;
6104     } else {
6105       CK = CK_BooleanToSignedIntegral;
6106     }
6107   } else {
6108     ExprResult CastExprRes = SplattedExpr;
6109     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6110     if (CastExprRes.isInvalid())
6111       return ExprError();
6112     SplattedExpr = CastExprRes.get();
6113   }
6114   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6115 }
6116 
6117 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6118                                     Expr *CastExpr, CastKind &Kind) {
6119   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6120 
6121   QualType SrcTy = CastExpr->getType();
6122 
6123   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6124   // an ExtVectorType.
6125   // In OpenCL, casts between vectors of different types are not allowed.
6126   // (See OpenCL 6.2).
6127   if (SrcTy->isVectorType()) {
6128     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6129         (getLangOpts().OpenCL &&
6130          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6131       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6132         << DestTy << SrcTy << R;
6133       return ExprError();
6134     }
6135     Kind = CK_BitCast;
6136     return CastExpr;
6137   }
6138 
6139   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6140   // conversion will take place first from scalar to elt type, and then
6141   // splat from elt type to vector.
6142   if (SrcTy->isPointerType())
6143     return Diag(R.getBegin(),
6144                 diag::err_invalid_conversion_between_vector_and_scalar)
6145       << DestTy << SrcTy << R;
6146 
6147   Kind = CK_VectorSplat;
6148   return prepareVectorSplat(DestTy, CastExpr);
6149 }
6150 
6151 ExprResult
6152 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6153                     Declarator &D, ParsedType &Ty,
6154                     SourceLocation RParenLoc, Expr *CastExpr) {
6155   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6156          "ActOnCastExpr(): missing type or expr");
6157 
6158   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6159   if (D.isInvalidType())
6160     return ExprError();
6161 
6162   if (getLangOpts().CPlusPlus) {
6163     // Check that there are no default arguments (C++ only).
6164     CheckExtraCXXDefaultArguments(D);
6165   } else {
6166     // Make sure any TypoExprs have been dealt with.
6167     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6168     if (!Res.isUsable())
6169       return ExprError();
6170     CastExpr = Res.get();
6171   }
6172 
6173   checkUnusedDeclAttributes(D);
6174 
6175   QualType castType = castTInfo->getType();
6176   Ty = CreateParsedType(castType, castTInfo);
6177 
6178   bool isVectorLiteral = false;
6179 
6180   // Check for an altivec or OpenCL literal,
6181   // i.e. all the elements are integer constants.
6182   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6183   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6184   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6185        && castType->isVectorType() && (PE || PLE)) {
6186     if (PLE && PLE->getNumExprs() == 0) {
6187       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6188       return ExprError();
6189     }
6190     if (PE || PLE->getNumExprs() == 1) {
6191       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6192       if (!E->getType()->isVectorType())
6193         isVectorLiteral = true;
6194     }
6195     else
6196       isVectorLiteral = true;
6197   }
6198 
6199   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6200   // then handle it as such.
6201   if (isVectorLiteral)
6202     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6203 
6204   // If the Expr being casted is a ParenListExpr, handle it specially.
6205   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6206   // sequence of BinOp comma operators.
6207   if (isa<ParenListExpr>(CastExpr)) {
6208     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6209     if (Result.isInvalid()) return ExprError();
6210     CastExpr = Result.get();
6211   }
6212 
6213   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6214       !getSourceManager().isInSystemMacro(LParenLoc))
6215     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6216 
6217   CheckTollFreeBridgeCast(castType, CastExpr);
6218 
6219   CheckObjCBridgeRelatedCast(castType, CastExpr);
6220 
6221   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6222 
6223   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6224 }
6225 
6226 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6227                                     SourceLocation RParenLoc, Expr *E,
6228                                     TypeSourceInfo *TInfo) {
6229   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6230          "Expected paren or paren list expression");
6231 
6232   Expr **exprs;
6233   unsigned numExprs;
6234   Expr *subExpr;
6235   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6236   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6237     LiteralLParenLoc = PE->getLParenLoc();
6238     LiteralRParenLoc = PE->getRParenLoc();
6239     exprs = PE->getExprs();
6240     numExprs = PE->getNumExprs();
6241   } else { // isa<ParenExpr> by assertion at function entrance
6242     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6243     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6244     subExpr = cast<ParenExpr>(E)->getSubExpr();
6245     exprs = &subExpr;
6246     numExprs = 1;
6247   }
6248 
6249   QualType Ty = TInfo->getType();
6250   assert(Ty->isVectorType() && "Expected vector type");
6251 
6252   SmallVector<Expr *, 8> initExprs;
6253   const VectorType *VTy = Ty->getAs<VectorType>();
6254   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6255 
6256   // '(...)' form of vector initialization in AltiVec: the number of
6257   // initializers must be one or must match the size of the vector.
6258   // If a single value is specified in the initializer then it will be
6259   // replicated to all the components of the vector
6260   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6261     // The number of initializers must be one or must match the size of the
6262     // vector. If a single value is specified in the initializer then it will
6263     // be replicated to all the components of the vector
6264     if (numExprs == 1) {
6265       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6266       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6267       if (Literal.isInvalid())
6268         return ExprError();
6269       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6270                                   PrepareScalarCast(Literal, ElemTy));
6271       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6272     }
6273     else if (numExprs < numElems) {
6274       Diag(E->getExprLoc(),
6275            diag::err_incorrect_number_of_vector_initializers);
6276       return ExprError();
6277     }
6278     else
6279       initExprs.append(exprs, exprs + numExprs);
6280   }
6281   else {
6282     // For OpenCL, when the number of initializers is a single value,
6283     // it will be replicated to all components of the vector.
6284     if (getLangOpts().OpenCL &&
6285         VTy->getVectorKind() == VectorType::GenericVector &&
6286         numExprs == 1) {
6287         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6288         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6289         if (Literal.isInvalid())
6290           return ExprError();
6291         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6292                                     PrepareScalarCast(Literal, ElemTy));
6293         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6294     }
6295 
6296     initExprs.append(exprs, exprs + numExprs);
6297   }
6298   // FIXME: This means that pretty-printing the final AST will produce curly
6299   // braces instead of the original commas.
6300   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6301                                                    initExprs, LiteralRParenLoc);
6302   initE->setType(Ty);
6303   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6304 }
6305 
6306 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6307 /// the ParenListExpr into a sequence of comma binary operators.
6308 ExprResult
6309 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6310   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6311   if (!E)
6312     return OrigExpr;
6313 
6314   ExprResult Result(E->getExpr(0));
6315 
6316   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6317     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6318                         E->getExpr(i));
6319 
6320   if (Result.isInvalid()) return ExprError();
6321 
6322   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6323 }
6324 
6325 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6326                                     SourceLocation R,
6327                                     MultiExprArg Val) {
6328   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6329   return expr;
6330 }
6331 
6332 /// Emit a specialized diagnostic when one expression is a null pointer
6333 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6334 /// emitted.
6335 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6336                                       SourceLocation QuestionLoc) {
6337   Expr *NullExpr = LHSExpr;
6338   Expr *NonPointerExpr = RHSExpr;
6339   Expr::NullPointerConstantKind NullKind =
6340       NullExpr->isNullPointerConstant(Context,
6341                                       Expr::NPC_ValueDependentIsNotNull);
6342 
6343   if (NullKind == Expr::NPCK_NotNull) {
6344     NullExpr = RHSExpr;
6345     NonPointerExpr = LHSExpr;
6346     NullKind =
6347         NullExpr->isNullPointerConstant(Context,
6348                                         Expr::NPC_ValueDependentIsNotNull);
6349   }
6350 
6351   if (NullKind == Expr::NPCK_NotNull)
6352     return false;
6353 
6354   if (NullKind == Expr::NPCK_ZeroExpression)
6355     return false;
6356 
6357   if (NullKind == Expr::NPCK_ZeroLiteral) {
6358     // In this case, check to make sure that we got here from a "NULL"
6359     // string in the source code.
6360     NullExpr = NullExpr->IgnoreParenImpCasts();
6361     SourceLocation loc = NullExpr->getExprLoc();
6362     if (!findMacroSpelling(loc, "NULL"))
6363       return false;
6364   }
6365 
6366   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6367   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6368       << NonPointerExpr->getType() << DiagType
6369       << NonPointerExpr->getSourceRange();
6370   return true;
6371 }
6372 
6373 /// Return false if the condition expression is valid, true otherwise.
6374 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6375   QualType CondTy = Cond->getType();
6376 
6377   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6378   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6379     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6380       << CondTy << Cond->getSourceRange();
6381     return true;
6382   }
6383 
6384   // C99 6.5.15p2
6385   if (CondTy->isScalarType()) return false;
6386 
6387   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6388     << CondTy << Cond->getSourceRange();
6389   return true;
6390 }
6391 
6392 /// Handle when one or both operands are void type.
6393 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6394                                          ExprResult &RHS) {
6395     Expr *LHSExpr = LHS.get();
6396     Expr *RHSExpr = RHS.get();
6397 
6398     if (!LHSExpr->getType()->isVoidType())
6399       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6400         << RHSExpr->getSourceRange();
6401     if (!RHSExpr->getType()->isVoidType())
6402       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6403         << LHSExpr->getSourceRange();
6404     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6405     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6406     return S.Context.VoidTy;
6407 }
6408 
6409 /// Return false if the NullExpr can be promoted to PointerTy,
6410 /// true otherwise.
6411 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6412                                         QualType PointerTy) {
6413   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6414       !NullExpr.get()->isNullPointerConstant(S.Context,
6415                                             Expr::NPC_ValueDependentIsNull))
6416     return true;
6417 
6418   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6419   return false;
6420 }
6421 
6422 /// Checks compatibility between two pointers and return the resulting
6423 /// type.
6424 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6425                                                      ExprResult &RHS,
6426                                                      SourceLocation Loc) {
6427   QualType LHSTy = LHS.get()->getType();
6428   QualType RHSTy = RHS.get()->getType();
6429 
6430   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6431     // Two identical pointers types are always compatible.
6432     return LHSTy;
6433   }
6434 
6435   QualType lhptee, rhptee;
6436 
6437   // Get the pointee types.
6438   bool IsBlockPointer = false;
6439   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6440     lhptee = LHSBTy->getPointeeType();
6441     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6442     IsBlockPointer = true;
6443   } else {
6444     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6445     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6446   }
6447 
6448   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6449   // differently qualified versions of compatible types, the result type is
6450   // a pointer to an appropriately qualified version of the composite
6451   // type.
6452 
6453   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6454   // clause doesn't make sense for our extensions. E.g. address space 2 should
6455   // be incompatible with address space 3: they may live on different devices or
6456   // anything.
6457   Qualifiers lhQual = lhptee.getQualifiers();
6458   Qualifiers rhQual = rhptee.getQualifiers();
6459 
6460   LangAS ResultAddrSpace = LangAS::Default;
6461   LangAS LAddrSpace = lhQual.getAddressSpace();
6462   LangAS RAddrSpace = rhQual.getAddressSpace();
6463 
6464   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6465   // spaces is disallowed.
6466   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6467     ResultAddrSpace = LAddrSpace;
6468   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6469     ResultAddrSpace = RAddrSpace;
6470   else {
6471     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6472         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6473         << RHS.get()->getSourceRange();
6474     return QualType();
6475   }
6476 
6477   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6478   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6479   lhQual.removeCVRQualifiers();
6480   rhQual.removeCVRQualifiers();
6481 
6482   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6483   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6484   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6485   // qual types are compatible iff
6486   //  * corresponded types are compatible
6487   //  * CVR qualifiers are equal
6488   //  * address spaces are equal
6489   // Thus for conditional operator we merge CVR and address space unqualified
6490   // pointees and if there is a composite type we return a pointer to it with
6491   // merged qualifiers.
6492   LHSCastKind =
6493       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6494   RHSCastKind =
6495       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6496   lhQual.removeAddressSpace();
6497   rhQual.removeAddressSpace();
6498 
6499   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6500   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6501 
6502   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6503 
6504   if (CompositeTy.isNull()) {
6505     // In this situation, we assume void* type. No especially good
6506     // reason, but this is what gcc does, and we do have to pick
6507     // to get a consistent AST.
6508     QualType incompatTy;
6509     incompatTy = S.Context.getPointerType(
6510         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6511     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6512     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6513 
6514     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6515     // for casts between types with incompatible address space qualifiers.
6516     // For the following code the compiler produces casts between global and
6517     // local address spaces of the corresponded innermost pointees:
6518     // local int *global *a;
6519     // global int *global *b;
6520     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6521     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6522         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6523         << RHS.get()->getSourceRange();
6524 
6525     return incompatTy;
6526   }
6527 
6528   // The pointer types are compatible.
6529   // In case of OpenCL ResultTy should have the address space qualifier
6530   // which is a superset of address spaces of both the 2nd and the 3rd
6531   // operands of the conditional operator.
6532   QualType ResultTy = [&, ResultAddrSpace]() {
6533     if (S.getLangOpts().OpenCL) {
6534       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6535       CompositeQuals.setAddressSpace(ResultAddrSpace);
6536       return S.Context
6537           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6538           .withCVRQualifiers(MergedCVRQual);
6539     }
6540     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6541   }();
6542   if (IsBlockPointer)
6543     ResultTy = S.Context.getBlockPointerType(ResultTy);
6544   else
6545     ResultTy = S.Context.getPointerType(ResultTy);
6546 
6547   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6548   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6549   return ResultTy;
6550 }
6551 
6552 /// Return the resulting type when the operands are both block pointers.
6553 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6554                                                           ExprResult &LHS,
6555                                                           ExprResult &RHS,
6556                                                           SourceLocation Loc) {
6557   QualType LHSTy = LHS.get()->getType();
6558   QualType RHSTy = RHS.get()->getType();
6559 
6560   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6561     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6562       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6563       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6564       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6565       return destType;
6566     }
6567     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6568       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6569       << RHS.get()->getSourceRange();
6570     return QualType();
6571   }
6572 
6573   // We have 2 block pointer types.
6574   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6575 }
6576 
6577 /// Return the resulting type when the operands are both pointers.
6578 static QualType
6579 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6580                                             ExprResult &RHS,
6581                                             SourceLocation Loc) {
6582   // get the pointer types
6583   QualType LHSTy = LHS.get()->getType();
6584   QualType RHSTy = RHS.get()->getType();
6585 
6586   // get the "pointed to" types
6587   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6588   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6589 
6590   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6591   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6592     // Figure out necessary qualifiers (C99 6.5.15p6)
6593     QualType destPointee
6594       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6595     QualType destType = S.Context.getPointerType(destPointee);
6596     // Add qualifiers if necessary.
6597     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6598     // Promote to void*.
6599     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6600     return destType;
6601   }
6602   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6603     QualType destPointee
6604       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6605     QualType destType = S.Context.getPointerType(destPointee);
6606     // Add qualifiers if necessary.
6607     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6608     // Promote to void*.
6609     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6610     return destType;
6611   }
6612 
6613   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6614 }
6615 
6616 /// Return false if the first expression is not an integer and the second
6617 /// expression is not a pointer, true otherwise.
6618 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6619                                         Expr* PointerExpr, SourceLocation Loc,
6620                                         bool IsIntFirstExpr) {
6621   if (!PointerExpr->getType()->isPointerType() ||
6622       !Int.get()->getType()->isIntegerType())
6623     return false;
6624 
6625   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6626   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6627 
6628   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6629     << Expr1->getType() << Expr2->getType()
6630     << Expr1->getSourceRange() << Expr2->getSourceRange();
6631   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6632                             CK_IntegralToPointer);
6633   return true;
6634 }
6635 
6636 /// Simple conversion between integer and floating point types.
6637 ///
6638 /// Used when handling the OpenCL conditional operator where the
6639 /// condition is a vector while the other operands are scalar.
6640 ///
6641 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6642 /// types are either integer or floating type. Between the two
6643 /// operands, the type with the higher rank is defined as the "result
6644 /// type". The other operand needs to be promoted to the same type. No
6645 /// other type promotion is allowed. We cannot use
6646 /// UsualArithmeticConversions() for this purpose, since it always
6647 /// promotes promotable types.
6648 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6649                                             ExprResult &RHS,
6650                                             SourceLocation QuestionLoc) {
6651   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6652   if (LHS.isInvalid())
6653     return QualType();
6654   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6655   if (RHS.isInvalid())
6656     return QualType();
6657 
6658   // For conversion purposes, we ignore any qualifiers.
6659   // For example, "const float" and "float" are equivalent.
6660   QualType LHSType =
6661     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6662   QualType RHSType =
6663     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6664 
6665   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6666     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6667       << LHSType << LHS.get()->getSourceRange();
6668     return QualType();
6669   }
6670 
6671   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6672     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6673       << RHSType << RHS.get()->getSourceRange();
6674     return QualType();
6675   }
6676 
6677   // If both types are identical, no conversion is needed.
6678   if (LHSType == RHSType)
6679     return LHSType;
6680 
6681   // Now handle "real" floating types (i.e. float, double, long double).
6682   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6683     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6684                                  /*IsCompAssign = */ false);
6685 
6686   // Finally, we have two differing integer types.
6687   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6688   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6689 }
6690 
6691 /// Convert scalar operands to a vector that matches the
6692 ///        condition in length.
6693 ///
6694 /// Used when handling the OpenCL conditional operator where the
6695 /// condition is a vector while the other operands are scalar.
6696 ///
6697 /// We first compute the "result type" for the scalar operands
6698 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6699 /// into a vector of that type where the length matches the condition
6700 /// vector type. s6.11.6 requires that the element types of the result
6701 /// and the condition must have the same number of bits.
6702 static QualType
6703 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6704                               QualType CondTy, SourceLocation QuestionLoc) {
6705   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6706   if (ResTy.isNull()) return QualType();
6707 
6708   const VectorType *CV = CondTy->getAs<VectorType>();
6709   assert(CV);
6710 
6711   // Determine the vector result type
6712   unsigned NumElements = CV->getNumElements();
6713   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6714 
6715   // Ensure that all types have the same number of bits
6716   if (S.Context.getTypeSize(CV->getElementType())
6717       != S.Context.getTypeSize(ResTy)) {
6718     // Since VectorTy is created internally, it does not pretty print
6719     // with an OpenCL name. Instead, we just print a description.
6720     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6721     SmallString<64> Str;
6722     llvm::raw_svector_ostream OS(Str);
6723     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6724     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6725       << CondTy << OS.str();
6726     return QualType();
6727   }
6728 
6729   // Convert operands to the vector result type
6730   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6731   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6732 
6733   return VectorTy;
6734 }
6735 
6736 /// Return false if this is a valid OpenCL condition vector
6737 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6738                                        SourceLocation QuestionLoc) {
6739   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6740   // integral type.
6741   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6742   assert(CondTy);
6743   QualType EleTy = CondTy->getElementType();
6744   if (EleTy->isIntegerType()) return false;
6745 
6746   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6747     << Cond->getType() << Cond->getSourceRange();
6748   return true;
6749 }
6750 
6751 /// Return false if the vector condition type and the vector
6752 ///        result type are compatible.
6753 ///
6754 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6755 /// number of elements, and their element types have the same number
6756 /// of bits.
6757 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6758                               SourceLocation QuestionLoc) {
6759   const VectorType *CV = CondTy->getAs<VectorType>();
6760   const VectorType *RV = VecResTy->getAs<VectorType>();
6761   assert(CV && RV);
6762 
6763   if (CV->getNumElements() != RV->getNumElements()) {
6764     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6765       << CondTy << VecResTy;
6766     return true;
6767   }
6768 
6769   QualType CVE = CV->getElementType();
6770   QualType RVE = RV->getElementType();
6771 
6772   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6773     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6774       << CondTy << VecResTy;
6775     return true;
6776   }
6777 
6778   return false;
6779 }
6780 
6781 /// Return the resulting type for the conditional operator in
6782 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6783 ///        s6.3.i) when the condition is a vector type.
6784 static QualType
6785 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6786                              ExprResult &LHS, ExprResult &RHS,
6787                              SourceLocation QuestionLoc) {
6788   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6789   if (Cond.isInvalid())
6790     return QualType();
6791   QualType CondTy = Cond.get()->getType();
6792 
6793   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6794     return QualType();
6795 
6796   // If either operand is a vector then find the vector type of the
6797   // result as specified in OpenCL v1.1 s6.3.i.
6798   if (LHS.get()->getType()->isVectorType() ||
6799       RHS.get()->getType()->isVectorType()) {
6800     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6801                                               /*isCompAssign*/false,
6802                                               /*AllowBothBool*/true,
6803                                               /*AllowBoolConversions*/false);
6804     if (VecResTy.isNull()) return QualType();
6805     // The result type must match the condition type as specified in
6806     // OpenCL v1.1 s6.11.6.
6807     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6808       return QualType();
6809     return VecResTy;
6810   }
6811 
6812   // Both operands are scalar.
6813   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6814 }
6815 
6816 /// Return true if the Expr is block type
6817 static bool checkBlockType(Sema &S, const Expr *E) {
6818   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6819     QualType Ty = CE->getCallee()->getType();
6820     if (Ty->isBlockPointerType()) {
6821       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6822       return true;
6823     }
6824   }
6825   return false;
6826 }
6827 
6828 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6829 /// In that case, LHS = cond.
6830 /// C99 6.5.15
6831 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6832                                         ExprResult &RHS, ExprValueKind &VK,
6833                                         ExprObjectKind &OK,
6834                                         SourceLocation QuestionLoc) {
6835 
6836   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6837   if (!LHSResult.isUsable()) return QualType();
6838   LHS = LHSResult;
6839 
6840   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6841   if (!RHSResult.isUsable()) return QualType();
6842   RHS = RHSResult;
6843 
6844   // C++ is sufficiently different to merit its own checker.
6845   if (getLangOpts().CPlusPlus)
6846     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6847 
6848   VK = VK_RValue;
6849   OK = OK_Ordinary;
6850 
6851   // The OpenCL operator with a vector condition is sufficiently
6852   // different to merit its own checker.
6853   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6854     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6855 
6856   // First, check the condition.
6857   Cond = UsualUnaryConversions(Cond.get());
6858   if (Cond.isInvalid())
6859     return QualType();
6860   if (checkCondition(*this, Cond.get(), QuestionLoc))
6861     return QualType();
6862 
6863   // Now check the two expressions.
6864   if (LHS.get()->getType()->isVectorType() ||
6865       RHS.get()->getType()->isVectorType())
6866     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6867                                /*AllowBothBool*/true,
6868                                /*AllowBoolConversions*/false);
6869 
6870   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6871   if (LHS.isInvalid() || RHS.isInvalid())
6872     return QualType();
6873 
6874   QualType LHSTy = LHS.get()->getType();
6875   QualType RHSTy = RHS.get()->getType();
6876 
6877   // Diagnose attempts to convert between __float128 and long double where
6878   // such conversions currently can't be handled.
6879   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6880     Diag(QuestionLoc,
6881          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6882       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6883     return QualType();
6884   }
6885 
6886   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6887   // selection operator (?:).
6888   if (getLangOpts().OpenCL &&
6889       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6890     return QualType();
6891   }
6892 
6893   // If both operands have arithmetic type, do the usual arithmetic conversions
6894   // to find a common type: C99 6.5.15p3,5.
6895   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6896     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6897     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6898 
6899     return ResTy;
6900   }
6901 
6902   // If both operands are the same structure or union type, the result is that
6903   // type.
6904   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6905     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6906       if (LHSRT->getDecl() == RHSRT->getDecl())
6907         // "If both the operands have structure or union type, the result has
6908         // that type."  This implies that CV qualifiers are dropped.
6909         return LHSTy.getUnqualifiedType();
6910     // FIXME: Type of conditional expression must be complete in C mode.
6911   }
6912 
6913   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6914   // The following || allows only one side to be void (a GCC-ism).
6915   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6916     return checkConditionalVoidType(*this, LHS, RHS);
6917   }
6918 
6919   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6920   // the type of the other operand."
6921   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6922   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6923 
6924   // All objective-c pointer type analysis is done here.
6925   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6926                                                         QuestionLoc);
6927   if (LHS.isInvalid() || RHS.isInvalid())
6928     return QualType();
6929   if (!compositeType.isNull())
6930     return compositeType;
6931 
6932 
6933   // Handle block pointer types.
6934   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6935     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6936                                                      QuestionLoc);
6937 
6938   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6939   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6940     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6941                                                        QuestionLoc);
6942 
6943   // GCC compatibility: soften pointer/integer mismatch.  Note that
6944   // null pointers have been filtered out by this point.
6945   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6946       /*isIntFirstExpr=*/true))
6947     return RHSTy;
6948   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6949       /*isIntFirstExpr=*/false))
6950     return LHSTy;
6951 
6952   // Emit a better diagnostic if one of the expressions is a null pointer
6953   // constant and the other is not a pointer type. In this case, the user most
6954   // likely forgot to take the address of the other expression.
6955   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6956     return QualType();
6957 
6958   // Otherwise, the operands are not compatible.
6959   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6960     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6961     << RHS.get()->getSourceRange();
6962   return QualType();
6963 }
6964 
6965 /// FindCompositeObjCPointerType - Helper method to find composite type of
6966 /// two objective-c pointer types of the two input expressions.
6967 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6968                                             SourceLocation QuestionLoc) {
6969   QualType LHSTy = LHS.get()->getType();
6970   QualType RHSTy = RHS.get()->getType();
6971 
6972   // Handle things like Class and struct objc_class*.  Here we case the result
6973   // to the pseudo-builtin, because that will be implicitly cast back to the
6974   // redefinition type if an attempt is made to access its fields.
6975   if (LHSTy->isObjCClassType() &&
6976       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6977     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6978     return LHSTy;
6979   }
6980   if (RHSTy->isObjCClassType() &&
6981       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6982     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6983     return RHSTy;
6984   }
6985   // And the same for struct objc_object* / id
6986   if (LHSTy->isObjCIdType() &&
6987       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6988     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6989     return LHSTy;
6990   }
6991   if (RHSTy->isObjCIdType() &&
6992       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6993     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6994     return RHSTy;
6995   }
6996   // And the same for struct objc_selector* / SEL
6997   if (Context.isObjCSelType(LHSTy) &&
6998       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6999     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7000     return LHSTy;
7001   }
7002   if (Context.isObjCSelType(RHSTy) &&
7003       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7004     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7005     return RHSTy;
7006   }
7007   // Check constraints for Objective-C object pointers types.
7008   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7009 
7010     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7011       // Two identical object pointer types are always compatible.
7012       return LHSTy;
7013     }
7014     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7015     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7016     QualType compositeType = LHSTy;
7017 
7018     // If both operands are interfaces and either operand can be
7019     // assigned to the other, use that type as the composite
7020     // type. This allows
7021     //   xxx ? (A*) a : (B*) b
7022     // where B is a subclass of A.
7023     //
7024     // Additionally, as for assignment, if either type is 'id'
7025     // allow silent coercion. Finally, if the types are
7026     // incompatible then make sure to use 'id' as the composite
7027     // type so the result is acceptable for sending messages to.
7028 
7029     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7030     // It could return the composite type.
7031     if (!(compositeType =
7032           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7033       // Nothing more to do.
7034     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7035       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7036     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7037       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7038     } else if ((LHSTy->isObjCQualifiedIdType() ||
7039                 RHSTy->isObjCQualifiedIdType()) &&
7040                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7041       // Need to handle "id<xx>" explicitly.
7042       // GCC allows qualified id and any Objective-C type to devolve to
7043       // id. Currently localizing to here until clear this should be
7044       // part of ObjCQualifiedIdTypesAreCompatible.
7045       compositeType = Context.getObjCIdType();
7046     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7047       compositeType = Context.getObjCIdType();
7048     } else {
7049       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7050       << LHSTy << RHSTy
7051       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7052       QualType incompatTy = Context.getObjCIdType();
7053       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7054       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7055       return incompatTy;
7056     }
7057     // The object pointer types are compatible.
7058     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7059     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7060     return compositeType;
7061   }
7062   // Check Objective-C object pointer types and 'void *'
7063   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7064     if (getLangOpts().ObjCAutoRefCount) {
7065       // ARC forbids the implicit conversion of object pointers to 'void *',
7066       // so these types are not compatible.
7067       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7068           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7069       LHS = RHS = true;
7070       return QualType();
7071     }
7072     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7073     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7074     QualType destPointee
7075     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7076     QualType destType = Context.getPointerType(destPointee);
7077     // Add qualifiers if necessary.
7078     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7079     // Promote to void*.
7080     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7081     return destType;
7082   }
7083   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7084     if (getLangOpts().ObjCAutoRefCount) {
7085       // ARC forbids the implicit conversion of object pointers to 'void *',
7086       // so these types are not compatible.
7087       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7088           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7089       LHS = RHS = true;
7090       return QualType();
7091     }
7092     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7093     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7094     QualType destPointee
7095     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7096     QualType destType = Context.getPointerType(destPointee);
7097     // Add qualifiers if necessary.
7098     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7099     // Promote to void*.
7100     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7101     return destType;
7102   }
7103   return QualType();
7104 }
7105 
7106 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7107 /// ParenRange in parentheses.
7108 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7109                                const PartialDiagnostic &Note,
7110                                SourceRange ParenRange) {
7111   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7112   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7113       EndLoc.isValid()) {
7114     Self.Diag(Loc, Note)
7115       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7116       << FixItHint::CreateInsertion(EndLoc, ")");
7117   } else {
7118     // We can't display the parentheses, so just show the bare note.
7119     Self.Diag(Loc, Note) << ParenRange;
7120   }
7121 }
7122 
7123 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7124   return BinaryOperator::isAdditiveOp(Opc) ||
7125          BinaryOperator::isMultiplicativeOp(Opc) ||
7126          BinaryOperator::isShiftOp(Opc);
7127 }
7128 
7129 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7130 /// expression, either using a built-in or overloaded operator,
7131 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7132 /// expression.
7133 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7134                                    Expr **RHSExprs) {
7135   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7136   E = E->IgnoreImpCasts();
7137   E = E->IgnoreConversionOperator();
7138   E = E->IgnoreImpCasts();
7139   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7140     E = MTE->GetTemporaryExpr();
7141     E = E->IgnoreImpCasts();
7142   }
7143 
7144   // Built-in binary operator.
7145   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7146     if (IsArithmeticOp(OP->getOpcode())) {
7147       *Opcode = OP->getOpcode();
7148       *RHSExprs = OP->getRHS();
7149       return true;
7150     }
7151   }
7152 
7153   // Overloaded operator.
7154   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7155     if (Call->getNumArgs() != 2)
7156       return false;
7157 
7158     // Make sure this is really a binary operator that is safe to pass into
7159     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7160     OverloadedOperatorKind OO = Call->getOperator();
7161     if (OO < OO_Plus || OO > OO_Arrow ||
7162         OO == OO_PlusPlus || OO == OO_MinusMinus)
7163       return false;
7164 
7165     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7166     if (IsArithmeticOp(OpKind)) {
7167       *Opcode = OpKind;
7168       *RHSExprs = Call->getArg(1);
7169       return true;
7170     }
7171   }
7172 
7173   return false;
7174 }
7175 
7176 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7177 /// or is a logical expression such as (x==y) which has int type, but is
7178 /// commonly interpreted as boolean.
7179 static bool ExprLooksBoolean(Expr *E) {
7180   E = E->IgnoreParenImpCasts();
7181 
7182   if (E->getType()->isBooleanType())
7183     return true;
7184   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7185     return OP->isComparisonOp() || OP->isLogicalOp();
7186   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7187     return OP->getOpcode() == UO_LNot;
7188   if (E->getType()->isPointerType())
7189     return true;
7190   // FIXME: What about overloaded operator calls returning "unspecified boolean
7191   // type"s (commonly pointer-to-members)?
7192 
7193   return false;
7194 }
7195 
7196 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7197 /// and binary operator are mixed in a way that suggests the programmer assumed
7198 /// the conditional operator has higher precedence, for example:
7199 /// "int x = a + someBinaryCondition ? 1 : 2".
7200 static void DiagnoseConditionalPrecedence(Sema &Self,
7201                                           SourceLocation OpLoc,
7202                                           Expr *Condition,
7203                                           Expr *LHSExpr,
7204                                           Expr *RHSExpr) {
7205   BinaryOperatorKind CondOpcode;
7206   Expr *CondRHS;
7207 
7208   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7209     return;
7210   if (!ExprLooksBoolean(CondRHS))
7211     return;
7212 
7213   // The condition is an arithmetic binary expression, with a right-
7214   // hand side that looks boolean, so warn.
7215 
7216   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7217       << Condition->getSourceRange()
7218       << BinaryOperator::getOpcodeStr(CondOpcode);
7219 
7220   SuggestParentheses(Self, OpLoc,
7221     Self.PDiag(diag::note_precedence_silence)
7222       << BinaryOperator::getOpcodeStr(CondOpcode),
7223     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7224 
7225   SuggestParentheses(Self, OpLoc,
7226     Self.PDiag(diag::note_precedence_conditional_first),
7227     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7228 }
7229 
7230 /// Compute the nullability of a conditional expression.
7231 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7232                                               QualType LHSTy, QualType RHSTy,
7233                                               ASTContext &Ctx) {
7234   if (!ResTy->isAnyPointerType())
7235     return ResTy;
7236 
7237   auto GetNullability = [&Ctx](QualType Ty) {
7238     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7239     if (Kind)
7240       return *Kind;
7241     return NullabilityKind::Unspecified;
7242   };
7243 
7244   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7245   NullabilityKind MergedKind;
7246 
7247   // Compute nullability of a binary conditional expression.
7248   if (IsBin) {
7249     if (LHSKind == NullabilityKind::NonNull)
7250       MergedKind = NullabilityKind::NonNull;
7251     else
7252       MergedKind = RHSKind;
7253   // Compute nullability of a normal conditional expression.
7254   } else {
7255     if (LHSKind == NullabilityKind::Nullable ||
7256         RHSKind == NullabilityKind::Nullable)
7257       MergedKind = NullabilityKind::Nullable;
7258     else if (LHSKind == NullabilityKind::NonNull)
7259       MergedKind = RHSKind;
7260     else if (RHSKind == NullabilityKind::NonNull)
7261       MergedKind = LHSKind;
7262     else
7263       MergedKind = NullabilityKind::Unspecified;
7264   }
7265 
7266   // Return if ResTy already has the correct nullability.
7267   if (GetNullability(ResTy) == MergedKind)
7268     return ResTy;
7269 
7270   // Strip all nullability from ResTy.
7271   while (ResTy->getNullability(Ctx))
7272     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7273 
7274   // Create a new AttributedType with the new nullability kind.
7275   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7276   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7277 }
7278 
7279 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7280 /// in the case of a the GNU conditional expr extension.
7281 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7282                                     SourceLocation ColonLoc,
7283                                     Expr *CondExpr, Expr *LHSExpr,
7284                                     Expr *RHSExpr) {
7285   if (!getLangOpts().CPlusPlus) {
7286     // C cannot handle TypoExpr nodes in the condition because it
7287     // doesn't handle dependent types properly, so make sure any TypoExprs have
7288     // been dealt with before checking the operands.
7289     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7290     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7291     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7292 
7293     if (!CondResult.isUsable())
7294       return ExprError();
7295 
7296     if (LHSExpr) {
7297       if (!LHSResult.isUsable())
7298         return ExprError();
7299     }
7300 
7301     if (!RHSResult.isUsable())
7302       return ExprError();
7303 
7304     CondExpr = CondResult.get();
7305     LHSExpr = LHSResult.get();
7306     RHSExpr = RHSResult.get();
7307   }
7308 
7309   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7310   // was the condition.
7311   OpaqueValueExpr *opaqueValue = nullptr;
7312   Expr *commonExpr = nullptr;
7313   if (!LHSExpr) {
7314     commonExpr = CondExpr;
7315     // Lower out placeholder types first.  This is important so that we don't
7316     // try to capture a placeholder. This happens in few cases in C++; such
7317     // as Objective-C++'s dictionary subscripting syntax.
7318     if (commonExpr->hasPlaceholderType()) {
7319       ExprResult result = CheckPlaceholderExpr(commonExpr);
7320       if (!result.isUsable()) return ExprError();
7321       commonExpr = result.get();
7322     }
7323     // We usually want to apply unary conversions *before* saving, except
7324     // in the special case of a C++ l-value conditional.
7325     if (!(getLangOpts().CPlusPlus
7326           && !commonExpr->isTypeDependent()
7327           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7328           && commonExpr->isGLValue()
7329           && commonExpr->isOrdinaryOrBitFieldObject()
7330           && RHSExpr->isOrdinaryOrBitFieldObject()
7331           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7332       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7333       if (commonRes.isInvalid())
7334         return ExprError();
7335       commonExpr = commonRes.get();
7336     }
7337 
7338     // If the common expression is a class or array prvalue, materialize it
7339     // so that we can safely refer to it multiple times.
7340     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7341                                    commonExpr->getType()->isArrayType())) {
7342       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7343       if (MatExpr.isInvalid())
7344         return ExprError();
7345       commonExpr = MatExpr.get();
7346     }
7347 
7348     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7349                                                 commonExpr->getType(),
7350                                                 commonExpr->getValueKind(),
7351                                                 commonExpr->getObjectKind(),
7352                                                 commonExpr);
7353     LHSExpr = CondExpr = opaqueValue;
7354   }
7355 
7356   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7357   ExprValueKind VK = VK_RValue;
7358   ExprObjectKind OK = OK_Ordinary;
7359   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7360   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7361                                              VK, OK, QuestionLoc);
7362   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7363       RHS.isInvalid())
7364     return ExprError();
7365 
7366   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7367                                 RHS.get());
7368 
7369   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7370 
7371   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7372                                          Context);
7373 
7374   if (!commonExpr)
7375     return new (Context)
7376         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7377                             RHS.get(), result, VK, OK);
7378 
7379   return new (Context) BinaryConditionalOperator(
7380       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7381       ColonLoc, result, VK, OK);
7382 }
7383 
7384 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7385 // being closely modeled after the C99 spec:-). The odd characteristic of this
7386 // routine is it effectively iqnores the qualifiers on the top level pointee.
7387 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7388 // FIXME: add a couple examples in this comment.
7389 static Sema::AssignConvertType
7390 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7391   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7392   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7393 
7394   // get the "pointed to" type (ignoring qualifiers at the top level)
7395   const Type *lhptee, *rhptee;
7396   Qualifiers lhq, rhq;
7397   std::tie(lhptee, lhq) =
7398       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7399   std::tie(rhptee, rhq) =
7400       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7401 
7402   Sema::AssignConvertType ConvTy = Sema::Compatible;
7403 
7404   // C99 6.5.16.1p1: This following citation is common to constraints
7405   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7406   // qualifiers of the type *pointed to* by the right;
7407 
7408   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7409   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7410       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7411     // Ignore lifetime for further calculation.
7412     lhq.removeObjCLifetime();
7413     rhq.removeObjCLifetime();
7414   }
7415 
7416   if (!lhq.compatiblyIncludes(rhq)) {
7417     // Treat address-space mismatches as fatal.  TODO: address subspaces
7418     if (!lhq.isAddressSpaceSupersetOf(rhq))
7419       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7420 
7421     // It's okay to add or remove GC or lifetime qualifiers when converting to
7422     // and from void*.
7423     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7424                         .compatiblyIncludes(
7425                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7426              && (lhptee->isVoidType() || rhptee->isVoidType()))
7427       ; // keep old
7428 
7429     // Treat lifetime mismatches as fatal.
7430     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7431       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7432 
7433     // For GCC/MS compatibility, other qualifier mismatches are treated
7434     // as still compatible in C.
7435     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7436   }
7437 
7438   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7439   // incomplete type and the other is a pointer to a qualified or unqualified
7440   // version of void...
7441   if (lhptee->isVoidType()) {
7442     if (rhptee->isIncompleteOrObjectType())
7443       return ConvTy;
7444 
7445     // As an extension, we allow cast to/from void* to function pointer.
7446     assert(rhptee->isFunctionType());
7447     return Sema::FunctionVoidPointer;
7448   }
7449 
7450   if (rhptee->isVoidType()) {
7451     if (lhptee->isIncompleteOrObjectType())
7452       return ConvTy;
7453 
7454     // As an extension, we allow cast to/from void* to function pointer.
7455     assert(lhptee->isFunctionType());
7456     return Sema::FunctionVoidPointer;
7457   }
7458 
7459   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7460   // unqualified versions of compatible types, ...
7461   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7462   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7463     // Check if the pointee types are compatible ignoring the sign.
7464     // We explicitly check for char so that we catch "char" vs
7465     // "unsigned char" on systems where "char" is unsigned.
7466     if (lhptee->isCharType())
7467       ltrans = S.Context.UnsignedCharTy;
7468     else if (lhptee->hasSignedIntegerRepresentation())
7469       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7470 
7471     if (rhptee->isCharType())
7472       rtrans = S.Context.UnsignedCharTy;
7473     else if (rhptee->hasSignedIntegerRepresentation())
7474       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7475 
7476     if (ltrans == rtrans) {
7477       // Types are compatible ignoring the sign. Qualifier incompatibility
7478       // takes priority over sign incompatibility because the sign
7479       // warning can be disabled.
7480       if (ConvTy != Sema::Compatible)
7481         return ConvTy;
7482 
7483       return Sema::IncompatiblePointerSign;
7484     }
7485 
7486     // If we are a multi-level pointer, it's possible that our issue is simply
7487     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7488     // the eventual target type is the same and the pointers have the same
7489     // level of indirection, this must be the issue.
7490     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7491       do {
7492         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7493         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7494       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7495 
7496       if (lhptee == rhptee)
7497         return Sema::IncompatibleNestedPointerQualifiers;
7498     }
7499 
7500     // General pointer incompatibility takes priority over qualifiers.
7501     return Sema::IncompatiblePointer;
7502   }
7503   if (!S.getLangOpts().CPlusPlus &&
7504       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7505     return Sema::IncompatiblePointer;
7506   return ConvTy;
7507 }
7508 
7509 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7510 /// block pointer types are compatible or whether a block and normal pointer
7511 /// are compatible. It is more restrict than comparing two function pointer
7512 // types.
7513 static Sema::AssignConvertType
7514 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7515                                     QualType RHSType) {
7516   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7517   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7518 
7519   QualType lhptee, rhptee;
7520 
7521   // get the "pointed to" type (ignoring qualifiers at the top level)
7522   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7523   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7524 
7525   // In C++, the types have to match exactly.
7526   if (S.getLangOpts().CPlusPlus)
7527     return Sema::IncompatibleBlockPointer;
7528 
7529   Sema::AssignConvertType ConvTy = Sema::Compatible;
7530 
7531   // For blocks we enforce that qualifiers are identical.
7532   Qualifiers LQuals = lhptee.getLocalQualifiers();
7533   Qualifiers RQuals = rhptee.getLocalQualifiers();
7534   if (S.getLangOpts().OpenCL) {
7535     LQuals.removeAddressSpace();
7536     RQuals.removeAddressSpace();
7537   }
7538   if (LQuals != RQuals)
7539     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7540 
7541   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7542   // assignment.
7543   // The current behavior is similar to C++ lambdas. A block might be
7544   // assigned to a variable iff its return type and parameters are compatible
7545   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7546   // an assignment. Presumably it should behave in way that a function pointer
7547   // assignment does in C, so for each parameter and return type:
7548   //  * CVR and address space of LHS should be a superset of CVR and address
7549   //  space of RHS.
7550   //  * unqualified types should be compatible.
7551   if (S.getLangOpts().OpenCL) {
7552     if (!S.Context.typesAreBlockPointerCompatible(
7553             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7554             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7555       return Sema::IncompatibleBlockPointer;
7556   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7557     return Sema::IncompatibleBlockPointer;
7558 
7559   return ConvTy;
7560 }
7561 
7562 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7563 /// for assignment compatibility.
7564 static Sema::AssignConvertType
7565 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7566                                    QualType RHSType) {
7567   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7568   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7569 
7570   if (LHSType->isObjCBuiltinType()) {
7571     // Class is not compatible with ObjC object pointers.
7572     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7573         !RHSType->isObjCQualifiedClassType())
7574       return Sema::IncompatiblePointer;
7575     return Sema::Compatible;
7576   }
7577   if (RHSType->isObjCBuiltinType()) {
7578     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7579         !LHSType->isObjCQualifiedClassType())
7580       return Sema::IncompatiblePointer;
7581     return Sema::Compatible;
7582   }
7583   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7584   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7585 
7586   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7587       // make an exception for id<P>
7588       !LHSType->isObjCQualifiedIdType())
7589     return Sema::CompatiblePointerDiscardsQualifiers;
7590 
7591   if (S.Context.typesAreCompatible(LHSType, RHSType))
7592     return Sema::Compatible;
7593   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7594     return Sema::IncompatibleObjCQualifiedId;
7595   return Sema::IncompatiblePointer;
7596 }
7597 
7598 Sema::AssignConvertType
7599 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7600                                  QualType LHSType, QualType RHSType) {
7601   // Fake up an opaque expression.  We don't actually care about what
7602   // cast operations are required, so if CheckAssignmentConstraints
7603   // adds casts to this they'll be wasted, but fortunately that doesn't
7604   // usually happen on valid code.
7605   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7606   ExprResult RHSPtr = &RHSExpr;
7607   CastKind K;
7608 
7609   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7610 }
7611 
7612 /// This helper function returns true if QT is a vector type that has element
7613 /// type ElementType.
7614 static bool isVector(QualType QT, QualType ElementType) {
7615   if (const VectorType *VT = QT->getAs<VectorType>())
7616     return VT->getElementType() == ElementType;
7617   return false;
7618 }
7619 
7620 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7621 /// has code to accommodate several GCC extensions when type checking
7622 /// pointers. Here are some objectionable examples that GCC considers warnings:
7623 ///
7624 ///  int a, *pint;
7625 ///  short *pshort;
7626 ///  struct foo *pfoo;
7627 ///
7628 ///  pint = pshort; // warning: assignment from incompatible pointer type
7629 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7630 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7631 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7632 ///
7633 /// As a result, the code for dealing with pointers is more complex than the
7634 /// C99 spec dictates.
7635 ///
7636 /// Sets 'Kind' for any result kind except Incompatible.
7637 Sema::AssignConvertType
7638 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7639                                  CastKind &Kind, bool ConvertRHS) {
7640   QualType RHSType = RHS.get()->getType();
7641   QualType OrigLHSType = LHSType;
7642 
7643   // Get canonical types.  We're not formatting these types, just comparing
7644   // them.
7645   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7646   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7647 
7648   // Common case: no conversion required.
7649   if (LHSType == RHSType) {
7650     Kind = CK_NoOp;
7651     return Compatible;
7652   }
7653 
7654   // If we have an atomic type, try a non-atomic assignment, then just add an
7655   // atomic qualification step.
7656   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7657     Sema::AssignConvertType result =
7658       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7659     if (result != Compatible)
7660       return result;
7661     if (Kind != CK_NoOp && ConvertRHS)
7662       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7663     Kind = CK_NonAtomicToAtomic;
7664     return Compatible;
7665   }
7666 
7667   // If the left-hand side is a reference type, then we are in a
7668   // (rare!) case where we've allowed the use of references in C,
7669   // e.g., as a parameter type in a built-in function. In this case,
7670   // just make sure that the type referenced is compatible with the
7671   // right-hand side type. The caller is responsible for adjusting
7672   // LHSType so that the resulting expression does not have reference
7673   // type.
7674   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7675     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7676       Kind = CK_LValueBitCast;
7677       return Compatible;
7678     }
7679     return Incompatible;
7680   }
7681 
7682   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7683   // to the same ExtVector type.
7684   if (LHSType->isExtVectorType()) {
7685     if (RHSType->isExtVectorType())
7686       return Incompatible;
7687     if (RHSType->isArithmeticType()) {
7688       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7689       if (ConvertRHS)
7690         RHS = prepareVectorSplat(LHSType, RHS.get());
7691       Kind = CK_VectorSplat;
7692       return Compatible;
7693     }
7694   }
7695 
7696   // Conversions to or from vector type.
7697   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7698     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7699       // Allow assignments of an AltiVec vector type to an equivalent GCC
7700       // vector type and vice versa
7701       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7702         Kind = CK_BitCast;
7703         return Compatible;
7704       }
7705 
7706       // If we are allowing lax vector conversions, and LHS and RHS are both
7707       // vectors, the total size only needs to be the same. This is a bitcast;
7708       // no bits are changed but the result type is different.
7709       if (isLaxVectorConversion(RHSType, LHSType)) {
7710         Kind = CK_BitCast;
7711         return IncompatibleVectors;
7712       }
7713     }
7714 
7715     // When the RHS comes from another lax conversion (e.g. binops between
7716     // scalars and vectors) the result is canonicalized as a vector. When the
7717     // LHS is also a vector, the lax is allowed by the condition above. Handle
7718     // the case where LHS is a scalar.
7719     if (LHSType->isScalarType()) {
7720       const VectorType *VecType = RHSType->getAs<VectorType>();
7721       if (VecType && VecType->getNumElements() == 1 &&
7722           isLaxVectorConversion(RHSType, LHSType)) {
7723         ExprResult *VecExpr = &RHS;
7724         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7725         Kind = CK_BitCast;
7726         return Compatible;
7727       }
7728     }
7729 
7730     return Incompatible;
7731   }
7732 
7733   // Diagnose attempts to convert between __float128 and long double where
7734   // such conversions currently can't be handled.
7735   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7736     return Incompatible;
7737 
7738   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7739   // discards the imaginary part.
7740   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7741       !LHSType->getAs<ComplexType>())
7742     return Incompatible;
7743 
7744   // Arithmetic conversions.
7745   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7746       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7747     if (ConvertRHS)
7748       Kind = PrepareScalarCast(RHS, LHSType);
7749     return Compatible;
7750   }
7751 
7752   // Conversions to normal pointers.
7753   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7754     // U* -> T*
7755     if (isa<PointerType>(RHSType)) {
7756       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7757       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7758       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7759       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7760     }
7761 
7762     // int -> T*
7763     if (RHSType->isIntegerType()) {
7764       Kind = CK_IntegralToPointer; // FIXME: null?
7765       return IntToPointer;
7766     }
7767 
7768     // C pointers are not compatible with ObjC object pointers,
7769     // with two exceptions:
7770     if (isa<ObjCObjectPointerType>(RHSType)) {
7771       //  - conversions to void*
7772       if (LHSPointer->getPointeeType()->isVoidType()) {
7773         Kind = CK_BitCast;
7774         return Compatible;
7775       }
7776 
7777       //  - conversions from 'Class' to the redefinition type
7778       if (RHSType->isObjCClassType() &&
7779           Context.hasSameType(LHSType,
7780                               Context.getObjCClassRedefinitionType())) {
7781         Kind = CK_BitCast;
7782         return Compatible;
7783       }
7784 
7785       Kind = CK_BitCast;
7786       return IncompatiblePointer;
7787     }
7788 
7789     // U^ -> void*
7790     if (RHSType->getAs<BlockPointerType>()) {
7791       if (LHSPointer->getPointeeType()->isVoidType()) {
7792         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7793         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7794                                 ->getPointeeType()
7795                                 .getAddressSpace();
7796         Kind =
7797             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7798         return Compatible;
7799       }
7800     }
7801 
7802     return Incompatible;
7803   }
7804 
7805   // Conversions to block pointers.
7806   if (isa<BlockPointerType>(LHSType)) {
7807     // U^ -> T^
7808     if (RHSType->isBlockPointerType()) {
7809       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7810                               ->getPointeeType()
7811                               .getAddressSpace();
7812       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7813                               ->getPointeeType()
7814                               .getAddressSpace();
7815       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7816       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7817     }
7818 
7819     // int or null -> T^
7820     if (RHSType->isIntegerType()) {
7821       Kind = CK_IntegralToPointer; // FIXME: null
7822       return IntToBlockPointer;
7823     }
7824 
7825     // id -> T^
7826     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7827       Kind = CK_AnyPointerToBlockPointerCast;
7828       return Compatible;
7829     }
7830 
7831     // void* -> T^
7832     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7833       if (RHSPT->getPointeeType()->isVoidType()) {
7834         Kind = CK_AnyPointerToBlockPointerCast;
7835         return Compatible;
7836       }
7837 
7838     return Incompatible;
7839   }
7840 
7841   // Conversions to Objective-C pointers.
7842   if (isa<ObjCObjectPointerType>(LHSType)) {
7843     // A* -> B*
7844     if (RHSType->isObjCObjectPointerType()) {
7845       Kind = CK_BitCast;
7846       Sema::AssignConvertType result =
7847         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7848       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7849           result == Compatible &&
7850           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7851         result = IncompatibleObjCWeakRef;
7852       return result;
7853     }
7854 
7855     // int or null -> A*
7856     if (RHSType->isIntegerType()) {
7857       Kind = CK_IntegralToPointer; // FIXME: null
7858       return IntToPointer;
7859     }
7860 
7861     // In general, C pointers are not compatible with ObjC object pointers,
7862     // with two exceptions:
7863     if (isa<PointerType>(RHSType)) {
7864       Kind = CK_CPointerToObjCPointerCast;
7865 
7866       //  - conversions from 'void*'
7867       if (RHSType->isVoidPointerType()) {
7868         return Compatible;
7869       }
7870 
7871       //  - conversions to 'Class' from its redefinition type
7872       if (LHSType->isObjCClassType() &&
7873           Context.hasSameType(RHSType,
7874                               Context.getObjCClassRedefinitionType())) {
7875         return Compatible;
7876       }
7877 
7878       return IncompatiblePointer;
7879     }
7880 
7881     // Only under strict condition T^ is compatible with an Objective-C pointer.
7882     if (RHSType->isBlockPointerType() &&
7883         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7884       if (ConvertRHS)
7885         maybeExtendBlockObject(RHS);
7886       Kind = CK_BlockPointerToObjCPointerCast;
7887       return Compatible;
7888     }
7889 
7890     return Incompatible;
7891   }
7892 
7893   // Conversions from pointers that are not covered by the above.
7894   if (isa<PointerType>(RHSType)) {
7895     // T* -> _Bool
7896     if (LHSType == Context.BoolTy) {
7897       Kind = CK_PointerToBoolean;
7898       return Compatible;
7899     }
7900 
7901     // T* -> int
7902     if (LHSType->isIntegerType()) {
7903       Kind = CK_PointerToIntegral;
7904       return PointerToInt;
7905     }
7906 
7907     return Incompatible;
7908   }
7909 
7910   // Conversions from Objective-C pointers that are not covered by the above.
7911   if (isa<ObjCObjectPointerType>(RHSType)) {
7912     // T* -> _Bool
7913     if (LHSType == Context.BoolTy) {
7914       Kind = CK_PointerToBoolean;
7915       return Compatible;
7916     }
7917 
7918     // T* -> int
7919     if (LHSType->isIntegerType()) {
7920       Kind = CK_PointerToIntegral;
7921       return PointerToInt;
7922     }
7923 
7924     return Incompatible;
7925   }
7926 
7927   // struct A -> struct B
7928   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7929     if (Context.typesAreCompatible(LHSType, RHSType)) {
7930       Kind = CK_NoOp;
7931       return Compatible;
7932     }
7933   }
7934 
7935   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7936     Kind = CK_IntToOCLSampler;
7937     return Compatible;
7938   }
7939 
7940   return Incompatible;
7941 }
7942 
7943 /// Constructs a transparent union from an expression that is
7944 /// used to initialize the transparent union.
7945 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7946                                       ExprResult &EResult, QualType UnionType,
7947                                       FieldDecl *Field) {
7948   // Build an initializer list that designates the appropriate member
7949   // of the transparent union.
7950   Expr *E = EResult.get();
7951   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7952                                                    E, SourceLocation());
7953   Initializer->setType(UnionType);
7954   Initializer->setInitializedFieldInUnion(Field);
7955 
7956   // Build a compound literal constructing a value of the transparent
7957   // union type from this initializer list.
7958   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7959   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7960                                         VK_RValue, Initializer, false);
7961 }
7962 
7963 Sema::AssignConvertType
7964 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7965                                                ExprResult &RHS) {
7966   QualType RHSType = RHS.get()->getType();
7967 
7968   // If the ArgType is a Union type, we want to handle a potential
7969   // transparent_union GCC extension.
7970   const RecordType *UT = ArgType->getAsUnionType();
7971   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7972     return Incompatible;
7973 
7974   // The field to initialize within the transparent union.
7975   RecordDecl *UD = UT->getDecl();
7976   FieldDecl *InitField = nullptr;
7977   // It's compatible if the expression matches any of the fields.
7978   for (auto *it : UD->fields()) {
7979     if (it->getType()->isPointerType()) {
7980       // If the transparent union contains a pointer type, we allow:
7981       // 1) void pointer
7982       // 2) null pointer constant
7983       if (RHSType->isPointerType())
7984         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7985           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7986           InitField = it;
7987           break;
7988         }
7989 
7990       if (RHS.get()->isNullPointerConstant(Context,
7991                                            Expr::NPC_ValueDependentIsNull)) {
7992         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7993                                 CK_NullToPointer);
7994         InitField = it;
7995         break;
7996       }
7997     }
7998 
7999     CastKind Kind;
8000     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8001           == Compatible) {
8002       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8003       InitField = it;
8004       break;
8005     }
8006   }
8007 
8008   if (!InitField)
8009     return Incompatible;
8010 
8011   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8012   return Compatible;
8013 }
8014 
8015 Sema::AssignConvertType
8016 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8017                                        bool Diagnose,
8018                                        bool DiagnoseCFAudited,
8019                                        bool ConvertRHS) {
8020   // We need to be able to tell the caller whether we diagnosed a problem, if
8021   // they ask us to issue diagnostics.
8022   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8023 
8024   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8025   // we can't avoid *all* modifications at the moment, so we need some somewhere
8026   // to put the updated value.
8027   ExprResult LocalRHS = CallerRHS;
8028   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8029 
8030   if (getLangOpts().CPlusPlus) {
8031     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8032       // C++ 5.17p3: If the left operand is not of class type, the
8033       // expression is implicitly converted (C++ 4) to the
8034       // cv-unqualified type of the left operand.
8035       QualType RHSType = RHS.get()->getType();
8036       if (Diagnose) {
8037         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8038                                         AA_Assigning);
8039       } else {
8040         ImplicitConversionSequence ICS =
8041             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8042                                   /*SuppressUserConversions=*/false,
8043                                   /*AllowExplicit=*/false,
8044                                   /*InOverloadResolution=*/false,
8045                                   /*CStyle=*/false,
8046                                   /*AllowObjCWritebackConversion=*/false);
8047         if (ICS.isFailure())
8048           return Incompatible;
8049         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8050                                         ICS, AA_Assigning);
8051       }
8052       if (RHS.isInvalid())
8053         return Incompatible;
8054       Sema::AssignConvertType result = Compatible;
8055       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8056           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8057         result = IncompatibleObjCWeakRef;
8058       return result;
8059     }
8060 
8061     // FIXME: Currently, we fall through and treat C++ classes like C
8062     // structures.
8063     // FIXME: We also fall through for atomics; not sure what should
8064     // happen there, though.
8065   } else if (RHS.get()->getType() == Context.OverloadTy) {
8066     // As a set of extensions to C, we support overloading on functions. These
8067     // functions need to be resolved here.
8068     DeclAccessPair DAP;
8069     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8070             RHS.get(), LHSType, /*Complain=*/false, DAP))
8071       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8072     else
8073       return Incompatible;
8074   }
8075 
8076   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8077   // a null pointer constant.
8078   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8079        LHSType->isBlockPointerType()) &&
8080       RHS.get()->isNullPointerConstant(Context,
8081                                        Expr::NPC_ValueDependentIsNull)) {
8082     if (Diagnose || ConvertRHS) {
8083       CastKind Kind;
8084       CXXCastPath Path;
8085       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8086                              /*IgnoreBaseAccess=*/false, Diagnose);
8087       if (ConvertRHS)
8088         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8089     }
8090     return Compatible;
8091   }
8092 
8093   // This check seems unnatural, however it is necessary to ensure the proper
8094   // conversion of functions/arrays. If the conversion were done for all
8095   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8096   // expressions that suppress this implicit conversion (&, sizeof).
8097   //
8098   // Suppress this for references: C++ 8.5.3p5.
8099   if (!LHSType->isReferenceType()) {
8100     // FIXME: We potentially allocate here even if ConvertRHS is false.
8101     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8102     if (RHS.isInvalid())
8103       return Incompatible;
8104   }
8105 
8106   Expr *PRE = RHS.get()->IgnoreParenCasts();
8107   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8108     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8109     if (PDecl && !PDecl->hasDefinition()) {
8110       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8111       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8112     }
8113   }
8114 
8115   CastKind Kind;
8116   Sema::AssignConvertType result =
8117     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8118 
8119   // C99 6.5.16.1p2: The value of the right operand is converted to the
8120   // type of the assignment expression.
8121   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8122   // so that we can use references in built-in functions even in C.
8123   // The getNonReferenceType() call makes sure that the resulting expression
8124   // does not have reference type.
8125   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8126     QualType Ty = LHSType.getNonLValueExprType(Context);
8127     Expr *E = RHS.get();
8128 
8129     // Check for various Objective-C errors. If we are not reporting
8130     // diagnostics and just checking for errors, e.g., during overload
8131     // resolution, return Incompatible to indicate the failure.
8132     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8133         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8134                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8135       if (!Diagnose)
8136         return Incompatible;
8137     }
8138     if (getLangOpts().ObjC1 &&
8139         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8140                                            E->getType(), E, Diagnose) ||
8141          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8142       if (!Diagnose)
8143         return Incompatible;
8144       // Replace the expression with a corrected version and continue so we
8145       // can find further errors.
8146       RHS = E;
8147       return Compatible;
8148     }
8149 
8150     if (ConvertRHS)
8151       RHS = ImpCastExprToType(E, Ty, Kind);
8152   }
8153   return result;
8154 }
8155 
8156 namespace {
8157 /// The original operand to an operator, prior to the application of the usual
8158 /// arithmetic conversions and converting the arguments of a builtin operator
8159 /// candidate.
8160 struct OriginalOperand {
8161   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8162     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8163       Op = MTE->GetTemporaryExpr();
8164     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8165       Op = BTE->getSubExpr();
8166     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8167       Orig = ICE->getSubExprAsWritten();
8168       Conversion = ICE->getConversionFunction();
8169     }
8170   }
8171 
8172   QualType getType() const { return Orig->getType(); }
8173 
8174   Expr *Orig;
8175   NamedDecl *Conversion;
8176 };
8177 }
8178 
8179 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8180                                ExprResult &RHS) {
8181   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8182 
8183   Diag(Loc, diag::err_typecheck_invalid_operands)
8184     << OrigLHS.getType() << OrigRHS.getType()
8185     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8186 
8187   // If a user-defined conversion was applied to either of the operands prior
8188   // to applying the built-in operator rules, tell the user about it.
8189   if (OrigLHS.Conversion) {
8190     Diag(OrigLHS.Conversion->getLocation(),
8191          diag::note_typecheck_invalid_operands_converted)
8192       << 0 << LHS.get()->getType();
8193   }
8194   if (OrigRHS.Conversion) {
8195     Diag(OrigRHS.Conversion->getLocation(),
8196          diag::note_typecheck_invalid_operands_converted)
8197       << 1 << RHS.get()->getType();
8198   }
8199 
8200   return QualType();
8201 }
8202 
8203 // Diagnose cases where a scalar was implicitly converted to a vector and
8204 // diagnose the underlying types. Otherwise, diagnose the error
8205 // as invalid vector logical operands for non-C++ cases.
8206 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8207                                             ExprResult &RHS) {
8208   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8209   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8210 
8211   bool LHSNatVec = LHSType->isVectorType();
8212   bool RHSNatVec = RHSType->isVectorType();
8213 
8214   if (!(LHSNatVec && RHSNatVec)) {
8215     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8216     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8217     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8218         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8219         << Vector->getSourceRange();
8220     return QualType();
8221   }
8222 
8223   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8224       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8225       << RHS.get()->getSourceRange();
8226 
8227   return QualType();
8228 }
8229 
8230 /// Try to convert a value of non-vector type to a vector type by converting
8231 /// the type to the element type of the vector and then performing a splat.
8232 /// If the language is OpenCL, we only use conversions that promote scalar
8233 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8234 /// for float->int.
8235 ///
8236 /// OpenCL V2.0 6.2.6.p2:
8237 /// An error shall occur if any scalar operand type has greater rank
8238 /// than the type of the vector element.
8239 ///
8240 /// \param scalar - if non-null, actually perform the conversions
8241 /// \return true if the operation fails (but without diagnosing the failure)
8242 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8243                                      QualType scalarTy,
8244                                      QualType vectorEltTy,
8245                                      QualType vectorTy,
8246                                      unsigned &DiagID) {
8247   // The conversion to apply to the scalar before splatting it,
8248   // if necessary.
8249   CastKind scalarCast = CK_NoOp;
8250 
8251   if (vectorEltTy->isIntegralType(S.Context)) {
8252     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8253         (scalarTy->isIntegerType() &&
8254          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8255       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8256       return true;
8257     }
8258     if (!scalarTy->isIntegralType(S.Context))
8259       return true;
8260     scalarCast = CK_IntegralCast;
8261   } else if (vectorEltTy->isRealFloatingType()) {
8262     if (scalarTy->isRealFloatingType()) {
8263       if (S.getLangOpts().OpenCL &&
8264           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8265         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8266         return true;
8267       }
8268       scalarCast = CK_FloatingCast;
8269     }
8270     else if (scalarTy->isIntegralType(S.Context))
8271       scalarCast = CK_IntegralToFloating;
8272     else
8273       return true;
8274   } else {
8275     return true;
8276   }
8277 
8278   // Adjust scalar if desired.
8279   if (scalar) {
8280     if (scalarCast != CK_NoOp)
8281       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8282     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8283   }
8284   return false;
8285 }
8286 
8287 /// Convert vector E to a vector with the same number of elements but different
8288 /// element type.
8289 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8290   const auto *VecTy = E->getType()->getAs<VectorType>();
8291   assert(VecTy && "Expression E must be a vector");
8292   QualType NewVecTy = S.Context.getVectorType(ElementType,
8293                                               VecTy->getNumElements(),
8294                                               VecTy->getVectorKind());
8295 
8296   // Look through the implicit cast. Return the subexpression if its type is
8297   // NewVecTy.
8298   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8299     if (ICE->getSubExpr()->getType() == NewVecTy)
8300       return ICE->getSubExpr();
8301 
8302   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8303   return S.ImpCastExprToType(E, NewVecTy, Cast);
8304 }
8305 
8306 /// Test if a (constant) integer Int can be casted to another integer type
8307 /// IntTy without losing precision.
8308 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8309                                       QualType OtherIntTy) {
8310   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8311 
8312   // Reject cases where the value of the Int is unknown as that would
8313   // possibly cause truncation, but accept cases where the scalar can be
8314   // demoted without loss of precision.
8315   llvm::APSInt Result;
8316   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8317   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8318   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8319   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8320 
8321   if (CstInt) {
8322     // If the scalar is constant and is of a higher order and has more active
8323     // bits that the vector element type, reject it.
8324     unsigned NumBits = IntSigned
8325                            ? (Result.isNegative() ? Result.getMinSignedBits()
8326                                                   : Result.getActiveBits())
8327                            : Result.getActiveBits();
8328     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8329       return true;
8330 
8331     // If the signedness of the scalar type and the vector element type
8332     // differs and the number of bits is greater than that of the vector
8333     // element reject it.
8334     return (IntSigned != OtherIntSigned &&
8335             NumBits > S.Context.getIntWidth(OtherIntTy));
8336   }
8337 
8338   // Reject cases where the value of the scalar is not constant and it's
8339   // order is greater than that of the vector element type.
8340   return (Order < 0);
8341 }
8342 
8343 /// Test if a (constant) integer Int can be casted to floating point type
8344 /// FloatTy without losing precision.
8345 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8346                                      QualType FloatTy) {
8347   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8348 
8349   // Determine if the integer constant can be expressed as a floating point
8350   // number of the appropriate type.
8351   llvm::APSInt Result;
8352   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8353   uint64_t Bits = 0;
8354   if (CstInt) {
8355     // Reject constants that would be truncated if they were converted to
8356     // the floating point type. Test by simple to/from conversion.
8357     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8358     //        could be avoided if there was a convertFromAPInt method
8359     //        which could signal back if implicit truncation occurred.
8360     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8361     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8362                            llvm::APFloat::rmTowardZero);
8363     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8364                              !IntTy->hasSignedIntegerRepresentation());
8365     bool Ignored = false;
8366     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8367                            &Ignored);
8368     if (Result != ConvertBack)
8369       return true;
8370   } else {
8371     // Reject types that cannot be fully encoded into the mantissa of
8372     // the float.
8373     Bits = S.Context.getTypeSize(IntTy);
8374     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8375         S.Context.getFloatTypeSemantics(FloatTy));
8376     if (Bits > FloatPrec)
8377       return true;
8378   }
8379 
8380   return false;
8381 }
8382 
8383 /// Attempt to convert and splat Scalar into a vector whose types matches
8384 /// Vector following GCC conversion rules. The rule is that implicit
8385 /// conversion can occur when Scalar can be casted to match Vector's element
8386 /// type without causing truncation of Scalar.
8387 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8388                                         ExprResult *Vector) {
8389   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8390   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8391   const VectorType *VT = VectorTy->getAs<VectorType>();
8392 
8393   assert(!isa<ExtVectorType>(VT) &&
8394          "ExtVectorTypes should not be handled here!");
8395 
8396   QualType VectorEltTy = VT->getElementType();
8397 
8398   // Reject cases where the vector element type or the scalar element type are
8399   // not integral or floating point types.
8400   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8401     return true;
8402 
8403   // The conversion to apply to the scalar before splatting it,
8404   // if necessary.
8405   CastKind ScalarCast = CK_NoOp;
8406 
8407   // Accept cases where the vector elements are integers and the scalar is
8408   // an integer.
8409   // FIXME: Notionally if the scalar was a floating point value with a precise
8410   //        integral representation, we could cast it to an appropriate integer
8411   //        type and then perform the rest of the checks here. GCC will perform
8412   //        this conversion in some cases as determined by the input language.
8413   //        We should accept it on a language independent basis.
8414   if (VectorEltTy->isIntegralType(S.Context) &&
8415       ScalarTy->isIntegralType(S.Context) &&
8416       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8417 
8418     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8419       return true;
8420 
8421     ScalarCast = CK_IntegralCast;
8422   } else if (VectorEltTy->isRealFloatingType()) {
8423     if (ScalarTy->isRealFloatingType()) {
8424 
8425       // Reject cases where the scalar type is not a constant and has a higher
8426       // Order than the vector element type.
8427       llvm::APFloat Result(0.0);
8428       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8429       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8430       if (!CstScalar && Order < 0)
8431         return true;
8432 
8433       // If the scalar cannot be safely casted to the vector element type,
8434       // reject it.
8435       if (CstScalar) {
8436         bool Truncated = false;
8437         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8438                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8439         if (Truncated)
8440           return true;
8441       }
8442 
8443       ScalarCast = CK_FloatingCast;
8444     } else if (ScalarTy->isIntegralType(S.Context)) {
8445       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8446         return true;
8447 
8448       ScalarCast = CK_IntegralToFloating;
8449     } else
8450       return true;
8451   }
8452 
8453   // Adjust scalar if desired.
8454   if (Scalar) {
8455     if (ScalarCast != CK_NoOp)
8456       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8457     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8458   }
8459   return false;
8460 }
8461 
8462 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8463                                    SourceLocation Loc, bool IsCompAssign,
8464                                    bool AllowBothBool,
8465                                    bool AllowBoolConversions) {
8466   if (!IsCompAssign) {
8467     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8468     if (LHS.isInvalid())
8469       return QualType();
8470   }
8471   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8472   if (RHS.isInvalid())
8473     return QualType();
8474 
8475   // For conversion purposes, we ignore any qualifiers.
8476   // For example, "const float" and "float" are equivalent.
8477   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8478   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8479 
8480   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8481   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8482   assert(LHSVecType || RHSVecType);
8483 
8484   // AltiVec-style "vector bool op vector bool" combinations are allowed
8485   // for some operators but not others.
8486   if (!AllowBothBool &&
8487       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8488       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8489     return InvalidOperands(Loc, LHS, RHS);
8490 
8491   // If the vector types are identical, return.
8492   if (Context.hasSameType(LHSType, RHSType))
8493     return LHSType;
8494 
8495   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8496   if (LHSVecType && RHSVecType &&
8497       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8498     if (isa<ExtVectorType>(LHSVecType)) {
8499       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8500       return LHSType;
8501     }
8502 
8503     if (!IsCompAssign)
8504       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8505     return RHSType;
8506   }
8507 
8508   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8509   // can be mixed, with the result being the non-bool type.  The non-bool
8510   // operand must have integer element type.
8511   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8512       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8513       (Context.getTypeSize(LHSVecType->getElementType()) ==
8514        Context.getTypeSize(RHSVecType->getElementType()))) {
8515     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8516         LHSVecType->getElementType()->isIntegerType() &&
8517         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8518       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8519       return LHSType;
8520     }
8521     if (!IsCompAssign &&
8522         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8523         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8524         RHSVecType->getElementType()->isIntegerType()) {
8525       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8526       return RHSType;
8527     }
8528   }
8529 
8530   // If there's a vector type and a scalar, try to convert the scalar to
8531   // the vector element type and splat.
8532   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8533   if (!RHSVecType) {
8534     if (isa<ExtVectorType>(LHSVecType)) {
8535       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8536                                     LHSVecType->getElementType(), LHSType,
8537                                     DiagID))
8538         return LHSType;
8539     } else {
8540       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8541         return LHSType;
8542     }
8543   }
8544   if (!LHSVecType) {
8545     if (isa<ExtVectorType>(RHSVecType)) {
8546       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8547                                     LHSType, RHSVecType->getElementType(),
8548                                     RHSType, DiagID))
8549         return RHSType;
8550     } else {
8551       if (LHS.get()->getValueKind() == VK_LValue ||
8552           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8553         return RHSType;
8554     }
8555   }
8556 
8557   // FIXME: The code below also handles conversion between vectors and
8558   // non-scalars, we should break this down into fine grained specific checks
8559   // and emit proper diagnostics.
8560   QualType VecType = LHSVecType ? LHSType : RHSType;
8561   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8562   QualType OtherType = LHSVecType ? RHSType : LHSType;
8563   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8564   if (isLaxVectorConversion(OtherType, VecType)) {
8565     // If we're allowing lax vector conversions, only the total (data) size
8566     // needs to be the same. For non compound assignment, if one of the types is
8567     // scalar, the result is always the vector type.
8568     if (!IsCompAssign) {
8569       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8570       return VecType;
8571     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8572     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8573     // type. Note that this is already done by non-compound assignments in
8574     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8575     // <1 x T> -> T. The result is also a vector type.
8576     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8577                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8578       ExprResult *RHSExpr = &RHS;
8579       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8580       return VecType;
8581     }
8582   }
8583 
8584   // Okay, the expression is invalid.
8585 
8586   // If there's a non-vector, non-real operand, diagnose that.
8587   if ((!RHSVecType && !RHSType->isRealType()) ||
8588       (!LHSVecType && !LHSType->isRealType())) {
8589     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8590       << LHSType << RHSType
8591       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8592     return QualType();
8593   }
8594 
8595   // OpenCL V1.1 6.2.6.p1:
8596   // If the operands are of more than one vector type, then an error shall
8597   // occur. Implicit conversions between vector types are not permitted, per
8598   // section 6.2.1.
8599   if (getLangOpts().OpenCL &&
8600       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8601       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8602     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8603                                                            << RHSType;
8604     return QualType();
8605   }
8606 
8607 
8608   // If there is a vector type that is not a ExtVector and a scalar, we reach
8609   // this point if scalar could not be converted to the vector's element type
8610   // without truncation.
8611   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8612       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8613     QualType Scalar = LHSVecType ? RHSType : LHSType;
8614     QualType Vector = LHSVecType ? LHSType : RHSType;
8615     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8616     Diag(Loc,
8617          diag::err_typecheck_vector_not_convertable_implict_truncation)
8618         << ScalarOrVector << Scalar << Vector;
8619 
8620     return QualType();
8621   }
8622 
8623   // Otherwise, use the generic diagnostic.
8624   Diag(Loc, DiagID)
8625     << LHSType << RHSType
8626     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8627   return QualType();
8628 }
8629 
8630 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8631 // expression.  These are mainly cases where the null pointer is used as an
8632 // integer instead of a pointer.
8633 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8634                                 SourceLocation Loc, bool IsCompare) {
8635   // The canonical way to check for a GNU null is with isNullPointerConstant,
8636   // but we use a bit of a hack here for speed; this is a relatively
8637   // hot path, and isNullPointerConstant is slow.
8638   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8639   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8640 
8641   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8642 
8643   // Avoid analyzing cases where the result will either be invalid (and
8644   // diagnosed as such) or entirely valid and not something to warn about.
8645   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8646       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8647     return;
8648 
8649   // Comparison operations would not make sense with a null pointer no matter
8650   // what the other expression is.
8651   if (!IsCompare) {
8652     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8653         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8654         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8655     return;
8656   }
8657 
8658   // The rest of the operations only make sense with a null pointer
8659   // if the other expression is a pointer.
8660   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8661       NonNullType->canDecayToPointerType())
8662     return;
8663 
8664   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8665       << LHSNull /* LHS is NULL */ << NonNullType
8666       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8667 }
8668 
8669 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8670                                                ExprResult &RHS,
8671                                                SourceLocation Loc, bool IsDiv) {
8672   // Check for division/remainder by zero.
8673   llvm::APSInt RHSValue;
8674   if (!RHS.get()->isValueDependent() &&
8675       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8676     S.DiagRuntimeBehavior(Loc, RHS.get(),
8677                           S.PDiag(diag::warn_remainder_division_by_zero)
8678                             << IsDiv << RHS.get()->getSourceRange());
8679 }
8680 
8681 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8682                                            SourceLocation Loc,
8683                                            bool IsCompAssign, bool IsDiv) {
8684   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8685 
8686   if (LHS.get()->getType()->isVectorType() ||
8687       RHS.get()->getType()->isVectorType())
8688     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8689                                /*AllowBothBool*/getLangOpts().AltiVec,
8690                                /*AllowBoolConversions*/false);
8691 
8692   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8693   if (LHS.isInvalid() || RHS.isInvalid())
8694     return QualType();
8695 
8696 
8697   if (compType.isNull() || !compType->isArithmeticType())
8698     return InvalidOperands(Loc, LHS, RHS);
8699   if (IsDiv)
8700     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8701   return compType;
8702 }
8703 
8704 QualType Sema::CheckRemainderOperands(
8705   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8706   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8707 
8708   if (LHS.get()->getType()->isVectorType() ||
8709       RHS.get()->getType()->isVectorType()) {
8710     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8711         RHS.get()->getType()->hasIntegerRepresentation())
8712       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8713                                  /*AllowBothBool*/getLangOpts().AltiVec,
8714                                  /*AllowBoolConversions*/false);
8715     return InvalidOperands(Loc, LHS, RHS);
8716   }
8717 
8718   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8719   if (LHS.isInvalid() || RHS.isInvalid())
8720     return QualType();
8721 
8722   if (compType.isNull() || !compType->isIntegerType())
8723     return InvalidOperands(Loc, LHS, RHS);
8724   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8725   return compType;
8726 }
8727 
8728 /// Diagnose invalid arithmetic on two void pointers.
8729 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8730                                                 Expr *LHSExpr, Expr *RHSExpr) {
8731   S.Diag(Loc, S.getLangOpts().CPlusPlus
8732                 ? diag::err_typecheck_pointer_arith_void_type
8733                 : diag::ext_gnu_void_ptr)
8734     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8735                             << RHSExpr->getSourceRange();
8736 }
8737 
8738 /// Diagnose invalid arithmetic on a void pointer.
8739 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8740                                             Expr *Pointer) {
8741   S.Diag(Loc, S.getLangOpts().CPlusPlus
8742                 ? diag::err_typecheck_pointer_arith_void_type
8743                 : diag::ext_gnu_void_ptr)
8744     << 0 /* one pointer */ << Pointer->getSourceRange();
8745 }
8746 
8747 /// Diagnose invalid arithmetic on a null pointer.
8748 ///
8749 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8750 /// idiom, which we recognize as a GNU extension.
8751 ///
8752 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8753                                             Expr *Pointer, bool IsGNUIdiom) {
8754   if (IsGNUIdiom)
8755     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8756       << Pointer->getSourceRange();
8757   else
8758     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8759       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8760 }
8761 
8762 /// Diagnose invalid arithmetic on two function pointers.
8763 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8764                                                     Expr *LHS, Expr *RHS) {
8765   assert(LHS->getType()->isAnyPointerType());
8766   assert(RHS->getType()->isAnyPointerType());
8767   S.Diag(Loc, S.getLangOpts().CPlusPlus
8768                 ? diag::err_typecheck_pointer_arith_function_type
8769                 : diag::ext_gnu_ptr_func_arith)
8770     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8771     // We only show the second type if it differs from the first.
8772     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8773                                                    RHS->getType())
8774     << RHS->getType()->getPointeeType()
8775     << LHS->getSourceRange() << RHS->getSourceRange();
8776 }
8777 
8778 /// Diagnose invalid arithmetic on a function pointer.
8779 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8780                                                 Expr *Pointer) {
8781   assert(Pointer->getType()->isAnyPointerType());
8782   S.Diag(Loc, S.getLangOpts().CPlusPlus
8783                 ? diag::err_typecheck_pointer_arith_function_type
8784                 : diag::ext_gnu_ptr_func_arith)
8785     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8786     << 0 /* one pointer, so only one type */
8787     << Pointer->getSourceRange();
8788 }
8789 
8790 /// Emit error if Operand is incomplete pointer type
8791 ///
8792 /// \returns True if pointer has incomplete type
8793 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8794                                                  Expr *Operand) {
8795   QualType ResType = Operand->getType();
8796   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8797     ResType = ResAtomicType->getValueType();
8798 
8799   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8800   QualType PointeeTy = ResType->getPointeeType();
8801   return S.RequireCompleteType(Loc, PointeeTy,
8802                                diag::err_typecheck_arithmetic_incomplete_type,
8803                                PointeeTy, Operand->getSourceRange());
8804 }
8805 
8806 /// Check the validity of an arithmetic pointer operand.
8807 ///
8808 /// If the operand has pointer type, this code will check for pointer types
8809 /// which are invalid in arithmetic operations. These will be diagnosed
8810 /// appropriately, including whether or not the use is supported as an
8811 /// extension.
8812 ///
8813 /// \returns True when the operand is valid to use (even if as an extension).
8814 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8815                                             Expr *Operand) {
8816   QualType ResType = Operand->getType();
8817   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8818     ResType = ResAtomicType->getValueType();
8819 
8820   if (!ResType->isAnyPointerType()) return true;
8821 
8822   QualType PointeeTy = ResType->getPointeeType();
8823   if (PointeeTy->isVoidType()) {
8824     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8825     return !S.getLangOpts().CPlusPlus;
8826   }
8827   if (PointeeTy->isFunctionType()) {
8828     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8829     return !S.getLangOpts().CPlusPlus;
8830   }
8831 
8832   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8833 
8834   return true;
8835 }
8836 
8837 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8838 /// operands.
8839 ///
8840 /// This routine will diagnose any invalid arithmetic on pointer operands much
8841 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8842 /// for emitting a single diagnostic even for operations where both LHS and RHS
8843 /// are (potentially problematic) pointers.
8844 ///
8845 /// \returns True when the operand is valid to use (even if as an extension).
8846 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8847                                                 Expr *LHSExpr, Expr *RHSExpr) {
8848   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8849   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8850   if (!isLHSPointer && !isRHSPointer) return true;
8851 
8852   QualType LHSPointeeTy, RHSPointeeTy;
8853   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8854   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8855 
8856   // if both are pointers check if operation is valid wrt address spaces
8857   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8858     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8859     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8860     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8861       S.Diag(Loc,
8862              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8863           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8864           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8865       return false;
8866     }
8867   }
8868 
8869   // Check for arithmetic on pointers to incomplete types.
8870   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8871   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8872   if (isLHSVoidPtr || isRHSVoidPtr) {
8873     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8874     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8875     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8876 
8877     return !S.getLangOpts().CPlusPlus;
8878   }
8879 
8880   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8881   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8882   if (isLHSFuncPtr || isRHSFuncPtr) {
8883     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8884     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8885                                                                 RHSExpr);
8886     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8887 
8888     return !S.getLangOpts().CPlusPlus;
8889   }
8890 
8891   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8892     return false;
8893   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8894     return false;
8895 
8896   return true;
8897 }
8898 
8899 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8900 /// literal.
8901 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8902                                   Expr *LHSExpr, Expr *RHSExpr) {
8903   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8904   Expr* IndexExpr = RHSExpr;
8905   if (!StrExpr) {
8906     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8907     IndexExpr = LHSExpr;
8908   }
8909 
8910   bool IsStringPlusInt = StrExpr &&
8911       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8912   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8913     return;
8914 
8915   llvm::APSInt index;
8916   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8917     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8918     if (index.isNonNegative() &&
8919         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8920                               index.isUnsigned()))
8921       return;
8922   }
8923 
8924   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8925   Self.Diag(OpLoc, diag::warn_string_plus_int)
8926       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8927 
8928   // Only print a fixit for "str" + int, not for int + "str".
8929   if (IndexExpr == RHSExpr) {
8930     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8931     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8932         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8933         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8934         << FixItHint::CreateInsertion(EndLoc, "]");
8935   } else
8936     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8937 }
8938 
8939 /// Emit a warning when adding a char literal to a string.
8940 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8941                                    Expr *LHSExpr, Expr *RHSExpr) {
8942   const Expr *StringRefExpr = LHSExpr;
8943   const CharacterLiteral *CharExpr =
8944       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8945 
8946   if (!CharExpr) {
8947     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8948     StringRefExpr = RHSExpr;
8949   }
8950 
8951   if (!CharExpr || !StringRefExpr)
8952     return;
8953 
8954   const QualType StringType = StringRefExpr->getType();
8955 
8956   // Return if not a PointerType.
8957   if (!StringType->isAnyPointerType())
8958     return;
8959 
8960   // Return if not a CharacterType.
8961   if (!StringType->getPointeeType()->isAnyCharacterType())
8962     return;
8963 
8964   ASTContext &Ctx = Self.getASTContext();
8965   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8966 
8967   const QualType CharType = CharExpr->getType();
8968   if (!CharType->isAnyCharacterType() &&
8969       CharType->isIntegerType() &&
8970       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8971     Self.Diag(OpLoc, diag::warn_string_plus_char)
8972         << DiagRange << Ctx.CharTy;
8973   } else {
8974     Self.Diag(OpLoc, diag::warn_string_plus_char)
8975         << DiagRange << CharExpr->getType();
8976   }
8977 
8978   // Only print a fixit for str + char, not for char + str.
8979   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8980     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8981     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8982         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8983         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8984         << FixItHint::CreateInsertion(EndLoc, "]");
8985   } else {
8986     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8987   }
8988 }
8989 
8990 /// Emit error when two pointers are incompatible.
8991 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8992                                            Expr *LHSExpr, Expr *RHSExpr) {
8993   assert(LHSExpr->getType()->isAnyPointerType());
8994   assert(RHSExpr->getType()->isAnyPointerType());
8995   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8996     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8997     << RHSExpr->getSourceRange();
8998 }
8999 
9000 // C99 6.5.6
9001 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9002                                      SourceLocation Loc, BinaryOperatorKind Opc,
9003                                      QualType* CompLHSTy) {
9004   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9005 
9006   if (LHS.get()->getType()->isVectorType() ||
9007       RHS.get()->getType()->isVectorType()) {
9008     QualType compType = CheckVectorOperands(
9009         LHS, RHS, Loc, CompLHSTy,
9010         /*AllowBothBool*/getLangOpts().AltiVec,
9011         /*AllowBoolConversions*/getLangOpts().ZVector);
9012     if (CompLHSTy) *CompLHSTy = compType;
9013     return compType;
9014   }
9015 
9016   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9017   if (LHS.isInvalid() || RHS.isInvalid())
9018     return QualType();
9019 
9020   // Diagnose "string literal" '+' int and string '+' "char literal".
9021   if (Opc == BO_Add) {
9022     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9023     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9024   }
9025 
9026   // handle the common case first (both operands are arithmetic).
9027   if (!compType.isNull() && compType->isArithmeticType()) {
9028     if (CompLHSTy) *CompLHSTy = compType;
9029     return compType;
9030   }
9031 
9032   // Type-checking.  Ultimately the pointer's going to be in PExp;
9033   // note that we bias towards the LHS being the pointer.
9034   Expr *PExp = LHS.get(), *IExp = RHS.get();
9035 
9036   bool isObjCPointer;
9037   if (PExp->getType()->isPointerType()) {
9038     isObjCPointer = false;
9039   } else if (PExp->getType()->isObjCObjectPointerType()) {
9040     isObjCPointer = true;
9041   } else {
9042     std::swap(PExp, IExp);
9043     if (PExp->getType()->isPointerType()) {
9044       isObjCPointer = false;
9045     } else if (PExp->getType()->isObjCObjectPointerType()) {
9046       isObjCPointer = true;
9047     } else {
9048       return InvalidOperands(Loc, LHS, RHS);
9049     }
9050   }
9051   assert(PExp->getType()->isAnyPointerType());
9052 
9053   if (!IExp->getType()->isIntegerType())
9054     return InvalidOperands(Loc, LHS, RHS);
9055 
9056   // Adding to a null pointer results in undefined behavior.
9057   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9058           Context, Expr::NPC_ValueDependentIsNotNull)) {
9059     // In C++ adding zero to a null pointer is defined.
9060     llvm::APSInt KnownVal;
9061     if (!getLangOpts().CPlusPlus ||
9062         (!IExp->isValueDependent() &&
9063          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9064       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9065       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9066           Context, BO_Add, PExp, IExp);
9067       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9068     }
9069   }
9070 
9071   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9072     return QualType();
9073 
9074   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9075     return QualType();
9076 
9077   // Check array bounds for pointer arithemtic
9078   CheckArrayAccess(PExp, IExp);
9079 
9080   if (CompLHSTy) {
9081     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9082     if (LHSTy.isNull()) {
9083       LHSTy = LHS.get()->getType();
9084       if (LHSTy->isPromotableIntegerType())
9085         LHSTy = Context.getPromotedIntegerType(LHSTy);
9086     }
9087     *CompLHSTy = LHSTy;
9088   }
9089 
9090   return PExp->getType();
9091 }
9092 
9093 // C99 6.5.6
9094 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9095                                         SourceLocation Loc,
9096                                         QualType* CompLHSTy) {
9097   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9098 
9099   if (LHS.get()->getType()->isVectorType() ||
9100       RHS.get()->getType()->isVectorType()) {
9101     QualType compType = CheckVectorOperands(
9102         LHS, RHS, Loc, CompLHSTy,
9103         /*AllowBothBool*/getLangOpts().AltiVec,
9104         /*AllowBoolConversions*/getLangOpts().ZVector);
9105     if (CompLHSTy) *CompLHSTy = compType;
9106     return compType;
9107   }
9108 
9109   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9110   if (LHS.isInvalid() || RHS.isInvalid())
9111     return QualType();
9112 
9113   // Enforce type constraints: C99 6.5.6p3.
9114 
9115   // Handle the common case first (both operands are arithmetic).
9116   if (!compType.isNull() && compType->isArithmeticType()) {
9117     if (CompLHSTy) *CompLHSTy = compType;
9118     return compType;
9119   }
9120 
9121   // Either ptr - int   or   ptr - ptr.
9122   if (LHS.get()->getType()->isAnyPointerType()) {
9123     QualType lpointee = LHS.get()->getType()->getPointeeType();
9124 
9125     // Diagnose bad cases where we step over interface counts.
9126     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9127         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9128       return QualType();
9129 
9130     // The result type of a pointer-int computation is the pointer type.
9131     if (RHS.get()->getType()->isIntegerType()) {
9132       // Subtracting from a null pointer should produce a warning.
9133       // The last argument to the diagnose call says this doesn't match the
9134       // GNU int-to-pointer idiom.
9135       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9136                                            Expr::NPC_ValueDependentIsNotNull)) {
9137         // In C++ adding zero to a null pointer is defined.
9138         llvm::APSInt KnownVal;
9139         if (!getLangOpts().CPlusPlus ||
9140             (!RHS.get()->isValueDependent() &&
9141              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9142           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9143         }
9144       }
9145 
9146       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9147         return QualType();
9148 
9149       // Check array bounds for pointer arithemtic
9150       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9151                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9152 
9153       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9154       return LHS.get()->getType();
9155     }
9156 
9157     // Handle pointer-pointer subtractions.
9158     if (const PointerType *RHSPTy
9159           = RHS.get()->getType()->getAs<PointerType>()) {
9160       QualType rpointee = RHSPTy->getPointeeType();
9161 
9162       if (getLangOpts().CPlusPlus) {
9163         // Pointee types must be the same: C++ [expr.add]
9164         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9165           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9166         }
9167       } else {
9168         // Pointee types must be compatible C99 6.5.6p3
9169         if (!Context.typesAreCompatible(
9170                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9171                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9172           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9173           return QualType();
9174         }
9175       }
9176 
9177       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9178                                                LHS.get(), RHS.get()))
9179         return QualType();
9180 
9181       // FIXME: Add warnings for nullptr - ptr.
9182 
9183       // The pointee type may have zero size.  As an extension, a structure or
9184       // union may have zero size or an array may have zero length.  In this
9185       // case subtraction does not make sense.
9186       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9187         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9188         if (ElementSize.isZero()) {
9189           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9190             << rpointee.getUnqualifiedType()
9191             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9192         }
9193       }
9194 
9195       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9196       return Context.getPointerDiffType();
9197     }
9198   }
9199 
9200   return InvalidOperands(Loc, LHS, RHS);
9201 }
9202 
9203 static bool isScopedEnumerationType(QualType T) {
9204   if (const EnumType *ET = T->getAs<EnumType>())
9205     return ET->getDecl()->isScoped();
9206   return false;
9207 }
9208 
9209 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9210                                    SourceLocation Loc, BinaryOperatorKind Opc,
9211                                    QualType LHSType) {
9212   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9213   // so skip remaining warnings as we don't want to modify values within Sema.
9214   if (S.getLangOpts().OpenCL)
9215     return;
9216 
9217   llvm::APSInt Right;
9218   // Check right/shifter operand
9219   if (RHS.get()->isValueDependent() ||
9220       !RHS.get()->EvaluateAsInt(Right, S.Context))
9221     return;
9222 
9223   if (Right.isNegative()) {
9224     S.DiagRuntimeBehavior(Loc, RHS.get(),
9225                           S.PDiag(diag::warn_shift_negative)
9226                             << RHS.get()->getSourceRange());
9227     return;
9228   }
9229   llvm::APInt LeftBits(Right.getBitWidth(),
9230                        S.Context.getTypeSize(LHS.get()->getType()));
9231   if (Right.uge(LeftBits)) {
9232     S.DiagRuntimeBehavior(Loc, RHS.get(),
9233                           S.PDiag(diag::warn_shift_gt_typewidth)
9234                             << RHS.get()->getSourceRange());
9235     return;
9236   }
9237   if (Opc != BO_Shl)
9238     return;
9239 
9240   // When left shifting an ICE which is signed, we can check for overflow which
9241   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9242   // integers have defined behavior modulo one more than the maximum value
9243   // representable in the result type, so never warn for those.
9244   llvm::APSInt Left;
9245   if (LHS.get()->isValueDependent() ||
9246       LHSType->hasUnsignedIntegerRepresentation() ||
9247       !LHS.get()->EvaluateAsInt(Left, S.Context))
9248     return;
9249 
9250   // If LHS does not have a signed type and non-negative value
9251   // then, the behavior is undefined. Warn about it.
9252   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9253     S.DiagRuntimeBehavior(Loc, LHS.get(),
9254                           S.PDiag(diag::warn_shift_lhs_negative)
9255                             << LHS.get()->getSourceRange());
9256     return;
9257   }
9258 
9259   llvm::APInt ResultBits =
9260       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9261   if (LeftBits.uge(ResultBits))
9262     return;
9263   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9264   Result = Result.shl(Right);
9265 
9266   // Print the bit representation of the signed integer as an unsigned
9267   // hexadecimal number.
9268   SmallString<40> HexResult;
9269   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9270 
9271   // If we are only missing a sign bit, this is less likely to result in actual
9272   // bugs -- if the result is cast back to an unsigned type, it will have the
9273   // expected value. Thus we place this behind a different warning that can be
9274   // turned off separately if needed.
9275   if (LeftBits == ResultBits - 1) {
9276     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9277         << HexResult << LHSType
9278         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9279     return;
9280   }
9281 
9282   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9283     << HexResult.str() << Result.getMinSignedBits() << LHSType
9284     << Left.getBitWidth() << LHS.get()->getSourceRange()
9285     << RHS.get()->getSourceRange();
9286 }
9287 
9288 /// Return the resulting type when a vector is shifted
9289 ///        by a scalar or vector shift amount.
9290 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9291                                  SourceLocation Loc, bool IsCompAssign) {
9292   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9293   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9294       !LHS.get()->getType()->isVectorType()) {
9295     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9296       << RHS.get()->getType() << LHS.get()->getType()
9297       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9298     return QualType();
9299   }
9300 
9301   if (!IsCompAssign) {
9302     LHS = S.UsualUnaryConversions(LHS.get());
9303     if (LHS.isInvalid()) return QualType();
9304   }
9305 
9306   RHS = S.UsualUnaryConversions(RHS.get());
9307   if (RHS.isInvalid()) return QualType();
9308 
9309   QualType LHSType = LHS.get()->getType();
9310   // Note that LHS might be a scalar because the routine calls not only in
9311   // OpenCL case.
9312   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9313   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9314 
9315   // Note that RHS might not be a vector.
9316   QualType RHSType = RHS.get()->getType();
9317   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9318   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9319 
9320   // The operands need to be integers.
9321   if (!LHSEleType->isIntegerType()) {
9322     S.Diag(Loc, diag::err_typecheck_expect_int)
9323       << LHS.get()->getType() << LHS.get()->getSourceRange();
9324     return QualType();
9325   }
9326 
9327   if (!RHSEleType->isIntegerType()) {
9328     S.Diag(Loc, diag::err_typecheck_expect_int)
9329       << RHS.get()->getType() << RHS.get()->getSourceRange();
9330     return QualType();
9331   }
9332 
9333   if (!LHSVecTy) {
9334     assert(RHSVecTy);
9335     if (IsCompAssign)
9336       return RHSType;
9337     if (LHSEleType != RHSEleType) {
9338       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9339       LHSEleType = RHSEleType;
9340     }
9341     QualType VecTy =
9342         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9343     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9344     LHSType = VecTy;
9345   } else if (RHSVecTy) {
9346     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9347     // are applied component-wise. So if RHS is a vector, then ensure
9348     // that the number of elements is the same as LHS...
9349     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9350       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9351         << LHS.get()->getType() << RHS.get()->getType()
9352         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9353       return QualType();
9354     }
9355     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9356       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9357       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9358       if (LHSBT != RHSBT &&
9359           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9360         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9361             << LHS.get()->getType() << RHS.get()->getType()
9362             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9363       }
9364     }
9365   } else {
9366     // ...else expand RHS to match the number of elements in LHS.
9367     QualType VecTy =
9368       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9369     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9370   }
9371 
9372   return LHSType;
9373 }
9374 
9375 // C99 6.5.7
9376 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9377                                   SourceLocation Loc, BinaryOperatorKind Opc,
9378                                   bool IsCompAssign) {
9379   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9380 
9381   // Vector shifts promote their scalar inputs to vector type.
9382   if (LHS.get()->getType()->isVectorType() ||
9383       RHS.get()->getType()->isVectorType()) {
9384     if (LangOpts.ZVector) {
9385       // The shift operators for the z vector extensions work basically
9386       // like general shifts, except that neither the LHS nor the RHS is
9387       // allowed to be a "vector bool".
9388       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9389         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9390           return InvalidOperands(Loc, LHS, RHS);
9391       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9392         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9393           return InvalidOperands(Loc, LHS, RHS);
9394     }
9395     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9396   }
9397 
9398   // Shifts don't perform usual arithmetic conversions, they just do integer
9399   // promotions on each operand. C99 6.5.7p3
9400 
9401   // For the LHS, do usual unary conversions, but then reset them away
9402   // if this is a compound assignment.
9403   ExprResult OldLHS = LHS;
9404   LHS = UsualUnaryConversions(LHS.get());
9405   if (LHS.isInvalid())
9406     return QualType();
9407   QualType LHSType = LHS.get()->getType();
9408   if (IsCompAssign) LHS = OldLHS;
9409 
9410   // The RHS is simpler.
9411   RHS = UsualUnaryConversions(RHS.get());
9412   if (RHS.isInvalid())
9413     return QualType();
9414   QualType RHSType = RHS.get()->getType();
9415 
9416   // C99 6.5.7p2: Each of the operands shall have integer type.
9417   if (!LHSType->hasIntegerRepresentation() ||
9418       !RHSType->hasIntegerRepresentation())
9419     return InvalidOperands(Loc, LHS, RHS);
9420 
9421   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9422   // hasIntegerRepresentation() above instead of this.
9423   if (isScopedEnumerationType(LHSType) ||
9424       isScopedEnumerationType(RHSType)) {
9425     return InvalidOperands(Loc, LHS, RHS);
9426   }
9427   // Sanity-check shift operands
9428   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9429 
9430   // "The type of the result is that of the promoted left operand."
9431   return LHSType;
9432 }
9433 
9434 /// If two different enums are compared, raise a warning.
9435 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9436                                 Expr *RHS) {
9437   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9438   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9439 
9440   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9441   if (!LHSEnumType)
9442     return;
9443   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9444   if (!RHSEnumType)
9445     return;
9446 
9447   // Ignore anonymous enums.
9448   if (!LHSEnumType->getDecl()->getIdentifier() &&
9449       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9450     return;
9451   if (!RHSEnumType->getDecl()->getIdentifier() &&
9452       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9453     return;
9454 
9455   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9456     return;
9457 
9458   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9459       << LHSStrippedType << RHSStrippedType
9460       << LHS->getSourceRange() << RHS->getSourceRange();
9461 }
9462 
9463 /// Diagnose bad pointer comparisons.
9464 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9465                                               ExprResult &LHS, ExprResult &RHS,
9466                                               bool IsError) {
9467   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9468                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9469     << LHS.get()->getType() << RHS.get()->getType()
9470     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9471 }
9472 
9473 /// Returns false if the pointers are converted to a composite type,
9474 /// true otherwise.
9475 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9476                                            ExprResult &LHS, ExprResult &RHS) {
9477   // C++ [expr.rel]p2:
9478   //   [...] Pointer conversions (4.10) and qualification
9479   //   conversions (4.4) are performed on pointer operands (or on
9480   //   a pointer operand and a null pointer constant) to bring
9481   //   them to their composite pointer type. [...]
9482   //
9483   // C++ [expr.eq]p1 uses the same notion for (in)equality
9484   // comparisons of pointers.
9485 
9486   QualType LHSType = LHS.get()->getType();
9487   QualType RHSType = RHS.get()->getType();
9488   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9489          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9490 
9491   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9492   if (T.isNull()) {
9493     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9494         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9495       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9496     else
9497       S.InvalidOperands(Loc, LHS, RHS);
9498     return true;
9499   }
9500 
9501   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9502   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9503   return false;
9504 }
9505 
9506 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9507                                                     ExprResult &LHS,
9508                                                     ExprResult &RHS,
9509                                                     bool IsError) {
9510   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9511                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9512     << LHS.get()->getType() << RHS.get()->getType()
9513     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9514 }
9515 
9516 static bool isObjCObjectLiteral(ExprResult &E) {
9517   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9518   case Stmt::ObjCArrayLiteralClass:
9519   case Stmt::ObjCDictionaryLiteralClass:
9520   case Stmt::ObjCStringLiteralClass:
9521   case Stmt::ObjCBoxedExprClass:
9522     return true;
9523   default:
9524     // Note that ObjCBoolLiteral is NOT an object literal!
9525     return false;
9526   }
9527 }
9528 
9529 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9530   const ObjCObjectPointerType *Type =
9531     LHS->getType()->getAs<ObjCObjectPointerType>();
9532 
9533   // If this is not actually an Objective-C object, bail out.
9534   if (!Type)
9535     return false;
9536 
9537   // Get the LHS object's interface type.
9538   QualType InterfaceType = Type->getPointeeType();
9539 
9540   // If the RHS isn't an Objective-C object, bail out.
9541   if (!RHS->getType()->isObjCObjectPointerType())
9542     return false;
9543 
9544   // Try to find the -isEqual: method.
9545   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9546   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9547                                                       InterfaceType,
9548                                                       /*instance=*/true);
9549   if (!Method) {
9550     if (Type->isObjCIdType()) {
9551       // For 'id', just check the global pool.
9552       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9553                                                   /*receiverId=*/true);
9554     } else {
9555       // Check protocols.
9556       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9557                                              /*instance=*/true);
9558     }
9559   }
9560 
9561   if (!Method)
9562     return false;
9563 
9564   QualType T = Method->parameters()[0]->getType();
9565   if (!T->isObjCObjectPointerType())
9566     return false;
9567 
9568   QualType R = Method->getReturnType();
9569   if (!R->isScalarType())
9570     return false;
9571 
9572   return true;
9573 }
9574 
9575 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9576   FromE = FromE->IgnoreParenImpCasts();
9577   switch (FromE->getStmtClass()) {
9578     default:
9579       break;
9580     case Stmt::ObjCStringLiteralClass:
9581       // "string literal"
9582       return LK_String;
9583     case Stmt::ObjCArrayLiteralClass:
9584       // "array literal"
9585       return LK_Array;
9586     case Stmt::ObjCDictionaryLiteralClass:
9587       // "dictionary literal"
9588       return LK_Dictionary;
9589     case Stmt::BlockExprClass:
9590       return LK_Block;
9591     case Stmt::ObjCBoxedExprClass: {
9592       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9593       switch (Inner->getStmtClass()) {
9594         case Stmt::IntegerLiteralClass:
9595         case Stmt::FloatingLiteralClass:
9596         case Stmt::CharacterLiteralClass:
9597         case Stmt::ObjCBoolLiteralExprClass:
9598         case Stmt::CXXBoolLiteralExprClass:
9599           // "numeric literal"
9600           return LK_Numeric;
9601         case Stmt::ImplicitCastExprClass: {
9602           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9603           // Boolean literals can be represented by implicit casts.
9604           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9605             return LK_Numeric;
9606           break;
9607         }
9608         default:
9609           break;
9610       }
9611       return LK_Boxed;
9612     }
9613   }
9614   return LK_None;
9615 }
9616 
9617 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9618                                           ExprResult &LHS, ExprResult &RHS,
9619                                           BinaryOperator::Opcode Opc){
9620   Expr *Literal;
9621   Expr *Other;
9622   if (isObjCObjectLiteral(LHS)) {
9623     Literal = LHS.get();
9624     Other = RHS.get();
9625   } else {
9626     Literal = RHS.get();
9627     Other = LHS.get();
9628   }
9629 
9630   // Don't warn on comparisons against nil.
9631   Other = Other->IgnoreParenCasts();
9632   if (Other->isNullPointerConstant(S.getASTContext(),
9633                                    Expr::NPC_ValueDependentIsNotNull))
9634     return;
9635 
9636   // This should be kept in sync with warn_objc_literal_comparison.
9637   // LK_String should always be after the other literals, since it has its own
9638   // warning flag.
9639   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9640   assert(LiteralKind != Sema::LK_Block);
9641   if (LiteralKind == Sema::LK_None) {
9642     llvm_unreachable("Unknown Objective-C object literal kind");
9643   }
9644 
9645   if (LiteralKind == Sema::LK_String)
9646     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9647       << Literal->getSourceRange();
9648   else
9649     S.Diag(Loc, diag::warn_objc_literal_comparison)
9650       << LiteralKind << Literal->getSourceRange();
9651 
9652   if (BinaryOperator::isEqualityOp(Opc) &&
9653       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9654     SourceLocation Start = LHS.get()->getLocStart();
9655     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9656     CharSourceRange OpRange =
9657       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9658 
9659     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9660       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9661       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9662       << FixItHint::CreateInsertion(End, "]");
9663   }
9664 }
9665 
9666 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9667 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9668                                            ExprResult &RHS, SourceLocation Loc,
9669                                            BinaryOperatorKind Opc) {
9670   // Check that left hand side is !something.
9671   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9672   if (!UO || UO->getOpcode() != UO_LNot) return;
9673 
9674   // Only check if the right hand side is non-bool arithmetic type.
9675   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9676 
9677   // Make sure that the something in !something is not bool.
9678   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9679   if (SubExpr->isKnownToHaveBooleanValue()) return;
9680 
9681   // Emit warning.
9682   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9683   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9684       << Loc << IsBitwiseOp;
9685 
9686   // First note suggest !(x < y)
9687   SourceLocation FirstOpen = SubExpr->getLocStart();
9688   SourceLocation FirstClose = RHS.get()->getLocEnd();
9689   FirstClose = S.getLocForEndOfToken(FirstClose);
9690   if (FirstClose.isInvalid())
9691     FirstOpen = SourceLocation();
9692   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9693       << IsBitwiseOp
9694       << FixItHint::CreateInsertion(FirstOpen, "(")
9695       << FixItHint::CreateInsertion(FirstClose, ")");
9696 
9697   // Second note suggests (!x) < y
9698   SourceLocation SecondOpen = LHS.get()->getLocStart();
9699   SourceLocation SecondClose = LHS.get()->getLocEnd();
9700   SecondClose = S.getLocForEndOfToken(SecondClose);
9701   if (SecondClose.isInvalid())
9702     SecondOpen = SourceLocation();
9703   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9704       << FixItHint::CreateInsertion(SecondOpen, "(")
9705       << FixItHint::CreateInsertion(SecondClose, ")");
9706 }
9707 
9708 // Get the decl for a simple expression: a reference to a variable,
9709 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9710 static ValueDecl *getCompareDecl(Expr *E) {
9711   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9712     return DR->getDecl();
9713   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9714     if (Ivar->isFreeIvar())
9715       return Ivar->getDecl();
9716   }
9717   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9718     if (Mem->isImplicitAccess())
9719       return Mem->getMemberDecl();
9720   }
9721   return nullptr;
9722 }
9723 
9724 /// Diagnose some forms of syntactically-obvious tautological comparison.
9725 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9726                                            Expr *LHS, Expr *RHS,
9727                                            BinaryOperatorKind Opc) {
9728   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9729   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9730 
9731   QualType LHSType = LHS->getType();
9732   QualType RHSType = RHS->getType();
9733   if (LHSType->hasFloatingRepresentation() ||
9734       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9735       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9736       S.inTemplateInstantiation())
9737     return;
9738 
9739   // Comparisons between two array types are ill-formed for operator<=>, so
9740   // we shouldn't emit any additional warnings about it.
9741   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9742     return;
9743 
9744   // For non-floating point types, check for self-comparisons of the form
9745   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9746   // often indicate logic errors in the program.
9747   //
9748   // NOTE: Don't warn about comparison expressions resulting from macro
9749   // expansion. Also don't warn about comparisons which are only self
9750   // comparisons within a template instantiation. The warnings should catch
9751   // obvious cases in the definition of the template anyways. The idea is to
9752   // warn when the typed comparison operator will always evaluate to the same
9753   // result.
9754   ValueDecl *DL = getCompareDecl(LHSStripped);
9755   ValueDecl *DR = getCompareDecl(RHSStripped);
9756   if (DL && DR && declaresSameEntity(DL, DR)) {
9757     StringRef Result;
9758     switch (Opc) {
9759     case BO_EQ: case BO_LE: case BO_GE:
9760       Result = "true";
9761       break;
9762     case BO_NE: case BO_LT: case BO_GT:
9763       Result = "false";
9764       break;
9765     case BO_Cmp:
9766       Result = "'std::strong_ordering::equal'";
9767       break;
9768     default:
9769       break;
9770     }
9771     S.DiagRuntimeBehavior(Loc, nullptr,
9772                           S.PDiag(diag::warn_comparison_always)
9773                               << 0 /*self-comparison*/ << !Result.empty()
9774                               << Result);
9775   } else if (DL && DR &&
9776              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9777              !DL->isWeak() && !DR->isWeak()) {
9778     // What is it always going to evaluate to?
9779     StringRef Result;
9780     switch(Opc) {
9781     case BO_EQ: // e.g. array1 == array2
9782       Result = "false";
9783       break;
9784     case BO_NE: // e.g. array1 != array2
9785       Result = "true";
9786       break;
9787     default: // e.g. array1 <= array2
9788       // The best we can say is 'a constant'
9789       break;
9790     }
9791     S.DiagRuntimeBehavior(Loc, nullptr,
9792                           S.PDiag(diag::warn_comparison_always)
9793                               << 1 /*array comparison*/
9794                               << !Result.empty() << Result);
9795   }
9796 
9797   if (isa<CastExpr>(LHSStripped))
9798     LHSStripped = LHSStripped->IgnoreParenCasts();
9799   if (isa<CastExpr>(RHSStripped))
9800     RHSStripped = RHSStripped->IgnoreParenCasts();
9801 
9802   // Warn about comparisons against a string constant (unless the other
9803   // operand is null); the user probably wants strcmp.
9804   Expr *LiteralString = nullptr;
9805   Expr *LiteralStringStripped = nullptr;
9806   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9807       !RHSStripped->isNullPointerConstant(S.Context,
9808                                           Expr::NPC_ValueDependentIsNull)) {
9809     LiteralString = LHS;
9810     LiteralStringStripped = LHSStripped;
9811   } else if ((isa<StringLiteral>(RHSStripped) ||
9812               isa<ObjCEncodeExpr>(RHSStripped)) &&
9813              !LHSStripped->isNullPointerConstant(S.Context,
9814                                           Expr::NPC_ValueDependentIsNull)) {
9815     LiteralString = RHS;
9816     LiteralStringStripped = RHSStripped;
9817   }
9818 
9819   if (LiteralString) {
9820     S.DiagRuntimeBehavior(Loc, nullptr,
9821                           S.PDiag(diag::warn_stringcompare)
9822                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9823                               << LiteralString->getSourceRange());
9824   }
9825 }
9826 
9827 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9828   switch (CK) {
9829   default: {
9830 #ifndef NDEBUG
9831     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9832                  << "\n";
9833 #endif
9834     llvm_unreachable("unhandled cast kind");
9835   }
9836   case CK_UserDefinedConversion:
9837     return ICK_Identity;
9838   case CK_LValueToRValue:
9839     return ICK_Lvalue_To_Rvalue;
9840   case CK_ArrayToPointerDecay:
9841     return ICK_Array_To_Pointer;
9842   case CK_FunctionToPointerDecay:
9843     return ICK_Function_To_Pointer;
9844   case CK_IntegralCast:
9845     return ICK_Integral_Conversion;
9846   case CK_FloatingCast:
9847     return ICK_Floating_Conversion;
9848   case CK_IntegralToFloating:
9849   case CK_FloatingToIntegral:
9850     return ICK_Floating_Integral;
9851   case CK_IntegralComplexCast:
9852   case CK_FloatingComplexCast:
9853   case CK_FloatingComplexToIntegralComplex:
9854   case CK_IntegralComplexToFloatingComplex:
9855     return ICK_Complex_Conversion;
9856   case CK_FloatingComplexToReal:
9857   case CK_FloatingRealToComplex:
9858   case CK_IntegralComplexToReal:
9859   case CK_IntegralRealToComplex:
9860     return ICK_Complex_Real;
9861   }
9862 }
9863 
9864 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9865                                              QualType FromType,
9866                                              SourceLocation Loc) {
9867   // Check for a narrowing implicit conversion.
9868   StandardConversionSequence SCS;
9869   SCS.setAsIdentityConversion();
9870   SCS.setToType(0, FromType);
9871   SCS.setToType(1, ToType);
9872   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9873     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9874 
9875   APValue PreNarrowingValue;
9876   QualType PreNarrowingType;
9877   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9878                                PreNarrowingType,
9879                                /*IgnoreFloatToIntegralConversion*/ true)) {
9880   case NK_Dependent_Narrowing:
9881     // Implicit conversion to a narrower type, but the expression is
9882     // value-dependent so we can't tell whether it's actually narrowing.
9883   case NK_Not_Narrowing:
9884     return false;
9885 
9886   case NK_Constant_Narrowing:
9887     // Implicit conversion to a narrower type, and the value is not a constant
9888     // expression.
9889     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9890         << /*Constant*/ 1
9891         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9892     return true;
9893 
9894   case NK_Variable_Narrowing:
9895     // Implicit conversion to a narrower type, and the value is not a constant
9896     // expression.
9897   case NK_Type_Narrowing:
9898     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9899         << /*Constant*/ 0 << FromType << ToType;
9900     // TODO: It's not a constant expression, but what if the user intended it
9901     // to be? Can we produce notes to help them figure out why it isn't?
9902     return true;
9903   }
9904   llvm_unreachable("unhandled case in switch");
9905 }
9906 
9907 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
9908                                                          ExprResult &LHS,
9909                                                          ExprResult &RHS,
9910                                                          SourceLocation Loc) {
9911   using CCT = ComparisonCategoryType;
9912 
9913   QualType LHSType = LHS.get()->getType();
9914   QualType RHSType = RHS.get()->getType();
9915   // Dig out the original argument type and expression before implicit casts
9916   // were applied. These are the types/expressions we need to check the
9917   // [expr.spaceship] requirements against.
9918   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9919   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9920   QualType LHSStrippedType = LHSStripped.get()->getType();
9921   QualType RHSStrippedType = RHSStripped.get()->getType();
9922 
9923   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9924   // other is not, the program is ill-formed.
9925   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9926     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9927     return QualType();
9928   }
9929 
9930   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9931                     RHSStrippedType->isEnumeralType();
9932   if (NumEnumArgs == 1) {
9933     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9934     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9935     if (OtherTy->hasFloatingRepresentation()) {
9936       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9937       return QualType();
9938     }
9939   }
9940   if (NumEnumArgs == 2) {
9941     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9942     // type E, the operator yields the result of converting the operands
9943     // to the underlying type of E and applying <=> to the converted operands.
9944     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
9945       S.InvalidOperands(Loc, LHS, RHS);
9946       return QualType();
9947     }
9948     QualType IntType =
9949         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
9950     assert(IntType->isArithmeticType());
9951 
9952     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
9953     // promote the boolean type, and all other promotable integer types, to
9954     // avoid this.
9955     if (IntType->isPromotableIntegerType())
9956       IntType = S.Context.getPromotedIntegerType(IntType);
9957 
9958     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
9959     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
9960     LHSType = RHSType = IntType;
9961   }
9962 
9963   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
9964   // usual arithmetic conversions are applied to the operands.
9965   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9966   if (LHS.isInvalid() || RHS.isInvalid())
9967     return QualType();
9968   if (Type.isNull())
9969     return S.InvalidOperands(Loc, LHS, RHS);
9970   assert(Type->isArithmeticType() || Type->isEnumeralType());
9971 
9972   bool HasNarrowing = checkThreeWayNarrowingConversion(
9973       S, Type, LHS.get(), LHSType, LHS.get()->getLocStart());
9974   HasNarrowing |= checkThreeWayNarrowingConversion(
9975       S, Type, RHS.get(), RHSType, RHS.get()->getLocStart());
9976   if (HasNarrowing)
9977     return QualType();
9978 
9979   assert(!Type.isNull() && "composite type for <=> has not been set");
9980 
9981   auto TypeKind = [&]() {
9982     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
9983       if (CT->getElementType()->hasFloatingRepresentation())
9984         return CCT::WeakEquality;
9985       return CCT::StrongEquality;
9986     }
9987     if (Type->isIntegralOrEnumerationType())
9988       return CCT::StrongOrdering;
9989     if (Type->hasFloatingRepresentation())
9990       return CCT::PartialOrdering;
9991     llvm_unreachable("other types are unimplemented");
9992   }();
9993 
9994   return S.CheckComparisonCategoryType(TypeKind, Loc);
9995 }
9996 
9997 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9998                                                  ExprResult &RHS,
9999                                                  SourceLocation Loc,
10000                                                  BinaryOperatorKind Opc) {
10001   if (Opc == BO_Cmp)
10002     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10003 
10004   // C99 6.5.8p3 / C99 6.5.9p4
10005   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10006   if (LHS.isInvalid() || RHS.isInvalid())
10007     return QualType();
10008   if (Type.isNull())
10009     return S.InvalidOperands(Loc, LHS, RHS);
10010   assert(Type->isArithmeticType() || Type->isEnumeralType());
10011 
10012   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10013 
10014   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10015     return S.InvalidOperands(Loc, LHS, RHS);
10016 
10017   // Check for comparisons of floating point operands using != and ==.
10018   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10019     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10020 
10021   // The result of comparisons is 'bool' in C++, 'int' in C.
10022   return S.Context.getLogicalOperationType();
10023 }
10024 
10025 // C99 6.5.8, C++ [expr.rel]
10026 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10027                                     SourceLocation Loc,
10028                                     BinaryOperatorKind Opc) {
10029   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10030   bool IsThreeWay = Opc == BO_Cmp;
10031   auto IsAnyPointerType = [](ExprResult E) {
10032     QualType Ty = E.get()->getType();
10033     return Ty->isPointerType() || Ty->isMemberPointerType();
10034   };
10035 
10036   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10037   // type, array-to-pointer, ..., conversions are performed on both operands to
10038   // bring them to their composite type.
10039   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10040   // any type-related checks.
10041   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10042     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10043     if (LHS.isInvalid())
10044       return QualType();
10045     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10046     if (RHS.isInvalid())
10047       return QualType();
10048   } else {
10049     LHS = DefaultLvalueConversion(LHS.get());
10050     if (LHS.isInvalid())
10051       return QualType();
10052     RHS = DefaultLvalueConversion(RHS.get());
10053     if (RHS.isInvalid())
10054       return QualType();
10055   }
10056 
10057   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10058 
10059   // Handle vector comparisons separately.
10060   if (LHS.get()->getType()->isVectorType() ||
10061       RHS.get()->getType()->isVectorType())
10062     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10063 
10064   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10065   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10066 
10067   QualType LHSType = LHS.get()->getType();
10068   QualType RHSType = RHS.get()->getType();
10069   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10070       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10071     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10072 
10073   const Expr::NullPointerConstantKind LHSNullKind =
10074       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10075   const Expr::NullPointerConstantKind RHSNullKind =
10076       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10077   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10078   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10079 
10080   auto computeResultTy = [&]() {
10081     if (Opc != BO_Cmp)
10082       return Context.getLogicalOperationType();
10083     assert(getLangOpts().CPlusPlus);
10084     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10085 
10086     QualType CompositeTy = LHS.get()->getType();
10087     assert(!CompositeTy->isReferenceType());
10088 
10089     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10090       return CheckComparisonCategoryType(Kind, Loc);
10091     };
10092 
10093     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10094     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10095     // result is of type std::strong_equality
10096     if (CompositeTy->isFunctionPointerType() ||
10097         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10098       // FIXME: consider making the function pointer case produce
10099       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10100       // and direction polls
10101       return buildResultTy(ComparisonCategoryType::StrongEquality);
10102 
10103     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10104     // pointer type, p <=> q is of type std::strong_ordering.
10105     if (CompositeTy->isPointerType()) {
10106       // P0946R0: Comparisons between a null pointer constant and an object
10107       // pointer result in std::strong_equality
10108       if (LHSIsNull != RHSIsNull)
10109         return buildResultTy(ComparisonCategoryType::StrongEquality);
10110       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10111     }
10112     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10113     // TODO: Extend support for operator<=> to ObjC types.
10114     return InvalidOperands(Loc, LHS, RHS);
10115   };
10116 
10117 
10118   if (!IsRelational && LHSIsNull != RHSIsNull) {
10119     bool IsEquality = Opc == BO_EQ;
10120     if (RHSIsNull)
10121       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10122                                    RHS.get()->getSourceRange());
10123     else
10124       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10125                                    LHS.get()->getSourceRange());
10126   }
10127 
10128   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10129       (RHSType->isIntegerType() && !RHSIsNull)) {
10130     // Skip normal pointer conversion checks in this case; we have better
10131     // diagnostics for this below.
10132   } else if (getLangOpts().CPlusPlus) {
10133     // Equality comparison of a function pointer to a void pointer is invalid,
10134     // but we allow it as an extension.
10135     // FIXME: If we really want to allow this, should it be part of composite
10136     // pointer type computation so it works in conditionals too?
10137     if (!IsRelational &&
10138         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10139          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10140       // This is a gcc extension compatibility comparison.
10141       // In a SFINAE context, we treat this as a hard error to maintain
10142       // conformance with the C++ standard.
10143       diagnoseFunctionPointerToVoidComparison(
10144           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10145 
10146       if (isSFINAEContext())
10147         return QualType();
10148 
10149       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10150       return computeResultTy();
10151     }
10152 
10153     // C++ [expr.eq]p2:
10154     //   If at least one operand is a pointer [...] bring them to their
10155     //   composite pointer type.
10156     // C++ [expr.spaceship]p6
10157     //  If at least one of the operands is of pointer type, [...] bring them
10158     //  to their composite pointer type.
10159     // C++ [expr.rel]p2:
10160     //   If both operands are pointers, [...] bring them to their composite
10161     //   pointer type.
10162     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10163             (IsRelational ? 2 : 1) &&
10164         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10165                                          RHSType->isObjCObjectPointerType()))) {
10166       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10167         return QualType();
10168       return computeResultTy();
10169     }
10170   } else if (LHSType->isPointerType() &&
10171              RHSType->isPointerType()) { // C99 6.5.8p2
10172     // All of the following pointer-related warnings are GCC extensions, except
10173     // when handling null pointer constants.
10174     QualType LCanPointeeTy =
10175       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10176     QualType RCanPointeeTy =
10177       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10178 
10179     // C99 6.5.9p2 and C99 6.5.8p2
10180     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10181                                    RCanPointeeTy.getUnqualifiedType())) {
10182       // Valid unless a relational comparison of function pointers
10183       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10184         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10185           << LHSType << RHSType << LHS.get()->getSourceRange()
10186           << RHS.get()->getSourceRange();
10187       }
10188     } else if (!IsRelational &&
10189                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10190       // Valid unless comparison between non-null pointer and function pointer
10191       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10192           && !LHSIsNull && !RHSIsNull)
10193         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10194                                                 /*isError*/false);
10195     } else {
10196       // Invalid
10197       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10198     }
10199     if (LCanPointeeTy != RCanPointeeTy) {
10200       // Treat NULL constant as a special case in OpenCL.
10201       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10202         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10203         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10204           Diag(Loc,
10205                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10206               << LHSType << RHSType << 0 /* comparison */
10207               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10208         }
10209       }
10210       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10211       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10212       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10213                                                : CK_BitCast;
10214       if (LHSIsNull && !RHSIsNull)
10215         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10216       else
10217         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10218     }
10219     return computeResultTy();
10220   }
10221 
10222   if (getLangOpts().CPlusPlus) {
10223     // C++ [expr.eq]p4:
10224     //   Two operands of type std::nullptr_t or one operand of type
10225     //   std::nullptr_t and the other a null pointer constant compare equal.
10226     if (!IsRelational && LHSIsNull && RHSIsNull) {
10227       if (LHSType->isNullPtrType()) {
10228         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10229         return computeResultTy();
10230       }
10231       if (RHSType->isNullPtrType()) {
10232         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10233         return computeResultTy();
10234       }
10235     }
10236 
10237     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10238     // These aren't covered by the composite pointer type rules.
10239     if (!IsRelational && RHSType->isNullPtrType() &&
10240         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10241       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10242       return computeResultTy();
10243     }
10244     if (!IsRelational && LHSType->isNullPtrType() &&
10245         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10246       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10247       return computeResultTy();
10248     }
10249 
10250     if (IsRelational &&
10251         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10252          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10253       // HACK: Relational comparison of nullptr_t against a pointer type is
10254       // invalid per DR583, but we allow it within std::less<> and friends,
10255       // since otherwise common uses of it break.
10256       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10257       // friends to have std::nullptr_t overload candidates.
10258       DeclContext *DC = CurContext;
10259       if (isa<FunctionDecl>(DC))
10260         DC = DC->getParent();
10261       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10262         if (CTSD->isInStdNamespace() &&
10263             llvm::StringSwitch<bool>(CTSD->getName())
10264                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10265                 .Default(false)) {
10266           if (RHSType->isNullPtrType())
10267             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10268           else
10269             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10270           return computeResultTy();
10271         }
10272       }
10273     }
10274 
10275     // C++ [expr.eq]p2:
10276     //   If at least one operand is a pointer to member, [...] bring them to
10277     //   their composite pointer type.
10278     if (!IsRelational &&
10279         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10280       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10281         return QualType();
10282       else
10283         return computeResultTy();
10284     }
10285   }
10286 
10287   // Handle block pointer types.
10288   if (!IsRelational && LHSType->isBlockPointerType() &&
10289       RHSType->isBlockPointerType()) {
10290     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10291     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10292 
10293     if (!LHSIsNull && !RHSIsNull &&
10294         !Context.typesAreCompatible(lpointee, rpointee)) {
10295       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10296         << LHSType << RHSType << LHS.get()->getSourceRange()
10297         << RHS.get()->getSourceRange();
10298     }
10299     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10300     return computeResultTy();
10301   }
10302 
10303   // Allow block pointers to be compared with null pointer constants.
10304   if (!IsRelational
10305       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10306           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10307     if (!LHSIsNull && !RHSIsNull) {
10308       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10309              ->getPointeeType()->isVoidType())
10310             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10311                 ->getPointeeType()->isVoidType())))
10312         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10313           << LHSType << RHSType << LHS.get()->getSourceRange()
10314           << RHS.get()->getSourceRange();
10315     }
10316     if (LHSIsNull && !RHSIsNull)
10317       LHS = ImpCastExprToType(LHS.get(), RHSType,
10318                               RHSType->isPointerType() ? CK_BitCast
10319                                 : CK_AnyPointerToBlockPointerCast);
10320     else
10321       RHS = ImpCastExprToType(RHS.get(), LHSType,
10322                               LHSType->isPointerType() ? CK_BitCast
10323                                 : CK_AnyPointerToBlockPointerCast);
10324     return computeResultTy();
10325   }
10326 
10327   if (LHSType->isObjCObjectPointerType() ||
10328       RHSType->isObjCObjectPointerType()) {
10329     const PointerType *LPT = LHSType->getAs<PointerType>();
10330     const PointerType *RPT = RHSType->getAs<PointerType>();
10331     if (LPT || RPT) {
10332       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10333       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10334 
10335       if (!LPtrToVoid && !RPtrToVoid &&
10336           !Context.typesAreCompatible(LHSType, RHSType)) {
10337         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10338                                           /*isError*/false);
10339       }
10340       if (LHSIsNull && !RHSIsNull) {
10341         Expr *E = LHS.get();
10342         if (getLangOpts().ObjCAutoRefCount)
10343           CheckObjCConversion(SourceRange(), RHSType, E,
10344                               CCK_ImplicitConversion);
10345         LHS = ImpCastExprToType(E, RHSType,
10346                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10347       }
10348       else {
10349         Expr *E = RHS.get();
10350         if (getLangOpts().ObjCAutoRefCount)
10351           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10352                               /*Diagnose=*/true,
10353                               /*DiagnoseCFAudited=*/false, Opc);
10354         RHS = ImpCastExprToType(E, LHSType,
10355                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10356       }
10357       return computeResultTy();
10358     }
10359     if (LHSType->isObjCObjectPointerType() &&
10360         RHSType->isObjCObjectPointerType()) {
10361       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10362         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10363                                           /*isError*/false);
10364       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10365         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10366 
10367       if (LHSIsNull && !RHSIsNull)
10368         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10369       else
10370         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10371       return computeResultTy();
10372     }
10373 
10374     if (!IsRelational && LHSType->isBlockPointerType() &&
10375         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10376       LHS = ImpCastExprToType(LHS.get(), RHSType,
10377                               CK_BlockPointerToObjCPointerCast);
10378       return computeResultTy();
10379     } else if (!IsRelational &&
10380                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10381                RHSType->isBlockPointerType()) {
10382       RHS = ImpCastExprToType(RHS.get(), LHSType,
10383                               CK_BlockPointerToObjCPointerCast);
10384       return computeResultTy();
10385     }
10386   }
10387   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10388       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10389     unsigned DiagID = 0;
10390     bool isError = false;
10391     if (LangOpts.DebuggerSupport) {
10392       // Under a debugger, allow the comparison of pointers to integers,
10393       // since users tend to want to compare addresses.
10394     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10395                (RHSIsNull && RHSType->isIntegerType())) {
10396       if (IsRelational) {
10397         isError = getLangOpts().CPlusPlus;
10398         DiagID =
10399           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10400                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10401       }
10402     } else if (getLangOpts().CPlusPlus) {
10403       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10404       isError = true;
10405     } else if (IsRelational)
10406       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10407     else
10408       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10409 
10410     if (DiagID) {
10411       Diag(Loc, DiagID)
10412         << LHSType << RHSType << LHS.get()->getSourceRange()
10413         << RHS.get()->getSourceRange();
10414       if (isError)
10415         return QualType();
10416     }
10417 
10418     if (LHSType->isIntegerType())
10419       LHS = ImpCastExprToType(LHS.get(), RHSType,
10420                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10421     else
10422       RHS = ImpCastExprToType(RHS.get(), LHSType,
10423                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10424     return computeResultTy();
10425   }
10426 
10427   // Handle block pointers.
10428   if (!IsRelational && RHSIsNull
10429       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10430     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10431     return computeResultTy();
10432   }
10433   if (!IsRelational && LHSIsNull
10434       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10435     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10436     return computeResultTy();
10437   }
10438 
10439   if (getLangOpts().OpenCLVersion >= 200) {
10440     if (LHSIsNull && RHSType->isQueueT()) {
10441       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10442       return computeResultTy();
10443     }
10444 
10445     if (LHSType->isQueueT() && RHSIsNull) {
10446       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10447       return computeResultTy();
10448     }
10449   }
10450 
10451   return InvalidOperands(Loc, LHS, RHS);
10452 }
10453 
10454 // Return a signed ext_vector_type that is of identical size and number of
10455 // elements. For floating point vectors, return an integer type of identical
10456 // size and number of elements. In the non ext_vector_type case, search from
10457 // the largest type to the smallest type to avoid cases where long long == long,
10458 // where long gets picked over long long.
10459 QualType Sema::GetSignedVectorType(QualType V) {
10460   const VectorType *VTy = V->getAs<VectorType>();
10461   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10462 
10463   if (isa<ExtVectorType>(VTy)) {
10464     if (TypeSize == Context.getTypeSize(Context.CharTy))
10465       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10466     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10467       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10468     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10469       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10470     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10471       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10472     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10473            "Unhandled vector element size in vector compare");
10474     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10475   }
10476 
10477   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10478     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10479                                  VectorType::GenericVector);
10480   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10481     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10482                                  VectorType::GenericVector);
10483   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10484     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10485                                  VectorType::GenericVector);
10486   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10487     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10488                                  VectorType::GenericVector);
10489   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10490          "Unhandled vector element size in vector compare");
10491   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10492                                VectorType::GenericVector);
10493 }
10494 
10495 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10496 /// operates on extended vector types.  Instead of producing an IntTy result,
10497 /// like a scalar comparison, a vector comparison produces a vector of integer
10498 /// types.
10499 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10500                                           SourceLocation Loc,
10501                                           BinaryOperatorKind Opc) {
10502   // Check to make sure we're operating on vectors of the same type and width,
10503   // Allowing one side to be a scalar of element type.
10504   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10505                               /*AllowBothBool*/true,
10506                               /*AllowBoolConversions*/getLangOpts().ZVector);
10507   if (vType.isNull())
10508     return vType;
10509 
10510   QualType LHSType = LHS.get()->getType();
10511 
10512   // If AltiVec, the comparison results in a numeric type, i.e.
10513   // bool for C++, int for C
10514   if (getLangOpts().AltiVec &&
10515       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10516     return Context.getLogicalOperationType();
10517 
10518   // For non-floating point types, check for self-comparisons of the form
10519   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10520   // often indicate logic errors in the program.
10521   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10522 
10523   // Check for comparisons of floating point operands using != and ==.
10524   if (BinaryOperator::isEqualityOp(Opc) &&
10525       LHSType->hasFloatingRepresentation()) {
10526     assert(RHS.get()->getType()->hasFloatingRepresentation());
10527     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10528   }
10529 
10530   // Return a signed type for the vector.
10531   return GetSignedVectorType(vType);
10532 }
10533 
10534 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10535                                           SourceLocation Loc) {
10536   // Ensure that either both operands are of the same vector type, or
10537   // one operand is of a vector type and the other is of its element type.
10538   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10539                                        /*AllowBothBool*/true,
10540                                        /*AllowBoolConversions*/false);
10541   if (vType.isNull())
10542     return InvalidOperands(Loc, LHS, RHS);
10543   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10544       vType->hasFloatingRepresentation())
10545     return InvalidOperands(Loc, LHS, RHS);
10546   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10547   //        usage of the logical operators && and || with vectors in C. This
10548   //        check could be notionally dropped.
10549   if (!getLangOpts().CPlusPlus &&
10550       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10551     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10552 
10553   return GetSignedVectorType(LHS.get()->getType());
10554 }
10555 
10556 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10557                                            SourceLocation Loc,
10558                                            BinaryOperatorKind Opc) {
10559   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10560 
10561   bool IsCompAssign =
10562       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10563 
10564   if (LHS.get()->getType()->isVectorType() ||
10565       RHS.get()->getType()->isVectorType()) {
10566     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10567         RHS.get()->getType()->hasIntegerRepresentation())
10568       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10569                         /*AllowBothBool*/true,
10570                         /*AllowBoolConversions*/getLangOpts().ZVector);
10571     return InvalidOperands(Loc, LHS, RHS);
10572   }
10573 
10574   if (Opc == BO_And)
10575     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10576 
10577   ExprResult LHSResult = LHS, RHSResult = RHS;
10578   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10579                                                  IsCompAssign);
10580   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10581     return QualType();
10582   LHS = LHSResult.get();
10583   RHS = RHSResult.get();
10584 
10585   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10586     return compType;
10587   return InvalidOperands(Loc, LHS, RHS);
10588 }
10589 
10590 // C99 6.5.[13,14]
10591 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10592                                            SourceLocation Loc,
10593                                            BinaryOperatorKind Opc) {
10594   // Check vector operands differently.
10595   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10596     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10597 
10598   // Diagnose cases where the user write a logical and/or but probably meant a
10599   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10600   // is a constant.
10601   if (LHS.get()->getType()->isIntegerType() &&
10602       !LHS.get()->getType()->isBooleanType() &&
10603       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10604       // Don't warn in macros or template instantiations.
10605       !Loc.isMacroID() && !inTemplateInstantiation()) {
10606     // If the RHS can be constant folded, and if it constant folds to something
10607     // that isn't 0 or 1 (which indicate a potential logical operation that
10608     // happened to fold to true/false) then warn.
10609     // Parens on the RHS are ignored.
10610     llvm::APSInt Result;
10611     if (RHS.get()->EvaluateAsInt(Result, Context))
10612       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10613            !RHS.get()->getExprLoc().isMacroID()) ||
10614           (Result != 0 && Result != 1)) {
10615         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10616           << RHS.get()->getSourceRange()
10617           << (Opc == BO_LAnd ? "&&" : "||");
10618         // Suggest replacing the logical operator with the bitwise version
10619         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10620             << (Opc == BO_LAnd ? "&" : "|")
10621             << FixItHint::CreateReplacement(SourceRange(
10622                                                  Loc, getLocForEndOfToken(Loc)),
10623                                             Opc == BO_LAnd ? "&" : "|");
10624         if (Opc == BO_LAnd)
10625           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10626           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10627               << FixItHint::CreateRemoval(
10628                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10629                               RHS.get()->getLocEnd()));
10630       }
10631   }
10632 
10633   if (!Context.getLangOpts().CPlusPlus) {
10634     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10635     // not operate on the built-in scalar and vector float types.
10636     if (Context.getLangOpts().OpenCL &&
10637         Context.getLangOpts().OpenCLVersion < 120) {
10638       if (LHS.get()->getType()->isFloatingType() ||
10639           RHS.get()->getType()->isFloatingType())
10640         return InvalidOperands(Loc, LHS, RHS);
10641     }
10642 
10643     LHS = UsualUnaryConversions(LHS.get());
10644     if (LHS.isInvalid())
10645       return QualType();
10646 
10647     RHS = UsualUnaryConversions(RHS.get());
10648     if (RHS.isInvalid())
10649       return QualType();
10650 
10651     if (!LHS.get()->getType()->isScalarType() ||
10652         !RHS.get()->getType()->isScalarType())
10653       return InvalidOperands(Loc, LHS, RHS);
10654 
10655     return Context.IntTy;
10656   }
10657 
10658   // The following is safe because we only use this method for
10659   // non-overloadable operands.
10660 
10661   // C++ [expr.log.and]p1
10662   // C++ [expr.log.or]p1
10663   // The operands are both contextually converted to type bool.
10664   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10665   if (LHSRes.isInvalid())
10666     return InvalidOperands(Loc, LHS, RHS);
10667   LHS = LHSRes;
10668 
10669   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10670   if (RHSRes.isInvalid())
10671     return InvalidOperands(Loc, LHS, RHS);
10672   RHS = RHSRes;
10673 
10674   // C++ [expr.log.and]p2
10675   // C++ [expr.log.or]p2
10676   // The result is a bool.
10677   return Context.BoolTy;
10678 }
10679 
10680 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10681   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10682   if (!ME) return false;
10683   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10684   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10685       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10686   if (!Base) return false;
10687   return Base->getMethodDecl() != nullptr;
10688 }
10689 
10690 /// Is the given expression (which must be 'const') a reference to a
10691 /// variable which was originally non-const, but which has become
10692 /// 'const' due to being captured within a block?
10693 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10694 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10695   assert(E->isLValue() && E->getType().isConstQualified());
10696   E = E->IgnoreParens();
10697 
10698   // Must be a reference to a declaration from an enclosing scope.
10699   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10700   if (!DRE) return NCCK_None;
10701   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10702 
10703   // The declaration must be a variable which is not declared 'const'.
10704   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10705   if (!var) return NCCK_None;
10706   if (var->getType().isConstQualified()) return NCCK_None;
10707   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10708 
10709   // Decide whether the first capture was for a block or a lambda.
10710   DeclContext *DC = S.CurContext, *Prev = nullptr;
10711   // Decide whether the first capture was for a block or a lambda.
10712   while (DC) {
10713     // For init-capture, it is possible that the variable belongs to the
10714     // template pattern of the current context.
10715     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10716       if (var->isInitCapture() &&
10717           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10718         break;
10719     if (DC == var->getDeclContext())
10720       break;
10721     Prev = DC;
10722     DC = DC->getParent();
10723   }
10724   // Unless we have an init-capture, we've gone one step too far.
10725   if (!var->isInitCapture())
10726     DC = Prev;
10727   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10728 }
10729 
10730 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10731   Ty = Ty.getNonReferenceType();
10732   if (IsDereference && Ty->isPointerType())
10733     Ty = Ty->getPointeeType();
10734   return !Ty.isConstQualified();
10735 }
10736 
10737 // Update err_typecheck_assign_const and note_typecheck_assign_const
10738 // when this enum is changed.
10739 enum {
10740   ConstFunction,
10741   ConstVariable,
10742   ConstMember,
10743   ConstMethod,
10744   NestedConstMember,
10745   ConstUnknown,  // Keep as last element
10746 };
10747 
10748 /// Emit the "read-only variable not assignable" error and print notes to give
10749 /// more information about why the variable is not assignable, such as pointing
10750 /// to the declaration of a const variable, showing that a method is const, or
10751 /// that the function is returning a const reference.
10752 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10753                                     SourceLocation Loc) {
10754   SourceRange ExprRange = E->getSourceRange();
10755 
10756   // Only emit one error on the first const found.  All other consts will emit
10757   // a note to the error.
10758   bool DiagnosticEmitted = false;
10759 
10760   // Track if the current expression is the result of a dereference, and if the
10761   // next checked expression is the result of a dereference.
10762   bool IsDereference = false;
10763   bool NextIsDereference = false;
10764 
10765   // Loop to process MemberExpr chains.
10766   while (true) {
10767     IsDereference = NextIsDereference;
10768 
10769     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10770     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10771       NextIsDereference = ME->isArrow();
10772       const ValueDecl *VD = ME->getMemberDecl();
10773       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10774         // Mutable fields can be modified even if the class is const.
10775         if (Field->isMutable()) {
10776           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10777           break;
10778         }
10779 
10780         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10781           if (!DiagnosticEmitted) {
10782             S.Diag(Loc, diag::err_typecheck_assign_const)
10783                 << ExprRange << ConstMember << false /*static*/ << Field
10784                 << Field->getType();
10785             DiagnosticEmitted = true;
10786           }
10787           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10788               << ConstMember << false /*static*/ << Field << Field->getType()
10789               << Field->getSourceRange();
10790         }
10791         E = ME->getBase();
10792         continue;
10793       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10794         if (VDecl->getType().isConstQualified()) {
10795           if (!DiagnosticEmitted) {
10796             S.Diag(Loc, diag::err_typecheck_assign_const)
10797                 << ExprRange << ConstMember << true /*static*/ << VDecl
10798                 << VDecl->getType();
10799             DiagnosticEmitted = true;
10800           }
10801           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10802               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10803               << VDecl->getSourceRange();
10804         }
10805         // Static fields do not inherit constness from parents.
10806         break;
10807       }
10808       break; // End MemberExpr
10809     } else if (const ArraySubscriptExpr *ASE =
10810                    dyn_cast<ArraySubscriptExpr>(E)) {
10811       E = ASE->getBase()->IgnoreParenImpCasts();
10812       continue;
10813     } else if (const ExtVectorElementExpr *EVE =
10814                    dyn_cast<ExtVectorElementExpr>(E)) {
10815       E = EVE->getBase()->IgnoreParenImpCasts();
10816       continue;
10817     }
10818     break;
10819   }
10820 
10821   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10822     // Function calls
10823     const FunctionDecl *FD = CE->getDirectCallee();
10824     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10825       if (!DiagnosticEmitted) {
10826         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10827                                                       << ConstFunction << FD;
10828         DiagnosticEmitted = true;
10829       }
10830       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10831              diag::note_typecheck_assign_const)
10832           << ConstFunction << FD << FD->getReturnType()
10833           << FD->getReturnTypeSourceRange();
10834     }
10835   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10836     // Point to variable declaration.
10837     if (const ValueDecl *VD = DRE->getDecl()) {
10838       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10839         if (!DiagnosticEmitted) {
10840           S.Diag(Loc, diag::err_typecheck_assign_const)
10841               << ExprRange << ConstVariable << VD << VD->getType();
10842           DiagnosticEmitted = true;
10843         }
10844         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10845             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10846       }
10847     }
10848   } else if (isa<CXXThisExpr>(E)) {
10849     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10850       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10851         if (MD->isConst()) {
10852           if (!DiagnosticEmitted) {
10853             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10854                                                           << ConstMethod << MD;
10855             DiagnosticEmitted = true;
10856           }
10857           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10858               << ConstMethod << MD << MD->getSourceRange();
10859         }
10860       }
10861     }
10862   }
10863 
10864   if (DiagnosticEmitted)
10865     return;
10866 
10867   // Can't determine a more specific message, so display the generic error.
10868   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10869 }
10870 
10871 enum OriginalExprKind {
10872   OEK_Variable,
10873   OEK_Member,
10874   OEK_LValue
10875 };
10876 
10877 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10878                                          const RecordType *Ty,
10879                                          SourceLocation Loc, SourceRange Range,
10880                                          OriginalExprKind OEK,
10881                                          bool &DiagnosticEmitted,
10882                                          bool IsNested = false) {
10883   // We walk the record hierarchy breadth-first to ensure that we print
10884   // diagnostics in field nesting order.
10885   // First, check every field for constness.
10886   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10887     if (Field->getType().isConstQualified()) {
10888       if (!DiagnosticEmitted) {
10889         S.Diag(Loc, diag::err_typecheck_assign_const)
10890             << Range << NestedConstMember << OEK << VD
10891             << IsNested << Field;
10892         DiagnosticEmitted = true;
10893       }
10894       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10895           << NestedConstMember << IsNested << Field
10896           << Field->getType() << Field->getSourceRange();
10897     }
10898   }
10899   // Then, recurse.
10900   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10901     QualType FTy = Field->getType();
10902     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10903       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10904                                    OEK, DiagnosticEmitted, true);
10905   }
10906 }
10907 
10908 /// Emit an error for the case where a record we are trying to assign to has a
10909 /// const-qualified field somewhere in its hierarchy.
10910 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10911                                          SourceLocation Loc) {
10912   QualType Ty = E->getType();
10913   assert(Ty->isRecordType() && "lvalue was not record?");
10914   SourceRange Range = E->getSourceRange();
10915   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10916   bool DiagEmitted = false;
10917 
10918   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10919     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10920             Range, OEK_Member, DiagEmitted);
10921   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10922     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10923             Range, OEK_Variable, DiagEmitted);
10924   else
10925     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10926             Range, OEK_LValue, DiagEmitted);
10927   if (!DiagEmitted)
10928     DiagnoseConstAssignment(S, E, Loc);
10929 }
10930 
10931 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10932 /// emit an error and return true.  If so, return false.
10933 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10934   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10935 
10936   S.CheckShadowingDeclModification(E, Loc);
10937 
10938   SourceLocation OrigLoc = Loc;
10939   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10940                                                               &Loc);
10941   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10942     IsLV = Expr::MLV_InvalidMessageExpression;
10943   if (IsLV == Expr::MLV_Valid)
10944     return false;
10945 
10946   unsigned DiagID = 0;
10947   bool NeedType = false;
10948   switch (IsLV) { // C99 6.5.16p2
10949   case Expr::MLV_ConstQualified:
10950     // Use a specialized diagnostic when we're assigning to an object
10951     // from an enclosing function or block.
10952     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10953       if (NCCK == NCCK_Block)
10954         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10955       else
10956         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10957       break;
10958     }
10959 
10960     // In ARC, use some specialized diagnostics for occasions where we
10961     // infer 'const'.  These are always pseudo-strong variables.
10962     if (S.getLangOpts().ObjCAutoRefCount) {
10963       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10964       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10965         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10966 
10967         // Use the normal diagnostic if it's pseudo-__strong but the
10968         // user actually wrote 'const'.
10969         if (var->isARCPseudoStrong() &&
10970             (!var->getTypeSourceInfo() ||
10971              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10972           // There are two pseudo-strong cases:
10973           //  - self
10974           ObjCMethodDecl *method = S.getCurMethodDecl();
10975           if (method && var == method->getSelfDecl())
10976             DiagID = method->isClassMethod()
10977               ? diag::err_typecheck_arc_assign_self_class_method
10978               : diag::err_typecheck_arc_assign_self;
10979 
10980           //  - fast enumeration variables
10981           else
10982             DiagID = diag::err_typecheck_arr_assign_enumeration;
10983 
10984           SourceRange Assign;
10985           if (Loc != OrigLoc)
10986             Assign = SourceRange(OrigLoc, OrigLoc);
10987           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10988           // We need to preserve the AST regardless, so migration tool
10989           // can do its job.
10990           return false;
10991         }
10992       }
10993     }
10994 
10995     // If none of the special cases above are triggered, then this is a
10996     // simple const assignment.
10997     if (DiagID == 0) {
10998       DiagnoseConstAssignment(S, E, Loc);
10999       return true;
11000     }
11001 
11002     break;
11003   case Expr::MLV_ConstAddrSpace:
11004     DiagnoseConstAssignment(S, E, Loc);
11005     return true;
11006   case Expr::MLV_ConstQualifiedField:
11007     DiagnoseRecursiveConstFields(S, E, Loc);
11008     return true;
11009   case Expr::MLV_ArrayType:
11010   case Expr::MLV_ArrayTemporary:
11011     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11012     NeedType = true;
11013     break;
11014   case Expr::MLV_NotObjectType:
11015     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11016     NeedType = true;
11017     break;
11018   case Expr::MLV_LValueCast:
11019     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11020     break;
11021   case Expr::MLV_Valid:
11022     llvm_unreachable("did not take early return for MLV_Valid");
11023   case Expr::MLV_InvalidExpression:
11024   case Expr::MLV_MemberFunction:
11025   case Expr::MLV_ClassTemporary:
11026     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11027     break;
11028   case Expr::MLV_IncompleteType:
11029   case Expr::MLV_IncompleteVoidType:
11030     return S.RequireCompleteType(Loc, E->getType(),
11031              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11032   case Expr::MLV_DuplicateVectorComponents:
11033     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11034     break;
11035   case Expr::MLV_NoSetterProperty:
11036     llvm_unreachable("readonly properties should be processed differently");
11037   case Expr::MLV_InvalidMessageExpression:
11038     DiagID = diag::err_readonly_message_assignment;
11039     break;
11040   case Expr::MLV_SubObjCPropertySetting:
11041     DiagID = diag::err_no_subobject_property_setting;
11042     break;
11043   }
11044 
11045   SourceRange Assign;
11046   if (Loc != OrigLoc)
11047     Assign = SourceRange(OrigLoc, OrigLoc);
11048   if (NeedType)
11049     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11050   else
11051     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11052   return true;
11053 }
11054 
11055 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11056                                          SourceLocation Loc,
11057                                          Sema &Sema) {
11058   if (Sema.inTemplateInstantiation())
11059     return;
11060   if (Sema.isUnevaluatedContext())
11061     return;
11062   if (Loc.isInvalid() || Loc.isMacroID())
11063     return;
11064   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11065     return;
11066 
11067   // C / C++ fields
11068   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11069   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11070   if (ML && MR) {
11071     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11072       return;
11073     const ValueDecl *LHSDecl =
11074         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11075     const ValueDecl *RHSDecl =
11076         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11077     if (LHSDecl != RHSDecl)
11078       return;
11079     if (LHSDecl->getType().isVolatileQualified())
11080       return;
11081     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11082       if (RefTy->getPointeeType().isVolatileQualified())
11083         return;
11084 
11085     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11086   }
11087 
11088   // Objective-C instance variables
11089   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11090   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11091   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11092     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11093     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11094     if (RL && RR && RL->getDecl() == RR->getDecl())
11095       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11096   }
11097 }
11098 
11099 // C99 6.5.16.1
11100 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11101                                        SourceLocation Loc,
11102                                        QualType CompoundType) {
11103   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11104 
11105   // Verify that LHS is a modifiable lvalue, and emit error if not.
11106   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11107     return QualType();
11108 
11109   QualType LHSType = LHSExpr->getType();
11110   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11111                                              CompoundType;
11112   // OpenCL v1.2 s6.1.1.1 p2:
11113   // The half data type can only be used to declare a pointer to a buffer that
11114   // contains half values
11115   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11116     LHSType->isHalfType()) {
11117     Diag(Loc, diag::err_opencl_half_load_store) << 1
11118         << LHSType.getUnqualifiedType();
11119     return QualType();
11120   }
11121 
11122   AssignConvertType ConvTy;
11123   if (CompoundType.isNull()) {
11124     Expr *RHSCheck = RHS.get();
11125 
11126     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11127 
11128     QualType LHSTy(LHSType);
11129     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11130     if (RHS.isInvalid())
11131       return QualType();
11132     // Special case of NSObject attributes on c-style pointer types.
11133     if (ConvTy == IncompatiblePointer &&
11134         ((Context.isObjCNSObjectType(LHSType) &&
11135           RHSType->isObjCObjectPointerType()) ||
11136          (Context.isObjCNSObjectType(RHSType) &&
11137           LHSType->isObjCObjectPointerType())))
11138       ConvTy = Compatible;
11139 
11140     if (ConvTy == Compatible &&
11141         LHSType->isObjCObjectType())
11142         Diag(Loc, diag::err_objc_object_assignment)
11143           << LHSType;
11144 
11145     // If the RHS is a unary plus or minus, check to see if they = and + are
11146     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11147     // instead of "x += 4".
11148     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11149       RHSCheck = ICE->getSubExpr();
11150     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11151       if ((UO->getOpcode() == UO_Plus ||
11152            UO->getOpcode() == UO_Minus) &&
11153           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11154           // Only if the two operators are exactly adjacent.
11155           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11156           // And there is a space or other character before the subexpr of the
11157           // unary +/-.  We don't want to warn on "x=-1".
11158           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
11159           UO->getSubExpr()->getLocStart().isFileID()) {
11160         Diag(Loc, diag::warn_not_compound_assign)
11161           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11162           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11163       }
11164     }
11165 
11166     if (ConvTy == Compatible) {
11167       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11168         // Warn about retain cycles where a block captures the LHS, but
11169         // not if the LHS is a simple variable into which the block is
11170         // being stored...unless that variable can be captured by reference!
11171         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11172         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11173         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11174           checkRetainCycles(LHSExpr, RHS.get());
11175       }
11176 
11177       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11178           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11179         // It is safe to assign a weak reference into a strong variable.
11180         // Although this code can still have problems:
11181         //   id x = self.weakProp;
11182         //   id y = self.weakProp;
11183         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11184         // paths through the function. This should be revisited if
11185         // -Wrepeated-use-of-weak is made flow-sensitive.
11186         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11187         // variable, which will be valid for the current autorelease scope.
11188         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11189                              RHS.get()->getLocStart()))
11190           getCurFunction()->markSafeWeakUse(RHS.get());
11191 
11192       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11193         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11194       }
11195     }
11196   } else {
11197     // Compound assignment "x += y"
11198     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11199   }
11200 
11201   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11202                                RHS.get(), AA_Assigning))
11203     return QualType();
11204 
11205   CheckForNullPointerDereference(*this, LHSExpr);
11206 
11207   // C99 6.5.16p3: The type of an assignment expression is the type of the
11208   // left operand unless the left operand has qualified type, in which case
11209   // it is the unqualified version of the type of the left operand.
11210   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11211   // is converted to the type of the assignment expression (above).
11212   // C++ 5.17p1: the type of the assignment expression is that of its left
11213   // operand.
11214   return (getLangOpts().CPlusPlus
11215           ? LHSType : LHSType.getUnqualifiedType());
11216 }
11217 
11218 // Only ignore explicit casts to void.
11219 static bool IgnoreCommaOperand(const Expr *E) {
11220   E = E->IgnoreParens();
11221 
11222   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11223     if (CE->getCastKind() == CK_ToVoid) {
11224       return true;
11225     }
11226   }
11227 
11228   return false;
11229 }
11230 
11231 // Look for instances where it is likely the comma operator is confused with
11232 // another operator.  There is a whitelist of acceptable expressions for the
11233 // left hand side of the comma operator, otherwise emit a warning.
11234 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11235   // No warnings in macros
11236   if (Loc.isMacroID())
11237     return;
11238 
11239   // Don't warn in template instantiations.
11240   if (inTemplateInstantiation())
11241     return;
11242 
11243   // Scope isn't fine-grained enough to whitelist the specific cases, so
11244   // instead, skip more than needed, then call back into here with the
11245   // CommaVisitor in SemaStmt.cpp.
11246   // The whitelisted locations are the initialization and increment portions
11247   // of a for loop.  The additional checks are on the condition of
11248   // if statements, do/while loops, and for loops.
11249   const unsigned ForIncrementFlags =
11250       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
11251   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11252   const unsigned ScopeFlags = getCurScope()->getFlags();
11253   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11254       (ScopeFlags & ForInitFlags) == ForInitFlags)
11255     return;
11256 
11257   // If there are multiple comma operators used together, get the RHS of the
11258   // of the comma operator as the LHS.
11259   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11260     if (BO->getOpcode() != BO_Comma)
11261       break;
11262     LHS = BO->getRHS();
11263   }
11264 
11265   // Only allow some expressions on LHS to not warn.
11266   if (IgnoreCommaOperand(LHS))
11267     return;
11268 
11269   Diag(Loc, diag::warn_comma_operator);
11270   Diag(LHS->getLocStart(), diag::note_cast_to_void)
11271       << LHS->getSourceRange()
11272       << FixItHint::CreateInsertion(LHS->getLocStart(),
11273                                     LangOpts.CPlusPlus ? "static_cast<void>("
11274                                                        : "(void)(")
11275       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
11276                                     ")");
11277 }
11278 
11279 // C99 6.5.17
11280 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11281                                    SourceLocation Loc) {
11282   LHS = S.CheckPlaceholderExpr(LHS.get());
11283   RHS = S.CheckPlaceholderExpr(RHS.get());
11284   if (LHS.isInvalid() || RHS.isInvalid())
11285     return QualType();
11286 
11287   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11288   // operands, but not unary promotions.
11289   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11290 
11291   // So we treat the LHS as a ignored value, and in C++ we allow the
11292   // containing site to determine what should be done with the RHS.
11293   LHS = S.IgnoredValueConversions(LHS.get());
11294   if (LHS.isInvalid())
11295     return QualType();
11296 
11297   S.DiagnoseUnusedExprResult(LHS.get());
11298 
11299   if (!S.getLangOpts().CPlusPlus) {
11300     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11301     if (RHS.isInvalid())
11302       return QualType();
11303     if (!RHS.get()->getType()->isVoidType())
11304       S.RequireCompleteType(Loc, RHS.get()->getType(),
11305                             diag::err_incomplete_type);
11306   }
11307 
11308   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11309     S.DiagnoseCommaOperator(LHS.get(), Loc);
11310 
11311   return RHS.get()->getType();
11312 }
11313 
11314 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11315 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11316 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11317                                                ExprValueKind &VK,
11318                                                ExprObjectKind &OK,
11319                                                SourceLocation OpLoc,
11320                                                bool IsInc, bool IsPrefix) {
11321   if (Op->isTypeDependent())
11322     return S.Context.DependentTy;
11323 
11324   QualType ResType = Op->getType();
11325   // Atomic types can be used for increment / decrement where the non-atomic
11326   // versions can, so ignore the _Atomic() specifier for the purpose of
11327   // checking.
11328   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11329     ResType = ResAtomicType->getValueType();
11330 
11331   assert(!ResType.isNull() && "no type for increment/decrement expression");
11332 
11333   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11334     // Decrement of bool is not allowed.
11335     if (!IsInc) {
11336       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11337       return QualType();
11338     }
11339     // Increment of bool sets it to true, but is deprecated.
11340     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11341                                               : diag::warn_increment_bool)
11342       << Op->getSourceRange();
11343   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11344     // Error on enum increments and decrements in C++ mode
11345     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11346     return QualType();
11347   } else if (ResType->isRealType()) {
11348     // OK!
11349   } else if (ResType->isPointerType()) {
11350     // C99 6.5.2.4p2, 6.5.6p2
11351     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11352       return QualType();
11353   } else if (ResType->isObjCObjectPointerType()) {
11354     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11355     // Otherwise, we just need a complete type.
11356     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11357         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11358       return QualType();
11359   } else if (ResType->isAnyComplexType()) {
11360     // C99 does not support ++/-- on complex types, we allow as an extension.
11361     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11362       << ResType << Op->getSourceRange();
11363   } else if (ResType->isPlaceholderType()) {
11364     ExprResult PR = S.CheckPlaceholderExpr(Op);
11365     if (PR.isInvalid()) return QualType();
11366     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11367                                           IsInc, IsPrefix);
11368   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11369     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11370   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11371              (ResType->getAs<VectorType>()->getVectorKind() !=
11372               VectorType::AltiVecBool)) {
11373     // The z vector extensions allow ++ and -- for non-bool vectors.
11374   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11375             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11376     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11377   } else {
11378     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11379       << ResType << int(IsInc) << Op->getSourceRange();
11380     return QualType();
11381   }
11382   // At this point, we know we have a real, complex or pointer type.
11383   // Now make sure the operand is a modifiable lvalue.
11384   if (CheckForModifiableLvalue(Op, OpLoc, S))
11385     return QualType();
11386   // In C++, a prefix increment is the same type as the operand. Otherwise
11387   // (in C or with postfix), the increment is the unqualified type of the
11388   // operand.
11389   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11390     VK = VK_LValue;
11391     OK = Op->getObjectKind();
11392     return ResType;
11393   } else {
11394     VK = VK_RValue;
11395     return ResType.getUnqualifiedType();
11396   }
11397 }
11398 
11399 
11400 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11401 /// This routine allows us to typecheck complex/recursive expressions
11402 /// where the declaration is needed for type checking. We only need to
11403 /// handle cases when the expression references a function designator
11404 /// or is an lvalue. Here are some examples:
11405 ///  - &(x) => x
11406 ///  - &*****f => f for f a function designator.
11407 ///  - &s.xx => s
11408 ///  - &s.zz[1].yy -> s, if zz is an array
11409 ///  - *(x + 1) -> x, if x is an array
11410 ///  - &"123"[2] -> 0
11411 ///  - & __real__ x -> x
11412 static ValueDecl *getPrimaryDecl(Expr *E) {
11413   switch (E->getStmtClass()) {
11414   case Stmt::DeclRefExprClass:
11415     return cast<DeclRefExpr>(E)->getDecl();
11416   case Stmt::MemberExprClass:
11417     // If this is an arrow operator, the address is an offset from
11418     // the base's value, so the object the base refers to is
11419     // irrelevant.
11420     if (cast<MemberExpr>(E)->isArrow())
11421       return nullptr;
11422     // Otherwise, the expression refers to a part of the base
11423     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11424   case Stmt::ArraySubscriptExprClass: {
11425     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11426     // promotion of register arrays earlier.
11427     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11428     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11429       if (ICE->getSubExpr()->getType()->isArrayType())
11430         return getPrimaryDecl(ICE->getSubExpr());
11431     }
11432     return nullptr;
11433   }
11434   case Stmt::UnaryOperatorClass: {
11435     UnaryOperator *UO = cast<UnaryOperator>(E);
11436 
11437     switch(UO->getOpcode()) {
11438     case UO_Real:
11439     case UO_Imag:
11440     case UO_Extension:
11441       return getPrimaryDecl(UO->getSubExpr());
11442     default:
11443       return nullptr;
11444     }
11445   }
11446   case Stmt::ParenExprClass:
11447     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11448   case Stmt::ImplicitCastExprClass:
11449     // If the result of an implicit cast is an l-value, we care about
11450     // the sub-expression; otherwise, the result here doesn't matter.
11451     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11452   default:
11453     return nullptr;
11454   }
11455 }
11456 
11457 namespace {
11458   enum {
11459     AO_Bit_Field = 0,
11460     AO_Vector_Element = 1,
11461     AO_Property_Expansion = 2,
11462     AO_Register_Variable = 3,
11463     AO_No_Error = 4
11464   };
11465 }
11466 /// Diagnose invalid operand for address of operations.
11467 ///
11468 /// \param Type The type of operand which cannot have its address taken.
11469 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11470                                          Expr *E, unsigned Type) {
11471   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11472 }
11473 
11474 /// CheckAddressOfOperand - The operand of & must be either a function
11475 /// designator or an lvalue designating an object. If it is an lvalue, the
11476 /// object cannot be declared with storage class register or be a bit field.
11477 /// Note: The usual conversions are *not* applied to the operand of the &
11478 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11479 /// In C++, the operand might be an overloaded function name, in which case
11480 /// we allow the '&' but retain the overloaded-function type.
11481 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11482   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11483     if (PTy->getKind() == BuiltinType::Overload) {
11484       Expr *E = OrigOp.get()->IgnoreParens();
11485       if (!isa<OverloadExpr>(E)) {
11486         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11487         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11488           << OrigOp.get()->getSourceRange();
11489         return QualType();
11490       }
11491 
11492       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11493       if (isa<UnresolvedMemberExpr>(Ovl))
11494         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11495           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11496             << OrigOp.get()->getSourceRange();
11497           return QualType();
11498         }
11499 
11500       return Context.OverloadTy;
11501     }
11502 
11503     if (PTy->getKind() == BuiltinType::UnknownAny)
11504       return Context.UnknownAnyTy;
11505 
11506     if (PTy->getKind() == BuiltinType::BoundMember) {
11507       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11508         << OrigOp.get()->getSourceRange();
11509       return QualType();
11510     }
11511 
11512     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11513     if (OrigOp.isInvalid()) return QualType();
11514   }
11515 
11516   if (OrigOp.get()->isTypeDependent())
11517     return Context.DependentTy;
11518 
11519   assert(!OrigOp.get()->getType()->isPlaceholderType());
11520 
11521   // Make sure to ignore parentheses in subsequent checks
11522   Expr *op = OrigOp.get()->IgnoreParens();
11523 
11524   // In OpenCL captures for blocks called as lambda functions
11525   // are located in the private address space. Blocks used in
11526   // enqueue_kernel can be located in a different address space
11527   // depending on a vendor implementation. Thus preventing
11528   // taking an address of the capture to avoid invalid AS casts.
11529   if (LangOpts.OpenCL) {
11530     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11531     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11532       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11533       return QualType();
11534     }
11535   }
11536 
11537   if (getLangOpts().C99) {
11538     // Implement C99-only parts of addressof rules.
11539     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11540       if (uOp->getOpcode() == UO_Deref)
11541         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11542         // (assuming the deref expression is valid).
11543         return uOp->getSubExpr()->getType();
11544     }
11545     // Technically, there should be a check for array subscript
11546     // expressions here, but the result of one is always an lvalue anyway.
11547   }
11548   ValueDecl *dcl = getPrimaryDecl(op);
11549 
11550   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11551     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11552                                            op->getLocStart()))
11553       return QualType();
11554 
11555   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11556   unsigned AddressOfError = AO_No_Error;
11557 
11558   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11559     bool sfinae = (bool)isSFINAEContext();
11560     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11561                                   : diag::ext_typecheck_addrof_temporary)
11562       << op->getType() << op->getSourceRange();
11563     if (sfinae)
11564       return QualType();
11565     // Materialize the temporary as an lvalue so that we can take its address.
11566     OrigOp = op =
11567         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11568   } else if (isa<ObjCSelectorExpr>(op)) {
11569     return Context.getPointerType(op->getType());
11570   } else if (lval == Expr::LV_MemberFunction) {
11571     // If it's an instance method, make a member pointer.
11572     // The expression must have exactly the form &A::foo.
11573 
11574     // If the underlying expression isn't a decl ref, give up.
11575     if (!isa<DeclRefExpr>(op)) {
11576       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11577         << OrigOp.get()->getSourceRange();
11578       return QualType();
11579     }
11580     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11581     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11582 
11583     // The id-expression was parenthesized.
11584     if (OrigOp.get() != DRE) {
11585       Diag(OpLoc, diag::err_parens_pointer_member_function)
11586         << OrigOp.get()->getSourceRange();
11587 
11588     // The method was named without a qualifier.
11589     } else if (!DRE->getQualifier()) {
11590       if (MD->getParent()->getName().empty())
11591         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11592           << op->getSourceRange();
11593       else {
11594         SmallString<32> Str;
11595         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11596         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11597           << op->getSourceRange()
11598           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11599       }
11600     }
11601 
11602     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11603     if (isa<CXXDestructorDecl>(MD))
11604       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11605 
11606     QualType MPTy = Context.getMemberPointerType(
11607         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11608     // Under the MS ABI, lock down the inheritance model now.
11609     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11610       (void)isCompleteType(OpLoc, MPTy);
11611     return MPTy;
11612   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11613     // C99 6.5.3.2p1
11614     // The operand must be either an l-value or a function designator
11615     if (!op->getType()->isFunctionType()) {
11616       // Use a special diagnostic for loads from property references.
11617       if (isa<PseudoObjectExpr>(op)) {
11618         AddressOfError = AO_Property_Expansion;
11619       } else {
11620         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11621           << op->getType() << op->getSourceRange();
11622         return QualType();
11623       }
11624     }
11625   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11626     // The operand cannot be a bit-field
11627     AddressOfError = AO_Bit_Field;
11628   } else if (op->getObjectKind() == OK_VectorComponent) {
11629     // The operand cannot be an element of a vector
11630     AddressOfError = AO_Vector_Element;
11631   } else if (dcl) { // C99 6.5.3.2p1
11632     // We have an lvalue with a decl. Make sure the decl is not declared
11633     // with the register storage-class specifier.
11634     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11635       // in C++ it is not error to take address of a register
11636       // variable (c++03 7.1.1P3)
11637       if (vd->getStorageClass() == SC_Register &&
11638           !getLangOpts().CPlusPlus) {
11639         AddressOfError = AO_Register_Variable;
11640       }
11641     } else if (isa<MSPropertyDecl>(dcl)) {
11642       AddressOfError = AO_Property_Expansion;
11643     } else if (isa<FunctionTemplateDecl>(dcl)) {
11644       return Context.OverloadTy;
11645     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11646       // Okay: we can take the address of a field.
11647       // Could be a pointer to member, though, if there is an explicit
11648       // scope qualifier for the class.
11649       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11650         DeclContext *Ctx = dcl->getDeclContext();
11651         if (Ctx && Ctx->isRecord()) {
11652           if (dcl->getType()->isReferenceType()) {
11653             Diag(OpLoc,
11654                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11655               << dcl->getDeclName() << dcl->getType();
11656             return QualType();
11657           }
11658 
11659           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11660             Ctx = Ctx->getParent();
11661 
11662           QualType MPTy = Context.getMemberPointerType(
11663               op->getType(),
11664               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11665           // Under the MS ABI, lock down the inheritance model now.
11666           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11667             (void)isCompleteType(OpLoc, MPTy);
11668           return MPTy;
11669         }
11670       }
11671     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11672                !isa<BindingDecl>(dcl))
11673       llvm_unreachable("Unknown/unexpected decl type");
11674   }
11675 
11676   if (AddressOfError != AO_No_Error) {
11677     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11678     return QualType();
11679   }
11680 
11681   if (lval == Expr::LV_IncompleteVoidType) {
11682     // Taking the address of a void variable is technically illegal, but we
11683     // allow it in cases which are otherwise valid.
11684     // Example: "extern void x; void* y = &x;".
11685     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11686   }
11687 
11688   // If the operand has type "type", the result has type "pointer to type".
11689   if (op->getType()->isObjCObjectType())
11690     return Context.getObjCObjectPointerType(op->getType());
11691 
11692   CheckAddressOfPackedMember(op);
11693 
11694   return Context.getPointerType(op->getType());
11695 }
11696 
11697 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11698   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11699   if (!DRE)
11700     return;
11701   const Decl *D = DRE->getDecl();
11702   if (!D)
11703     return;
11704   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11705   if (!Param)
11706     return;
11707   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11708     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11709       return;
11710   if (FunctionScopeInfo *FD = S.getCurFunction())
11711     if (!FD->ModifiedNonNullParams.count(Param))
11712       FD->ModifiedNonNullParams.insert(Param);
11713 }
11714 
11715 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11716 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11717                                         SourceLocation OpLoc) {
11718   if (Op->isTypeDependent())
11719     return S.Context.DependentTy;
11720 
11721   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11722   if (ConvResult.isInvalid())
11723     return QualType();
11724   Op = ConvResult.get();
11725   QualType OpTy = Op->getType();
11726   QualType Result;
11727 
11728   if (isa<CXXReinterpretCastExpr>(Op)) {
11729     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11730     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11731                                      Op->getSourceRange());
11732   }
11733 
11734   if (const PointerType *PT = OpTy->getAs<PointerType>())
11735   {
11736     Result = PT->getPointeeType();
11737   }
11738   else if (const ObjCObjectPointerType *OPT =
11739              OpTy->getAs<ObjCObjectPointerType>())
11740     Result = OPT->getPointeeType();
11741   else {
11742     ExprResult PR = S.CheckPlaceholderExpr(Op);
11743     if (PR.isInvalid()) return QualType();
11744     if (PR.get() != Op)
11745       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11746   }
11747 
11748   if (Result.isNull()) {
11749     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11750       << OpTy << Op->getSourceRange();
11751     return QualType();
11752   }
11753 
11754   // Note that per both C89 and C99, indirection is always legal, even if Result
11755   // is an incomplete type or void.  It would be possible to warn about
11756   // dereferencing a void pointer, but it's completely well-defined, and such a
11757   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11758   // for pointers to 'void' but is fine for any other pointer type:
11759   //
11760   // C++ [expr.unary.op]p1:
11761   //   [...] the expression to which [the unary * operator] is applied shall
11762   //   be a pointer to an object type, or a pointer to a function type
11763   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11764     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11765       << OpTy << Op->getSourceRange();
11766 
11767   // Dereferences are usually l-values...
11768   VK = VK_LValue;
11769 
11770   // ...except that certain expressions are never l-values in C.
11771   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11772     VK = VK_RValue;
11773 
11774   return Result;
11775 }
11776 
11777 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11778   BinaryOperatorKind Opc;
11779   switch (Kind) {
11780   default: llvm_unreachable("Unknown binop!");
11781   case tok::periodstar:           Opc = BO_PtrMemD; break;
11782   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11783   case tok::star:                 Opc = BO_Mul; break;
11784   case tok::slash:                Opc = BO_Div; break;
11785   case tok::percent:              Opc = BO_Rem; break;
11786   case tok::plus:                 Opc = BO_Add; break;
11787   case tok::minus:                Opc = BO_Sub; break;
11788   case tok::lessless:             Opc = BO_Shl; break;
11789   case tok::greatergreater:       Opc = BO_Shr; break;
11790   case tok::lessequal:            Opc = BO_LE; break;
11791   case tok::less:                 Opc = BO_LT; break;
11792   case tok::greaterequal:         Opc = BO_GE; break;
11793   case tok::greater:              Opc = BO_GT; break;
11794   case tok::exclaimequal:         Opc = BO_NE; break;
11795   case tok::equalequal:           Opc = BO_EQ; break;
11796   case tok::spaceship:            Opc = BO_Cmp; break;
11797   case tok::amp:                  Opc = BO_And; break;
11798   case tok::caret:                Opc = BO_Xor; break;
11799   case tok::pipe:                 Opc = BO_Or; break;
11800   case tok::ampamp:               Opc = BO_LAnd; break;
11801   case tok::pipepipe:             Opc = BO_LOr; break;
11802   case tok::equal:                Opc = BO_Assign; break;
11803   case tok::starequal:            Opc = BO_MulAssign; break;
11804   case tok::slashequal:           Opc = BO_DivAssign; break;
11805   case tok::percentequal:         Opc = BO_RemAssign; break;
11806   case tok::plusequal:            Opc = BO_AddAssign; break;
11807   case tok::minusequal:           Opc = BO_SubAssign; break;
11808   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11809   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11810   case tok::ampequal:             Opc = BO_AndAssign; break;
11811   case tok::caretequal:           Opc = BO_XorAssign; break;
11812   case tok::pipeequal:            Opc = BO_OrAssign; break;
11813   case tok::comma:                Opc = BO_Comma; break;
11814   }
11815   return Opc;
11816 }
11817 
11818 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11819   tok::TokenKind Kind) {
11820   UnaryOperatorKind Opc;
11821   switch (Kind) {
11822   default: llvm_unreachable("Unknown unary op!");
11823   case tok::plusplus:     Opc = UO_PreInc; break;
11824   case tok::minusminus:   Opc = UO_PreDec; break;
11825   case tok::amp:          Opc = UO_AddrOf; break;
11826   case tok::star:         Opc = UO_Deref; break;
11827   case tok::plus:         Opc = UO_Plus; break;
11828   case tok::minus:        Opc = UO_Minus; break;
11829   case tok::tilde:        Opc = UO_Not; break;
11830   case tok::exclaim:      Opc = UO_LNot; break;
11831   case tok::kw___real:    Opc = UO_Real; break;
11832   case tok::kw___imag:    Opc = UO_Imag; break;
11833   case tok::kw___extension__: Opc = UO_Extension; break;
11834   }
11835   return Opc;
11836 }
11837 
11838 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11839 /// This warning suppressed in the event of macro expansions.
11840 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11841                                    SourceLocation OpLoc, bool IsBuiltin) {
11842   if (S.inTemplateInstantiation())
11843     return;
11844   if (S.isUnevaluatedContext())
11845     return;
11846   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11847     return;
11848   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11849   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11850   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11851   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11852   if (!LHSDeclRef || !RHSDeclRef ||
11853       LHSDeclRef->getLocation().isMacroID() ||
11854       RHSDeclRef->getLocation().isMacroID())
11855     return;
11856   const ValueDecl *LHSDecl =
11857     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11858   const ValueDecl *RHSDecl =
11859     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11860   if (LHSDecl != RHSDecl)
11861     return;
11862   if (LHSDecl->getType().isVolatileQualified())
11863     return;
11864   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11865     if (RefTy->getPointeeType().isVolatileQualified())
11866       return;
11867 
11868   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11869                           : diag::warn_self_assignment_overloaded)
11870       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11871       << RHSExpr->getSourceRange();
11872 }
11873 
11874 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11875 /// is usually indicative of introspection within the Objective-C pointer.
11876 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11877                                           SourceLocation OpLoc) {
11878   if (!S.getLangOpts().ObjC1)
11879     return;
11880 
11881   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11882   const Expr *LHS = L.get();
11883   const Expr *RHS = R.get();
11884 
11885   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11886     ObjCPointerExpr = LHS;
11887     OtherExpr = RHS;
11888   }
11889   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11890     ObjCPointerExpr = RHS;
11891     OtherExpr = LHS;
11892   }
11893 
11894   // This warning is deliberately made very specific to reduce false
11895   // positives with logic that uses '&' for hashing.  This logic mainly
11896   // looks for code trying to introspect into tagged pointers, which
11897   // code should generally never do.
11898   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11899     unsigned Diag = diag::warn_objc_pointer_masking;
11900     // Determine if we are introspecting the result of performSelectorXXX.
11901     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11902     // Special case messages to -performSelector and friends, which
11903     // can return non-pointer values boxed in a pointer value.
11904     // Some clients may wish to silence warnings in this subcase.
11905     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11906       Selector S = ME->getSelector();
11907       StringRef SelArg0 = S.getNameForSlot(0);
11908       if (SelArg0.startswith("performSelector"))
11909         Diag = diag::warn_objc_pointer_masking_performSelector;
11910     }
11911 
11912     S.Diag(OpLoc, Diag)
11913       << ObjCPointerExpr->getSourceRange();
11914   }
11915 }
11916 
11917 static NamedDecl *getDeclFromExpr(Expr *E) {
11918   if (!E)
11919     return nullptr;
11920   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11921     return DRE->getDecl();
11922   if (auto *ME = dyn_cast<MemberExpr>(E))
11923     return ME->getMemberDecl();
11924   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11925     return IRE->getDecl();
11926   return nullptr;
11927 }
11928 
11929 // This helper function promotes a binary operator's operands (which are of a
11930 // half vector type) to a vector of floats and then truncates the result to
11931 // a vector of either half or short.
11932 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11933                                       BinaryOperatorKind Opc, QualType ResultTy,
11934                                       ExprValueKind VK, ExprObjectKind OK,
11935                                       bool IsCompAssign, SourceLocation OpLoc,
11936                                       FPOptions FPFeatures) {
11937   auto &Context = S.getASTContext();
11938   assert((isVector(ResultTy, Context.HalfTy) ||
11939           isVector(ResultTy, Context.ShortTy)) &&
11940          "Result must be a vector of half or short");
11941   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11942          isVector(RHS.get()->getType(), Context.HalfTy) &&
11943          "both operands expected to be a half vector");
11944 
11945   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11946   QualType BinOpResTy = RHS.get()->getType();
11947 
11948   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11949   // change BinOpResTy to a vector of ints.
11950   if (isVector(ResultTy, Context.ShortTy))
11951     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11952 
11953   if (IsCompAssign)
11954     return new (Context) CompoundAssignOperator(
11955         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11956         OpLoc, FPFeatures);
11957 
11958   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11959   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11960                                           VK, OK, OpLoc, FPFeatures);
11961   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11962 }
11963 
11964 static std::pair<ExprResult, ExprResult>
11965 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11966                            Expr *RHSExpr) {
11967   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11968   if (!S.getLangOpts().CPlusPlus) {
11969     // C cannot handle TypoExpr nodes on either side of a binop because it
11970     // doesn't handle dependent types properly, so make sure any TypoExprs have
11971     // been dealt with before checking the operands.
11972     LHS = S.CorrectDelayedTyposInExpr(LHS);
11973     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11974       if (Opc != BO_Assign)
11975         return ExprResult(E);
11976       // Avoid correcting the RHS to the same Expr as the LHS.
11977       Decl *D = getDeclFromExpr(E);
11978       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11979     });
11980   }
11981   return std::make_pair(LHS, RHS);
11982 }
11983 
11984 /// Returns true if conversion between vectors of halfs and vectors of floats
11985 /// is needed.
11986 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11987                                      QualType SrcType) {
11988   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11989          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11990          isVector(SrcType, Ctx.HalfTy);
11991 }
11992 
11993 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11994 /// operator @p Opc at location @c TokLoc. This routine only supports
11995 /// built-in operations; ActOnBinOp handles overloaded operators.
11996 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11997                                     BinaryOperatorKind Opc,
11998                                     Expr *LHSExpr, Expr *RHSExpr) {
11999   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12000     // The syntax only allows initializer lists on the RHS of assignment,
12001     // so we don't need to worry about accepting invalid code for
12002     // non-assignment operators.
12003     // C++11 5.17p9:
12004     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12005     //   of x = {} is x = T().
12006     InitializationKind Kind = InitializationKind::CreateDirectList(
12007         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
12008     InitializedEntity Entity =
12009         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12010     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12011     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12012     if (Init.isInvalid())
12013       return Init;
12014     RHSExpr = Init.get();
12015   }
12016 
12017   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12018   QualType ResultTy;     // Result type of the binary operator.
12019   // The following two variables are used for compound assignment operators
12020   QualType CompLHSTy;    // Type of LHS after promotions for computation
12021   QualType CompResultTy; // Type of computation result
12022   ExprValueKind VK = VK_RValue;
12023   ExprObjectKind OK = OK_Ordinary;
12024   bool ConvertHalfVec = false;
12025 
12026   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12027   if (!LHS.isUsable() || !RHS.isUsable())
12028     return ExprError();
12029 
12030   if (getLangOpts().OpenCL) {
12031     QualType LHSTy = LHSExpr->getType();
12032     QualType RHSTy = RHSExpr->getType();
12033     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12034     // the ATOMIC_VAR_INIT macro.
12035     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12036       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
12037       if (BO_Assign == Opc)
12038         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12039       else
12040         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12041       return ExprError();
12042     }
12043 
12044     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12045     // only with a builtin functions and therefore should be disallowed here.
12046     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12047         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12048         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12049         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12050       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12051       return ExprError();
12052     }
12053   }
12054 
12055   switch (Opc) {
12056   case BO_Assign:
12057     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12058     if (getLangOpts().CPlusPlus &&
12059         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12060       VK = LHS.get()->getValueKind();
12061       OK = LHS.get()->getObjectKind();
12062     }
12063     if (!ResultTy.isNull()) {
12064       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12065       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12066     }
12067     RecordModifiableNonNullParam(*this, LHS.get());
12068     break;
12069   case BO_PtrMemD:
12070   case BO_PtrMemI:
12071     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12072                                             Opc == BO_PtrMemI);
12073     break;
12074   case BO_Mul:
12075   case BO_Div:
12076     ConvertHalfVec = true;
12077     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12078                                            Opc == BO_Div);
12079     break;
12080   case BO_Rem:
12081     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12082     break;
12083   case BO_Add:
12084     ConvertHalfVec = true;
12085     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12086     break;
12087   case BO_Sub:
12088     ConvertHalfVec = true;
12089     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12090     break;
12091   case BO_Shl:
12092   case BO_Shr:
12093     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12094     break;
12095   case BO_LE:
12096   case BO_LT:
12097   case BO_GE:
12098   case BO_GT:
12099     ConvertHalfVec = true;
12100     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12101     break;
12102   case BO_EQ:
12103   case BO_NE:
12104     ConvertHalfVec = true;
12105     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12106     break;
12107   case BO_Cmp:
12108     ConvertHalfVec = true;
12109     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12110     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12111     break;
12112   case BO_And:
12113     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12114     LLVM_FALLTHROUGH;
12115   case BO_Xor:
12116   case BO_Or:
12117     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12118     break;
12119   case BO_LAnd:
12120   case BO_LOr:
12121     ConvertHalfVec = true;
12122     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12123     break;
12124   case BO_MulAssign:
12125   case BO_DivAssign:
12126     ConvertHalfVec = true;
12127     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12128                                                Opc == BO_DivAssign);
12129     CompLHSTy = CompResultTy;
12130     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12131       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12132     break;
12133   case BO_RemAssign:
12134     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12135     CompLHSTy = CompResultTy;
12136     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12137       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12138     break;
12139   case BO_AddAssign:
12140     ConvertHalfVec = true;
12141     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12142     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12143       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12144     break;
12145   case BO_SubAssign:
12146     ConvertHalfVec = true;
12147     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12148     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12149       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12150     break;
12151   case BO_ShlAssign:
12152   case BO_ShrAssign:
12153     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12154     CompLHSTy = CompResultTy;
12155     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12156       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12157     break;
12158   case BO_AndAssign:
12159   case BO_OrAssign: // fallthrough
12160     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12161     LLVM_FALLTHROUGH;
12162   case BO_XorAssign:
12163     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12164     CompLHSTy = CompResultTy;
12165     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12166       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12167     break;
12168   case BO_Comma:
12169     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12170     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12171       VK = RHS.get()->getValueKind();
12172       OK = RHS.get()->getObjectKind();
12173     }
12174     break;
12175   }
12176   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12177     return ExprError();
12178 
12179   // Some of the binary operations require promoting operands of half vector to
12180   // float vectors and truncating the result back to half vector. For now, we do
12181   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12182   // arm64).
12183   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12184          isVector(LHS.get()->getType(), Context.HalfTy) &&
12185          "both sides are half vectors or neither sides are");
12186   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12187                                             LHS.get()->getType());
12188 
12189   // Check for array bounds violations for both sides of the BinaryOperator
12190   CheckArrayAccess(LHS.get());
12191   CheckArrayAccess(RHS.get());
12192 
12193   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12194     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12195                                                  &Context.Idents.get("object_setClass"),
12196                                                  SourceLocation(), LookupOrdinaryName);
12197     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12198       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
12199       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
12200       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
12201       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
12202       FixItHint::CreateInsertion(RHSLocEnd, ")");
12203     }
12204     else
12205       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12206   }
12207   else if (const ObjCIvarRefExpr *OIRE =
12208            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12209     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12210 
12211   // Opc is not a compound assignment if CompResultTy is null.
12212   if (CompResultTy.isNull()) {
12213     if (ConvertHalfVec)
12214       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12215                                  OpLoc, FPFeatures);
12216     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12217                                         OK, OpLoc, FPFeatures);
12218   }
12219 
12220   // Handle compound assignments.
12221   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12222       OK_ObjCProperty) {
12223     VK = VK_LValue;
12224     OK = LHS.get()->getObjectKind();
12225   }
12226 
12227   if (ConvertHalfVec)
12228     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12229                                OpLoc, FPFeatures);
12230 
12231   return new (Context) CompoundAssignOperator(
12232       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12233       OpLoc, FPFeatures);
12234 }
12235 
12236 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12237 /// operators are mixed in a way that suggests that the programmer forgot that
12238 /// comparison operators have higher precedence. The most typical example of
12239 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12240 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12241                                       SourceLocation OpLoc, Expr *LHSExpr,
12242                                       Expr *RHSExpr) {
12243   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12244   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12245 
12246   // Check that one of the sides is a comparison operator and the other isn't.
12247   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12248   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12249   if (isLeftComp == isRightComp)
12250     return;
12251 
12252   // Bitwise operations are sometimes used as eager logical ops.
12253   // Don't diagnose this.
12254   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12255   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12256   if (isLeftBitwise || isRightBitwise)
12257     return;
12258 
12259   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
12260                                                    OpLoc)
12261                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
12262   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12263   SourceRange ParensRange = isLeftComp ?
12264       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
12265     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
12266 
12267   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12268     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12269   SuggestParentheses(Self, OpLoc,
12270     Self.PDiag(diag::note_precedence_silence) << OpStr,
12271     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12272   SuggestParentheses(Self, OpLoc,
12273     Self.PDiag(diag::note_precedence_bitwise_first)
12274       << BinaryOperator::getOpcodeStr(Opc),
12275     ParensRange);
12276 }
12277 
12278 /// It accepts a '&&' expr that is inside a '||' one.
12279 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12280 /// in parentheses.
12281 static void
12282 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12283                                        BinaryOperator *Bop) {
12284   assert(Bop->getOpcode() == BO_LAnd);
12285   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12286       << Bop->getSourceRange() << OpLoc;
12287   SuggestParentheses(Self, Bop->getOperatorLoc(),
12288     Self.PDiag(diag::note_precedence_silence)
12289       << Bop->getOpcodeStr(),
12290     Bop->getSourceRange());
12291 }
12292 
12293 /// Returns true if the given expression can be evaluated as a constant
12294 /// 'true'.
12295 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12296   bool Res;
12297   return !E->isValueDependent() &&
12298          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12299 }
12300 
12301 /// Returns true if the given expression can be evaluated as a constant
12302 /// 'false'.
12303 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12304   bool Res;
12305   return !E->isValueDependent() &&
12306          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12307 }
12308 
12309 /// Look for '&&' in the left hand of a '||' expr.
12310 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12311                                              Expr *LHSExpr, Expr *RHSExpr) {
12312   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12313     if (Bop->getOpcode() == BO_LAnd) {
12314       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12315       if (EvaluatesAsFalse(S, RHSExpr))
12316         return;
12317       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12318       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12319         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12320     } else if (Bop->getOpcode() == BO_LOr) {
12321       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12322         // If it's "a || b && 1 || c" we didn't warn earlier for
12323         // "a || b && 1", but warn now.
12324         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12325           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12326       }
12327     }
12328   }
12329 }
12330 
12331 /// Look for '&&' in the right hand of a '||' expr.
12332 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12333                                              Expr *LHSExpr, Expr *RHSExpr) {
12334   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12335     if (Bop->getOpcode() == BO_LAnd) {
12336       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12337       if (EvaluatesAsFalse(S, LHSExpr))
12338         return;
12339       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12340       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12341         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12342     }
12343   }
12344 }
12345 
12346 /// Look for bitwise op in the left or right hand of a bitwise op with
12347 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12348 /// the '&' expression in parentheses.
12349 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12350                                          SourceLocation OpLoc, Expr *SubExpr) {
12351   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12352     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12353       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12354         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12355         << Bop->getSourceRange() << OpLoc;
12356       SuggestParentheses(S, Bop->getOperatorLoc(),
12357         S.PDiag(diag::note_precedence_silence)
12358           << Bop->getOpcodeStr(),
12359         Bop->getSourceRange());
12360     }
12361   }
12362 }
12363 
12364 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12365                                     Expr *SubExpr, StringRef Shift) {
12366   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12367     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12368       StringRef Op = Bop->getOpcodeStr();
12369       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12370           << Bop->getSourceRange() << OpLoc << Shift << Op;
12371       SuggestParentheses(S, Bop->getOperatorLoc(),
12372           S.PDiag(diag::note_precedence_silence) << Op,
12373           Bop->getSourceRange());
12374     }
12375   }
12376 }
12377 
12378 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12379                                  Expr *LHSExpr, Expr *RHSExpr) {
12380   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12381   if (!OCE)
12382     return;
12383 
12384   FunctionDecl *FD = OCE->getDirectCallee();
12385   if (!FD || !FD->isOverloadedOperator())
12386     return;
12387 
12388   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12389   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12390     return;
12391 
12392   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12393       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12394       << (Kind == OO_LessLess);
12395   SuggestParentheses(S, OCE->getOperatorLoc(),
12396                      S.PDiag(diag::note_precedence_silence)
12397                          << (Kind == OO_LessLess ? "<<" : ">>"),
12398                      OCE->getSourceRange());
12399   SuggestParentheses(S, OpLoc,
12400                      S.PDiag(diag::note_evaluate_comparison_first),
12401                      SourceRange(OCE->getArg(1)->getLocStart(),
12402                                  RHSExpr->getLocEnd()));
12403 }
12404 
12405 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12406 /// precedence.
12407 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12408                                     SourceLocation OpLoc, Expr *LHSExpr,
12409                                     Expr *RHSExpr){
12410   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12411   if (BinaryOperator::isBitwiseOp(Opc))
12412     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12413 
12414   // Diagnose "arg1 & arg2 | arg3"
12415   if ((Opc == BO_Or || Opc == BO_Xor) &&
12416       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12417     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12418     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12419   }
12420 
12421   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12422   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12423   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12424     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12425     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12426   }
12427 
12428   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12429       || Opc == BO_Shr) {
12430     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12431     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12432     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12433   }
12434 
12435   // Warn on overloaded shift operators and comparisons, such as:
12436   // cout << 5 == 4;
12437   if (BinaryOperator::isComparisonOp(Opc))
12438     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12439 }
12440 
12441 // Binary Operators.  'Tok' is the token for the operator.
12442 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12443                             tok::TokenKind Kind,
12444                             Expr *LHSExpr, Expr *RHSExpr) {
12445   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12446   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12447   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12448 
12449   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12450   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12451 
12452   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12453 }
12454 
12455 /// Build an overloaded binary operator expression in the given scope.
12456 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12457                                        BinaryOperatorKind Opc,
12458                                        Expr *LHS, Expr *RHS) {
12459   switch (Opc) {
12460   case BO_Assign:
12461   case BO_DivAssign:
12462   case BO_RemAssign:
12463   case BO_SubAssign:
12464   case BO_AndAssign:
12465   case BO_OrAssign:
12466   case BO_XorAssign:
12467     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12468     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12469     break;
12470   default:
12471     break;
12472   }
12473 
12474   // Find all of the overloaded operators visible from this
12475   // point. We perform both an operator-name lookup from the local
12476   // scope and an argument-dependent lookup based on the types of
12477   // the arguments.
12478   UnresolvedSet<16> Functions;
12479   OverloadedOperatorKind OverOp
12480     = BinaryOperator::getOverloadedOperator(Opc);
12481   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12482     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12483                                    RHS->getType(), Functions);
12484 
12485   // Build the (potentially-overloaded, potentially-dependent)
12486   // binary operation.
12487   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12488 }
12489 
12490 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12491                             BinaryOperatorKind Opc,
12492                             Expr *LHSExpr, Expr *RHSExpr) {
12493   ExprResult LHS, RHS;
12494   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12495   if (!LHS.isUsable() || !RHS.isUsable())
12496     return ExprError();
12497   LHSExpr = LHS.get();
12498   RHSExpr = RHS.get();
12499 
12500   // We want to end up calling one of checkPseudoObjectAssignment
12501   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12502   // both expressions are overloadable or either is type-dependent),
12503   // or CreateBuiltinBinOp (in any other case).  We also want to get
12504   // any placeholder types out of the way.
12505 
12506   // Handle pseudo-objects in the LHS.
12507   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12508     // Assignments with a pseudo-object l-value need special analysis.
12509     if (pty->getKind() == BuiltinType::PseudoObject &&
12510         BinaryOperator::isAssignmentOp(Opc))
12511       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12512 
12513     // Don't resolve overloads if the other type is overloadable.
12514     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12515       // We can't actually test that if we still have a placeholder,
12516       // though.  Fortunately, none of the exceptions we see in that
12517       // code below are valid when the LHS is an overload set.  Note
12518       // that an overload set can be dependently-typed, but it never
12519       // instantiates to having an overloadable type.
12520       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12521       if (resolvedRHS.isInvalid()) return ExprError();
12522       RHSExpr = resolvedRHS.get();
12523 
12524       if (RHSExpr->isTypeDependent() ||
12525           RHSExpr->getType()->isOverloadableType())
12526         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12527     }
12528 
12529     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12530     // template, diagnose the missing 'template' keyword instead of diagnosing
12531     // an invalid use of a bound member function.
12532     //
12533     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12534     // to C++1z [over.over]/1.4, but we already checked for that case above.
12535     if (Opc == BO_LT && inTemplateInstantiation() &&
12536         (pty->getKind() == BuiltinType::BoundMember ||
12537          pty->getKind() == BuiltinType::Overload)) {
12538       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12539       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12540           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12541             return isa<FunctionTemplateDecl>(ND);
12542           })) {
12543         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12544                                 : OE->getNameLoc(),
12545              diag::err_template_kw_missing)
12546           << OE->getName().getAsString() << "";
12547         return ExprError();
12548       }
12549     }
12550 
12551     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12552     if (LHS.isInvalid()) return ExprError();
12553     LHSExpr = LHS.get();
12554   }
12555 
12556   // Handle pseudo-objects in the RHS.
12557   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12558     // An overload in the RHS can potentially be resolved by the type
12559     // being assigned to.
12560     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12561       if (getLangOpts().CPlusPlus &&
12562           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12563            LHSExpr->getType()->isOverloadableType()))
12564         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12565 
12566       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12567     }
12568 
12569     // Don't resolve overloads if the other type is overloadable.
12570     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12571         LHSExpr->getType()->isOverloadableType())
12572       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12573 
12574     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12575     if (!resolvedRHS.isUsable()) return ExprError();
12576     RHSExpr = resolvedRHS.get();
12577   }
12578 
12579   if (getLangOpts().CPlusPlus) {
12580     // If either expression is type-dependent, always build an
12581     // overloaded op.
12582     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12583       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12584 
12585     // Otherwise, build an overloaded op if either expression has an
12586     // overloadable type.
12587     if (LHSExpr->getType()->isOverloadableType() ||
12588         RHSExpr->getType()->isOverloadableType())
12589       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12590   }
12591 
12592   // Build a built-in binary operation.
12593   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12594 }
12595 
12596 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12597   if (T.isNull() || T->isDependentType())
12598     return false;
12599 
12600   if (!T->isPromotableIntegerType())
12601     return true;
12602 
12603   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12604 }
12605 
12606 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12607                                       UnaryOperatorKind Opc,
12608                                       Expr *InputExpr) {
12609   ExprResult Input = InputExpr;
12610   ExprValueKind VK = VK_RValue;
12611   ExprObjectKind OK = OK_Ordinary;
12612   QualType resultType;
12613   bool CanOverflow = false;
12614 
12615   bool ConvertHalfVec = false;
12616   if (getLangOpts().OpenCL) {
12617     QualType Ty = InputExpr->getType();
12618     // The only legal unary operation for atomics is '&'.
12619     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12620     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12621     // only with a builtin functions and therefore should be disallowed here.
12622         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12623         || Ty->isBlockPointerType())) {
12624       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12625                        << InputExpr->getType()
12626                        << Input.get()->getSourceRange());
12627     }
12628   }
12629   switch (Opc) {
12630   case UO_PreInc:
12631   case UO_PreDec:
12632   case UO_PostInc:
12633   case UO_PostDec:
12634     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12635                                                 OpLoc,
12636                                                 Opc == UO_PreInc ||
12637                                                 Opc == UO_PostInc,
12638                                                 Opc == UO_PreInc ||
12639                                                 Opc == UO_PreDec);
12640     CanOverflow = isOverflowingIntegerType(Context, resultType);
12641     break;
12642   case UO_AddrOf:
12643     resultType = CheckAddressOfOperand(Input, OpLoc);
12644     RecordModifiableNonNullParam(*this, InputExpr);
12645     break;
12646   case UO_Deref: {
12647     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12648     if (Input.isInvalid()) return ExprError();
12649     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12650     break;
12651   }
12652   case UO_Plus:
12653   case UO_Minus:
12654     CanOverflow = Opc == UO_Minus &&
12655                   isOverflowingIntegerType(Context, Input.get()->getType());
12656     Input = UsualUnaryConversions(Input.get());
12657     if (Input.isInvalid()) return ExprError();
12658     // Unary plus and minus require promoting an operand of half vector to a
12659     // float vector and truncating the result back to a half vector. For now, we
12660     // do this only when HalfArgsAndReturns is set (that is, when the target is
12661     // arm or arm64).
12662     ConvertHalfVec =
12663         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12664 
12665     // If the operand is a half vector, promote it to a float vector.
12666     if (ConvertHalfVec)
12667       Input = convertVector(Input.get(), Context.FloatTy, *this);
12668     resultType = Input.get()->getType();
12669     if (resultType->isDependentType())
12670       break;
12671     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12672       break;
12673     else if (resultType->isVectorType() &&
12674              // The z vector extensions don't allow + or - with bool vectors.
12675              (!Context.getLangOpts().ZVector ||
12676               resultType->getAs<VectorType>()->getVectorKind() !=
12677               VectorType::AltiVecBool))
12678       break;
12679     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12680              Opc == UO_Plus &&
12681              resultType->isPointerType())
12682       break;
12683 
12684     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12685       << resultType << Input.get()->getSourceRange());
12686 
12687   case UO_Not: // bitwise complement
12688     Input = UsualUnaryConversions(Input.get());
12689     if (Input.isInvalid())
12690       return ExprError();
12691     resultType = Input.get()->getType();
12692 
12693     if (resultType->isDependentType())
12694       break;
12695     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12696     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12697       // C99 does not support '~' for complex conjugation.
12698       Diag(OpLoc, diag::ext_integer_complement_complex)
12699           << resultType << Input.get()->getSourceRange();
12700     else if (resultType->hasIntegerRepresentation())
12701       break;
12702     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12703       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12704       // on vector float types.
12705       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12706       if (!T->isIntegerType())
12707         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12708                           << resultType << Input.get()->getSourceRange());
12709     } else {
12710       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12711                        << resultType << Input.get()->getSourceRange());
12712     }
12713     break;
12714 
12715   case UO_LNot: // logical negation
12716     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12717     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12718     if (Input.isInvalid()) return ExprError();
12719     resultType = Input.get()->getType();
12720 
12721     // Though we still have to promote half FP to float...
12722     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12723       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12724       resultType = Context.FloatTy;
12725     }
12726 
12727     if (resultType->isDependentType())
12728       break;
12729     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12730       // C99 6.5.3.3p1: ok, fallthrough;
12731       if (Context.getLangOpts().CPlusPlus) {
12732         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12733         // operand contextually converted to bool.
12734         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12735                                   ScalarTypeToBooleanCastKind(resultType));
12736       } else if (Context.getLangOpts().OpenCL &&
12737                  Context.getLangOpts().OpenCLVersion < 120) {
12738         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12739         // operate on scalar float types.
12740         if (!resultType->isIntegerType() && !resultType->isPointerType())
12741           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12742                            << resultType << Input.get()->getSourceRange());
12743       }
12744     } else if (resultType->isExtVectorType()) {
12745       if (Context.getLangOpts().OpenCL &&
12746           Context.getLangOpts().OpenCLVersion < 120) {
12747         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12748         // operate on vector float types.
12749         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12750         if (!T->isIntegerType())
12751           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12752                            << resultType << Input.get()->getSourceRange());
12753       }
12754       // Vector logical not returns the signed variant of the operand type.
12755       resultType = GetSignedVectorType(resultType);
12756       break;
12757     } else {
12758       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12759       //        type in C++. We should allow that here too.
12760       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12761         << resultType << Input.get()->getSourceRange());
12762     }
12763 
12764     // LNot always has type int. C99 6.5.3.3p5.
12765     // In C++, it's bool. C++ 5.3.1p8
12766     resultType = Context.getLogicalOperationType();
12767     break;
12768   case UO_Real:
12769   case UO_Imag:
12770     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12771     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12772     // complex l-values to ordinary l-values and all other values to r-values.
12773     if (Input.isInvalid()) return ExprError();
12774     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12775       if (Input.get()->getValueKind() != VK_RValue &&
12776           Input.get()->getObjectKind() == OK_Ordinary)
12777         VK = Input.get()->getValueKind();
12778     } else if (!getLangOpts().CPlusPlus) {
12779       // In C, a volatile scalar is read by __imag. In C++, it is not.
12780       Input = DefaultLvalueConversion(Input.get());
12781     }
12782     break;
12783   case UO_Extension:
12784     resultType = Input.get()->getType();
12785     VK = Input.get()->getValueKind();
12786     OK = Input.get()->getObjectKind();
12787     break;
12788   case UO_Coawait:
12789     // It's unnecessary to represent the pass-through operator co_await in the
12790     // AST; just return the input expression instead.
12791     assert(!Input.get()->getType()->isDependentType() &&
12792                    "the co_await expression must be non-dependant before "
12793                    "building operator co_await");
12794     return Input;
12795   }
12796   if (resultType.isNull() || Input.isInvalid())
12797     return ExprError();
12798 
12799   // Check for array bounds violations in the operand of the UnaryOperator,
12800   // except for the '*' and '&' operators that have to be handled specially
12801   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12802   // that are explicitly defined as valid by the standard).
12803   if (Opc != UO_AddrOf && Opc != UO_Deref)
12804     CheckArrayAccess(Input.get());
12805 
12806   auto *UO = new (Context)
12807       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12808   // Convert the result back to a half vector.
12809   if (ConvertHalfVec)
12810     return convertVector(UO, Context.HalfTy, *this);
12811   return UO;
12812 }
12813 
12814 /// Determine whether the given expression is a qualified member
12815 /// access expression, of a form that could be turned into a pointer to member
12816 /// with the address-of operator.
12817 bool Sema::isQualifiedMemberAccess(Expr *E) {
12818   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12819     if (!DRE->getQualifier())
12820       return false;
12821 
12822     ValueDecl *VD = DRE->getDecl();
12823     if (!VD->isCXXClassMember())
12824       return false;
12825 
12826     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12827       return true;
12828     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12829       return Method->isInstance();
12830 
12831     return false;
12832   }
12833 
12834   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12835     if (!ULE->getQualifier())
12836       return false;
12837 
12838     for (NamedDecl *D : ULE->decls()) {
12839       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12840         if (Method->isInstance())
12841           return true;
12842       } else {
12843         // Overload set does not contain methods.
12844         break;
12845       }
12846     }
12847 
12848     return false;
12849   }
12850 
12851   return false;
12852 }
12853 
12854 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12855                               UnaryOperatorKind Opc, Expr *Input) {
12856   // First things first: handle placeholders so that the
12857   // overloaded-operator check considers the right type.
12858   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12859     // Increment and decrement of pseudo-object references.
12860     if (pty->getKind() == BuiltinType::PseudoObject &&
12861         UnaryOperator::isIncrementDecrementOp(Opc))
12862       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12863 
12864     // extension is always a builtin operator.
12865     if (Opc == UO_Extension)
12866       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12867 
12868     // & gets special logic for several kinds of placeholder.
12869     // The builtin code knows what to do.
12870     if (Opc == UO_AddrOf &&
12871         (pty->getKind() == BuiltinType::Overload ||
12872          pty->getKind() == BuiltinType::UnknownAny ||
12873          pty->getKind() == BuiltinType::BoundMember))
12874       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12875 
12876     // Anything else needs to be handled now.
12877     ExprResult Result = CheckPlaceholderExpr(Input);
12878     if (Result.isInvalid()) return ExprError();
12879     Input = Result.get();
12880   }
12881 
12882   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12883       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12884       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12885     // Find all of the overloaded operators visible from this
12886     // point. We perform both an operator-name lookup from the local
12887     // scope and an argument-dependent lookup based on the types of
12888     // the arguments.
12889     UnresolvedSet<16> Functions;
12890     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12891     if (S && OverOp != OO_None)
12892       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12893                                    Functions);
12894 
12895     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12896   }
12897 
12898   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12899 }
12900 
12901 // Unary Operators.  'Tok' is the token for the operator.
12902 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12903                               tok::TokenKind Op, Expr *Input) {
12904   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12905 }
12906 
12907 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12908 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12909                                 LabelDecl *TheDecl) {
12910   TheDecl->markUsed(Context);
12911   // Create the AST node.  The address of a label always has type 'void*'.
12912   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12913                                      Context.getPointerType(Context.VoidTy));
12914 }
12915 
12916 /// Given the last statement in a statement-expression, check whether
12917 /// the result is a producing expression (like a call to an
12918 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12919 /// release out of the full-expression.  Otherwise, return null.
12920 /// Cannot fail.
12921 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12922   // Should always be wrapped with one of these.
12923   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12924   if (!cleanups) return nullptr;
12925 
12926   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12927   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12928     return nullptr;
12929 
12930   // Splice out the cast.  This shouldn't modify any interesting
12931   // features of the statement.
12932   Expr *producer = cast->getSubExpr();
12933   assert(producer->getType() == cast->getType());
12934   assert(producer->getValueKind() == cast->getValueKind());
12935   cleanups->setSubExpr(producer);
12936   return cleanups;
12937 }
12938 
12939 void Sema::ActOnStartStmtExpr() {
12940   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12941 }
12942 
12943 void Sema::ActOnStmtExprError() {
12944   // Note that function is also called by TreeTransform when leaving a
12945   // StmtExpr scope without rebuilding anything.
12946 
12947   DiscardCleanupsInEvaluationContext();
12948   PopExpressionEvaluationContext();
12949 }
12950 
12951 ExprResult
12952 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12953                     SourceLocation RPLoc) { // "({..})"
12954   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12955   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12956 
12957   if (hasAnyUnrecoverableErrorsInThisFunction())
12958     DiscardCleanupsInEvaluationContext();
12959   assert(!Cleanup.exprNeedsCleanups() &&
12960          "cleanups within StmtExpr not correctly bound!");
12961   PopExpressionEvaluationContext();
12962 
12963   // FIXME: there are a variety of strange constraints to enforce here, for
12964   // example, it is not possible to goto into a stmt expression apparently.
12965   // More semantic analysis is needed.
12966 
12967   // If there are sub-stmts in the compound stmt, take the type of the last one
12968   // as the type of the stmtexpr.
12969   QualType Ty = Context.VoidTy;
12970   bool StmtExprMayBindToTemp = false;
12971   if (!Compound->body_empty()) {
12972     Stmt *LastStmt = Compound->body_back();
12973     LabelStmt *LastLabelStmt = nullptr;
12974     // If LastStmt is a label, skip down through into the body.
12975     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12976       LastLabelStmt = Label;
12977       LastStmt = Label->getSubStmt();
12978     }
12979 
12980     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12981       // Do function/array conversion on the last expression, but not
12982       // lvalue-to-rvalue.  However, initialize an unqualified type.
12983       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12984       if (LastExpr.isInvalid())
12985         return ExprError();
12986       Ty = LastExpr.get()->getType().getUnqualifiedType();
12987 
12988       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12989         // In ARC, if the final expression ends in a consume, splice
12990         // the consume out and bind it later.  In the alternate case
12991         // (when dealing with a retainable type), the result
12992         // initialization will create a produce.  In both cases the
12993         // result will be +1, and we'll need to balance that out with
12994         // a bind.
12995         if (Expr *rebuiltLastStmt
12996               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12997           LastExpr = rebuiltLastStmt;
12998         } else {
12999           LastExpr = PerformCopyInitialization(
13000               InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
13001               SourceLocation(), LastExpr);
13002         }
13003 
13004         if (LastExpr.isInvalid())
13005           return ExprError();
13006         if (LastExpr.get() != nullptr) {
13007           if (!LastLabelStmt)
13008             Compound->setLastStmt(LastExpr.get());
13009           else
13010             LastLabelStmt->setSubStmt(LastExpr.get());
13011           StmtExprMayBindToTemp = true;
13012         }
13013       }
13014     }
13015   }
13016 
13017   // FIXME: Check that expression type is complete/non-abstract; statement
13018   // expressions are not lvalues.
13019   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13020   if (StmtExprMayBindToTemp)
13021     return MaybeBindToTemporary(ResStmtExpr);
13022   return ResStmtExpr;
13023 }
13024 
13025 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13026                                       TypeSourceInfo *TInfo,
13027                                       ArrayRef<OffsetOfComponent> Components,
13028                                       SourceLocation RParenLoc) {
13029   QualType ArgTy = TInfo->getType();
13030   bool Dependent = ArgTy->isDependentType();
13031   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13032 
13033   // We must have at least one component that refers to the type, and the first
13034   // one is known to be a field designator.  Verify that the ArgTy represents
13035   // a struct/union/class.
13036   if (!Dependent && !ArgTy->isRecordType())
13037     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13038                        << ArgTy << TypeRange);
13039 
13040   // Type must be complete per C99 7.17p3 because a declaring a variable
13041   // with an incomplete type would be ill-formed.
13042   if (!Dependent
13043       && RequireCompleteType(BuiltinLoc, ArgTy,
13044                              diag::err_offsetof_incomplete_type, TypeRange))
13045     return ExprError();
13046 
13047   bool DidWarnAboutNonPOD = false;
13048   QualType CurrentType = ArgTy;
13049   SmallVector<OffsetOfNode, 4> Comps;
13050   SmallVector<Expr*, 4> Exprs;
13051   for (const OffsetOfComponent &OC : Components) {
13052     if (OC.isBrackets) {
13053       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13054       if (!CurrentType->isDependentType()) {
13055         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13056         if(!AT)
13057           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13058                            << CurrentType);
13059         CurrentType = AT->getElementType();
13060       } else
13061         CurrentType = Context.DependentTy;
13062 
13063       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13064       if (IdxRval.isInvalid())
13065         return ExprError();
13066       Expr *Idx = IdxRval.get();
13067 
13068       // The expression must be an integral expression.
13069       // FIXME: An integral constant expression?
13070       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13071           !Idx->getType()->isIntegerType())
13072         return ExprError(Diag(Idx->getLocStart(),
13073                               diag::err_typecheck_subscript_not_integer)
13074                          << Idx->getSourceRange());
13075 
13076       // Record this array index.
13077       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13078       Exprs.push_back(Idx);
13079       continue;
13080     }
13081 
13082     // Offset of a field.
13083     if (CurrentType->isDependentType()) {
13084       // We have the offset of a field, but we can't look into the dependent
13085       // type. Just record the identifier of the field.
13086       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13087       CurrentType = Context.DependentTy;
13088       continue;
13089     }
13090 
13091     // We need to have a complete type to look into.
13092     if (RequireCompleteType(OC.LocStart, CurrentType,
13093                             diag::err_offsetof_incomplete_type))
13094       return ExprError();
13095 
13096     // Look for the designated field.
13097     const RecordType *RC = CurrentType->getAs<RecordType>();
13098     if (!RC)
13099       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13100                        << CurrentType);
13101     RecordDecl *RD = RC->getDecl();
13102 
13103     // C++ [lib.support.types]p5:
13104     //   The macro offsetof accepts a restricted set of type arguments in this
13105     //   International Standard. type shall be a POD structure or a POD union
13106     //   (clause 9).
13107     // C++11 [support.types]p4:
13108     //   If type is not a standard-layout class (Clause 9), the results are
13109     //   undefined.
13110     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13111       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13112       unsigned DiagID =
13113         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13114                             : diag::ext_offsetof_non_pod_type;
13115 
13116       if (!IsSafe && !DidWarnAboutNonPOD &&
13117           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13118                               PDiag(DiagID)
13119                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13120                               << CurrentType))
13121         DidWarnAboutNonPOD = true;
13122     }
13123 
13124     // Look for the field.
13125     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13126     LookupQualifiedName(R, RD);
13127     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13128     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13129     if (!MemberDecl) {
13130       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13131         MemberDecl = IndirectMemberDecl->getAnonField();
13132     }
13133 
13134     if (!MemberDecl)
13135       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13136                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13137                                                               OC.LocEnd));
13138 
13139     // C99 7.17p3:
13140     //   (If the specified member is a bit-field, the behavior is undefined.)
13141     //
13142     // We diagnose this as an error.
13143     if (MemberDecl->isBitField()) {
13144       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13145         << MemberDecl->getDeclName()
13146         << SourceRange(BuiltinLoc, RParenLoc);
13147       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13148       return ExprError();
13149     }
13150 
13151     RecordDecl *Parent = MemberDecl->getParent();
13152     if (IndirectMemberDecl)
13153       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13154 
13155     // If the member was found in a base class, introduce OffsetOfNodes for
13156     // the base class indirections.
13157     CXXBasePaths Paths;
13158     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13159                       Paths)) {
13160       if (Paths.getDetectedVirtual()) {
13161         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13162           << MemberDecl->getDeclName()
13163           << SourceRange(BuiltinLoc, RParenLoc);
13164         return ExprError();
13165       }
13166 
13167       CXXBasePath &Path = Paths.front();
13168       for (const CXXBasePathElement &B : Path)
13169         Comps.push_back(OffsetOfNode(B.Base));
13170     }
13171 
13172     if (IndirectMemberDecl) {
13173       for (auto *FI : IndirectMemberDecl->chain()) {
13174         assert(isa<FieldDecl>(FI));
13175         Comps.push_back(OffsetOfNode(OC.LocStart,
13176                                      cast<FieldDecl>(FI), OC.LocEnd));
13177       }
13178     } else
13179       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13180 
13181     CurrentType = MemberDecl->getType().getNonReferenceType();
13182   }
13183 
13184   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13185                               Comps, Exprs, RParenLoc);
13186 }
13187 
13188 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13189                                       SourceLocation BuiltinLoc,
13190                                       SourceLocation TypeLoc,
13191                                       ParsedType ParsedArgTy,
13192                                       ArrayRef<OffsetOfComponent> Components,
13193                                       SourceLocation RParenLoc) {
13194 
13195   TypeSourceInfo *ArgTInfo;
13196   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13197   if (ArgTy.isNull())
13198     return ExprError();
13199 
13200   if (!ArgTInfo)
13201     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13202 
13203   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13204 }
13205 
13206 
13207 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13208                                  Expr *CondExpr,
13209                                  Expr *LHSExpr, Expr *RHSExpr,
13210                                  SourceLocation RPLoc) {
13211   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13212 
13213   ExprValueKind VK = VK_RValue;
13214   ExprObjectKind OK = OK_Ordinary;
13215   QualType resType;
13216   bool ValueDependent = false;
13217   bool CondIsTrue = false;
13218   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13219     resType = Context.DependentTy;
13220     ValueDependent = true;
13221   } else {
13222     // The conditional expression is required to be a constant expression.
13223     llvm::APSInt condEval(32);
13224     ExprResult CondICE
13225       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13226           diag::err_typecheck_choose_expr_requires_constant, false);
13227     if (CondICE.isInvalid())
13228       return ExprError();
13229     CondExpr = CondICE.get();
13230     CondIsTrue = condEval.getZExtValue();
13231 
13232     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13233     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13234 
13235     resType = ActiveExpr->getType();
13236     ValueDependent = ActiveExpr->isValueDependent();
13237     VK = ActiveExpr->getValueKind();
13238     OK = ActiveExpr->getObjectKind();
13239   }
13240 
13241   return new (Context)
13242       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13243                  CondIsTrue, resType->isDependentType(), ValueDependent);
13244 }
13245 
13246 //===----------------------------------------------------------------------===//
13247 // Clang Extensions.
13248 //===----------------------------------------------------------------------===//
13249 
13250 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13251 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13252   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13253 
13254   if (LangOpts.CPlusPlus) {
13255     Decl *ManglingContextDecl;
13256     if (MangleNumberingContext *MCtx =
13257             getCurrentMangleNumberContext(Block->getDeclContext(),
13258                                           ManglingContextDecl)) {
13259       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13260       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13261     }
13262   }
13263 
13264   PushBlockScope(CurScope, Block);
13265   CurContext->addDecl(Block);
13266   if (CurScope)
13267     PushDeclContext(CurScope, Block);
13268   else
13269     CurContext = Block;
13270 
13271   getCurBlock()->HasImplicitReturnType = true;
13272 
13273   // Enter a new evaluation context to insulate the block from any
13274   // cleanups from the enclosing full-expression.
13275   PushExpressionEvaluationContext(
13276       ExpressionEvaluationContext::PotentiallyEvaluated);
13277 }
13278 
13279 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13280                                Scope *CurScope) {
13281   assert(ParamInfo.getIdentifier() == nullptr &&
13282          "block-id should have no identifier!");
13283   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13284   BlockScopeInfo *CurBlock = getCurBlock();
13285 
13286   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13287   QualType T = Sig->getType();
13288 
13289   // FIXME: We should allow unexpanded parameter packs here, but that would,
13290   // in turn, make the block expression contain unexpanded parameter packs.
13291   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13292     // Drop the parameters.
13293     FunctionProtoType::ExtProtoInfo EPI;
13294     EPI.HasTrailingReturn = false;
13295     EPI.TypeQuals |= DeclSpec::TQ_const;
13296     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13297     Sig = Context.getTrivialTypeSourceInfo(T);
13298   }
13299 
13300   // GetTypeForDeclarator always produces a function type for a block
13301   // literal signature.  Furthermore, it is always a FunctionProtoType
13302   // unless the function was written with a typedef.
13303   assert(T->isFunctionType() &&
13304          "GetTypeForDeclarator made a non-function block signature");
13305 
13306   // Look for an explicit signature in that function type.
13307   FunctionProtoTypeLoc ExplicitSignature;
13308 
13309   if ((ExplicitSignature =
13310            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13311 
13312     // Check whether that explicit signature was synthesized by
13313     // GetTypeForDeclarator.  If so, don't save that as part of the
13314     // written signature.
13315     if (ExplicitSignature.getLocalRangeBegin() ==
13316         ExplicitSignature.getLocalRangeEnd()) {
13317       // This would be much cheaper if we stored TypeLocs instead of
13318       // TypeSourceInfos.
13319       TypeLoc Result = ExplicitSignature.getReturnLoc();
13320       unsigned Size = Result.getFullDataSize();
13321       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13322       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13323 
13324       ExplicitSignature = FunctionProtoTypeLoc();
13325     }
13326   }
13327 
13328   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13329   CurBlock->FunctionType = T;
13330 
13331   const FunctionType *Fn = T->getAs<FunctionType>();
13332   QualType RetTy = Fn->getReturnType();
13333   bool isVariadic =
13334     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13335 
13336   CurBlock->TheDecl->setIsVariadic(isVariadic);
13337 
13338   // Context.DependentTy is used as a placeholder for a missing block
13339   // return type.  TODO:  what should we do with declarators like:
13340   //   ^ * { ... }
13341   // If the answer is "apply template argument deduction"....
13342   if (RetTy != Context.DependentTy) {
13343     CurBlock->ReturnType = RetTy;
13344     CurBlock->TheDecl->setBlockMissingReturnType(false);
13345     CurBlock->HasImplicitReturnType = false;
13346   }
13347 
13348   // Push block parameters from the declarator if we had them.
13349   SmallVector<ParmVarDecl*, 8> Params;
13350   if (ExplicitSignature) {
13351     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13352       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13353       if (Param->getIdentifier() == nullptr &&
13354           !Param->isImplicit() &&
13355           !Param->isInvalidDecl() &&
13356           !getLangOpts().CPlusPlus)
13357         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13358       Params.push_back(Param);
13359     }
13360 
13361   // Fake up parameter variables if we have a typedef, like
13362   //   ^ fntype { ... }
13363   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13364     for (const auto &I : Fn->param_types()) {
13365       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13366           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13367       Params.push_back(Param);
13368     }
13369   }
13370 
13371   // Set the parameters on the block decl.
13372   if (!Params.empty()) {
13373     CurBlock->TheDecl->setParams(Params);
13374     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13375                              /*CheckParameterNames=*/false);
13376   }
13377 
13378   // Finally we can process decl attributes.
13379   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13380 
13381   // Put the parameter variables in scope.
13382   for (auto AI : CurBlock->TheDecl->parameters()) {
13383     AI->setOwningFunction(CurBlock->TheDecl);
13384 
13385     // If this has an identifier, add it to the scope stack.
13386     if (AI->getIdentifier()) {
13387       CheckShadow(CurBlock->TheScope, AI);
13388 
13389       PushOnScopeChains(AI, CurBlock->TheScope);
13390     }
13391   }
13392 }
13393 
13394 /// ActOnBlockError - If there is an error parsing a block, this callback
13395 /// is invoked to pop the information about the block from the action impl.
13396 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13397   // Leave the expression-evaluation context.
13398   DiscardCleanupsInEvaluationContext();
13399   PopExpressionEvaluationContext();
13400 
13401   // Pop off CurBlock, handle nested blocks.
13402   PopDeclContext();
13403   PopFunctionScopeInfo();
13404 }
13405 
13406 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13407 /// literal was successfully completed.  ^(int x){...}
13408 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13409                                     Stmt *Body, Scope *CurScope) {
13410   // If blocks are disabled, emit an error.
13411   if (!LangOpts.Blocks)
13412     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13413 
13414   // Leave the expression-evaluation context.
13415   if (hasAnyUnrecoverableErrorsInThisFunction())
13416     DiscardCleanupsInEvaluationContext();
13417   assert(!Cleanup.exprNeedsCleanups() &&
13418          "cleanups within block not correctly bound!");
13419   PopExpressionEvaluationContext();
13420 
13421   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13422 
13423   if (BSI->HasImplicitReturnType)
13424     deduceClosureReturnType(*BSI);
13425 
13426   PopDeclContext();
13427 
13428   QualType RetTy = Context.VoidTy;
13429   if (!BSI->ReturnType.isNull())
13430     RetTy = BSI->ReturnType;
13431 
13432   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13433   QualType BlockTy;
13434 
13435   // Set the captured variables on the block.
13436   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13437   SmallVector<BlockDecl::Capture, 4> Captures;
13438   for (Capture &Cap : BSI->Captures) {
13439     if (Cap.isThisCapture())
13440       continue;
13441     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13442                               Cap.isNested(), Cap.getInitExpr());
13443     Captures.push_back(NewCap);
13444   }
13445   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13446 
13447   // If the user wrote a function type in some form, try to use that.
13448   if (!BSI->FunctionType.isNull()) {
13449     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13450 
13451     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13452     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13453 
13454     // Turn protoless block types into nullary block types.
13455     if (isa<FunctionNoProtoType>(FTy)) {
13456       FunctionProtoType::ExtProtoInfo EPI;
13457       EPI.ExtInfo = Ext;
13458       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13459 
13460     // Otherwise, if we don't need to change anything about the function type,
13461     // preserve its sugar structure.
13462     } else if (FTy->getReturnType() == RetTy &&
13463                (!NoReturn || FTy->getNoReturnAttr())) {
13464       BlockTy = BSI->FunctionType;
13465 
13466     // Otherwise, make the minimal modifications to the function type.
13467     } else {
13468       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13469       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13470       EPI.TypeQuals = 0; // FIXME: silently?
13471       EPI.ExtInfo = Ext;
13472       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13473     }
13474 
13475   // If we don't have a function type, just build one from nothing.
13476   } else {
13477     FunctionProtoType::ExtProtoInfo EPI;
13478     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13479     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13480   }
13481 
13482   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13483   BlockTy = Context.getBlockPointerType(BlockTy);
13484 
13485   // If needed, diagnose invalid gotos and switches in the block.
13486   if (getCurFunction()->NeedsScopeChecking() &&
13487       !PP.isCodeCompletionEnabled())
13488     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13489 
13490   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13491 
13492   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13493     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13494 
13495   // Try to apply the named return value optimization. We have to check again
13496   // if we can do this, though, because blocks keep return statements around
13497   // to deduce an implicit return type.
13498   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13499       !BSI->TheDecl->isDependentContext())
13500     computeNRVO(Body, BSI);
13501 
13502   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13503   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13504   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13505 
13506   // If the block isn't obviously global, i.e. it captures anything at
13507   // all, then we need to do a few things in the surrounding context:
13508   if (Result->getBlockDecl()->hasCaptures()) {
13509     // First, this expression has a new cleanup object.
13510     ExprCleanupObjects.push_back(Result->getBlockDecl());
13511     Cleanup.setExprNeedsCleanups(true);
13512 
13513     // It also gets a branch-protected scope if any of the captured
13514     // variables needs destruction.
13515     for (const auto &CI : Result->getBlockDecl()->captures()) {
13516       const VarDecl *var = CI.getVariable();
13517       if (var->getType().isDestructedType() != QualType::DK_none) {
13518         setFunctionHasBranchProtectedScope();
13519         break;
13520       }
13521     }
13522   }
13523 
13524   return Result;
13525 }
13526 
13527 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13528                             SourceLocation RPLoc) {
13529   TypeSourceInfo *TInfo;
13530   GetTypeFromParser(Ty, &TInfo);
13531   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13532 }
13533 
13534 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13535                                 Expr *E, TypeSourceInfo *TInfo,
13536                                 SourceLocation RPLoc) {
13537   Expr *OrigExpr = E;
13538   bool IsMS = false;
13539 
13540   // CUDA device code does not support varargs.
13541   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13542     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13543       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13544       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13545         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13546     }
13547   }
13548 
13549   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13550   // as Microsoft ABI on an actual Microsoft platform, where
13551   // __builtin_ms_va_list and __builtin_va_list are the same.)
13552   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13553       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13554     QualType MSVaListType = Context.getBuiltinMSVaListType();
13555     if (Context.hasSameType(MSVaListType, E->getType())) {
13556       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13557         return ExprError();
13558       IsMS = true;
13559     }
13560   }
13561 
13562   // Get the va_list type
13563   QualType VaListType = Context.getBuiltinVaListType();
13564   if (!IsMS) {
13565     if (VaListType->isArrayType()) {
13566       // Deal with implicit array decay; for example, on x86-64,
13567       // va_list is an array, but it's supposed to decay to
13568       // a pointer for va_arg.
13569       VaListType = Context.getArrayDecayedType(VaListType);
13570       // Make sure the input expression also decays appropriately.
13571       ExprResult Result = UsualUnaryConversions(E);
13572       if (Result.isInvalid())
13573         return ExprError();
13574       E = Result.get();
13575     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13576       // If va_list is a record type and we are compiling in C++ mode,
13577       // check the argument using reference binding.
13578       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13579           Context, Context.getLValueReferenceType(VaListType), false);
13580       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13581       if (Init.isInvalid())
13582         return ExprError();
13583       E = Init.getAs<Expr>();
13584     } else {
13585       // Otherwise, the va_list argument must be an l-value because
13586       // it is modified by va_arg.
13587       if (!E->isTypeDependent() &&
13588           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13589         return ExprError();
13590     }
13591   }
13592 
13593   if (!IsMS && !E->isTypeDependent() &&
13594       !Context.hasSameType(VaListType, E->getType()))
13595     return ExprError(Diag(E->getLocStart(),
13596                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13597       << OrigExpr->getType() << E->getSourceRange());
13598 
13599   if (!TInfo->getType()->isDependentType()) {
13600     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13601                             diag::err_second_parameter_to_va_arg_incomplete,
13602                             TInfo->getTypeLoc()))
13603       return ExprError();
13604 
13605     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13606                                TInfo->getType(),
13607                                diag::err_second_parameter_to_va_arg_abstract,
13608                                TInfo->getTypeLoc()))
13609       return ExprError();
13610 
13611     if (!TInfo->getType().isPODType(Context)) {
13612       Diag(TInfo->getTypeLoc().getBeginLoc(),
13613            TInfo->getType()->isObjCLifetimeType()
13614              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13615              : diag::warn_second_parameter_to_va_arg_not_pod)
13616         << TInfo->getType()
13617         << TInfo->getTypeLoc().getSourceRange();
13618     }
13619 
13620     // Check for va_arg where arguments of the given type will be promoted
13621     // (i.e. this va_arg is guaranteed to have undefined behavior).
13622     QualType PromoteType;
13623     if (TInfo->getType()->isPromotableIntegerType()) {
13624       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13625       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13626         PromoteType = QualType();
13627     }
13628     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13629       PromoteType = Context.DoubleTy;
13630     if (!PromoteType.isNull())
13631       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13632                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13633                           << TInfo->getType()
13634                           << PromoteType
13635                           << TInfo->getTypeLoc().getSourceRange());
13636   }
13637 
13638   QualType T = TInfo->getType().getNonLValueExprType(Context);
13639   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13640 }
13641 
13642 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13643   // The type of __null will be int or long, depending on the size of
13644   // pointers on the target.
13645   QualType Ty;
13646   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13647   if (pw == Context.getTargetInfo().getIntWidth())
13648     Ty = Context.IntTy;
13649   else if (pw == Context.getTargetInfo().getLongWidth())
13650     Ty = Context.LongTy;
13651   else if (pw == Context.getTargetInfo().getLongLongWidth())
13652     Ty = Context.LongLongTy;
13653   else {
13654     llvm_unreachable("I don't know size of pointer!");
13655   }
13656 
13657   return new (Context) GNUNullExpr(Ty, TokenLoc);
13658 }
13659 
13660 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13661                                               bool Diagnose) {
13662   if (!getLangOpts().ObjC1)
13663     return false;
13664 
13665   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13666   if (!PT)
13667     return false;
13668 
13669   if (!PT->isObjCIdType()) {
13670     // Check if the destination is the 'NSString' interface.
13671     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13672     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13673       return false;
13674   }
13675 
13676   // Ignore any parens, implicit casts (should only be
13677   // array-to-pointer decays), and not-so-opaque values.  The last is
13678   // important for making this trigger for property assignments.
13679   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13680   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13681     if (OV->getSourceExpr())
13682       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13683 
13684   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13685   if (!SL || !SL->isAscii())
13686     return false;
13687   if (Diagnose) {
13688     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13689       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13690     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13691   }
13692   return true;
13693 }
13694 
13695 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13696                                               const Expr *SrcExpr) {
13697   if (!DstType->isFunctionPointerType() ||
13698       !SrcExpr->getType()->isFunctionType())
13699     return false;
13700 
13701   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13702   if (!DRE)
13703     return false;
13704 
13705   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13706   if (!FD)
13707     return false;
13708 
13709   return !S.checkAddressOfFunctionIsAvailable(FD,
13710                                               /*Complain=*/true,
13711                                               SrcExpr->getLocStart());
13712 }
13713 
13714 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13715                                     SourceLocation Loc,
13716                                     QualType DstType, QualType SrcType,
13717                                     Expr *SrcExpr, AssignmentAction Action,
13718                                     bool *Complained) {
13719   if (Complained)
13720     *Complained = false;
13721 
13722   // Decode the result (notice that AST's are still created for extensions).
13723   bool CheckInferredResultType = false;
13724   bool isInvalid = false;
13725   unsigned DiagKind = 0;
13726   FixItHint Hint;
13727   ConversionFixItGenerator ConvHints;
13728   bool MayHaveConvFixit = false;
13729   bool MayHaveFunctionDiff = false;
13730   const ObjCInterfaceDecl *IFace = nullptr;
13731   const ObjCProtocolDecl *PDecl = nullptr;
13732 
13733   switch (ConvTy) {
13734   case Compatible:
13735       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13736       return false;
13737 
13738   case PointerToInt:
13739     DiagKind = diag::ext_typecheck_convert_pointer_int;
13740     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13741     MayHaveConvFixit = true;
13742     break;
13743   case IntToPointer:
13744     DiagKind = diag::ext_typecheck_convert_int_pointer;
13745     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13746     MayHaveConvFixit = true;
13747     break;
13748   case IncompatiblePointer:
13749     if (Action == AA_Passing_CFAudited)
13750       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13751     else if (SrcType->isFunctionPointerType() &&
13752              DstType->isFunctionPointerType())
13753       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13754     else
13755       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13756 
13757     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13758       SrcType->isObjCObjectPointerType();
13759     if (Hint.isNull() && !CheckInferredResultType) {
13760       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13761     }
13762     else if (CheckInferredResultType) {
13763       SrcType = SrcType.getUnqualifiedType();
13764       DstType = DstType.getUnqualifiedType();
13765     }
13766     MayHaveConvFixit = true;
13767     break;
13768   case IncompatiblePointerSign:
13769     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13770     break;
13771   case FunctionVoidPointer:
13772     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13773     break;
13774   case IncompatiblePointerDiscardsQualifiers: {
13775     // Perform array-to-pointer decay if necessary.
13776     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13777 
13778     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13779     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13780     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13781       DiagKind = diag::err_typecheck_incompatible_address_space;
13782       break;
13783 
13784     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13785       DiagKind = diag::err_typecheck_incompatible_ownership;
13786       break;
13787     }
13788 
13789     llvm_unreachable("unknown error case for discarding qualifiers!");
13790     // fallthrough
13791   }
13792   case CompatiblePointerDiscardsQualifiers:
13793     // If the qualifiers lost were because we were applying the
13794     // (deprecated) C++ conversion from a string literal to a char*
13795     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13796     // Ideally, this check would be performed in
13797     // checkPointerTypesForAssignment. However, that would require a
13798     // bit of refactoring (so that the second argument is an
13799     // expression, rather than a type), which should be done as part
13800     // of a larger effort to fix checkPointerTypesForAssignment for
13801     // C++ semantics.
13802     if (getLangOpts().CPlusPlus &&
13803         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13804       return false;
13805     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13806     break;
13807   case IncompatibleNestedPointerQualifiers:
13808     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13809     break;
13810   case IntToBlockPointer:
13811     DiagKind = diag::err_int_to_block_pointer;
13812     break;
13813   case IncompatibleBlockPointer:
13814     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13815     break;
13816   case IncompatibleObjCQualifiedId: {
13817     if (SrcType->isObjCQualifiedIdType()) {
13818       const ObjCObjectPointerType *srcOPT =
13819                 SrcType->getAs<ObjCObjectPointerType>();
13820       for (auto *srcProto : srcOPT->quals()) {
13821         PDecl = srcProto;
13822         break;
13823       }
13824       if (const ObjCInterfaceType *IFaceT =
13825             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13826         IFace = IFaceT->getDecl();
13827     }
13828     else if (DstType->isObjCQualifiedIdType()) {
13829       const ObjCObjectPointerType *dstOPT =
13830         DstType->getAs<ObjCObjectPointerType>();
13831       for (auto *dstProto : dstOPT->quals()) {
13832         PDecl = dstProto;
13833         break;
13834       }
13835       if (const ObjCInterfaceType *IFaceT =
13836             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13837         IFace = IFaceT->getDecl();
13838     }
13839     DiagKind = diag::warn_incompatible_qualified_id;
13840     break;
13841   }
13842   case IncompatibleVectors:
13843     DiagKind = diag::warn_incompatible_vectors;
13844     break;
13845   case IncompatibleObjCWeakRef:
13846     DiagKind = diag::err_arc_weak_unavailable_assign;
13847     break;
13848   case Incompatible:
13849     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13850       if (Complained)
13851         *Complained = true;
13852       return true;
13853     }
13854 
13855     DiagKind = diag::err_typecheck_convert_incompatible;
13856     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13857     MayHaveConvFixit = true;
13858     isInvalid = true;
13859     MayHaveFunctionDiff = true;
13860     break;
13861   }
13862 
13863   QualType FirstType, SecondType;
13864   switch (Action) {
13865   case AA_Assigning:
13866   case AA_Initializing:
13867     // The destination type comes first.
13868     FirstType = DstType;
13869     SecondType = SrcType;
13870     break;
13871 
13872   case AA_Returning:
13873   case AA_Passing:
13874   case AA_Passing_CFAudited:
13875   case AA_Converting:
13876   case AA_Sending:
13877   case AA_Casting:
13878     // The source type comes first.
13879     FirstType = SrcType;
13880     SecondType = DstType;
13881     break;
13882   }
13883 
13884   PartialDiagnostic FDiag = PDiag(DiagKind);
13885   if (Action == AA_Passing_CFAudited)
13886     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13887   else
13888     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13889 
13890   // If we can fix the conversion, suggest the FixIts.
13891   assert(ConvHints.isNull() || Hint.isNull());
13892   if (!ConvHints.isNull()) {
13893     for (FixItHint &H : ConvHints.Hints)
13894       FDiag << H;
13895   } else {
13896     FDiag << Hint;
13897   }
13898   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13899 
13900   if (MayHaveFunctionDiff)
13901     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13902 
13903   Diag(Loc, FDiag);
13904   if (DiagKind == diag::warn_incompatible_qualified_id &&
13905       PDecl && IFace && !IFace->hasDefinition())
13906       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13907         << IFace << PDecl;
13908 
13909   if (SecondType == Context.OverloadTy)
13910     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13911                               FirstType, /*TakingAddress=*/true);
13912 
13913   if (CheckInferredResultType)
13914     EmitRelatedResultTypeNote(SrcExpr);
13915 
13916   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13917     EmitRelatedResultTypeNoteForReturn(DstType);
13918 
13919   if (Complained)
13920     *Complained = true;
13921   return isInvalid;
13922 }
13923 
13924 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13925                                                  llvm::APSInt *Result) {
13926   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13927   public:
13928     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13929       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13930     }
13931   } Diagnoser;
13932 
13933   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13934 }
13935 
13936 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13937                                                  llvm::APSInt *Result,
13938                                                  unsigned DiagID,
13939                                                  bool AllowFold) {
13940   class IDDiagnoser : public VerifyICEDiagnoser {
13941     unsigned DiagID;
13942 
13943   public:
13944     IDDiagnoser(unsigned DiagID)
13945       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13946 
13947     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13948       S.Diag(Loc, DiagID) << SR;
13949     }
13950   } Diagnoser(DiagID);
13951 
13952   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13953 }
13954 
13955 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13956                                             SourceRange SR) {
13957   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13958 }
13959 
13960 ExprResult
13961 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13962                                       VerifyICEDiagnoser &Diagnoser,
13963                                       bool AllowFold) {
13964   SourceLocation DiagLoc = E->getLocStart();
13965 
13966   if (getLangOpts().CPlusPlus11) {
13967     // C++11 [expr.const]p5:
13968     //   If an expression of literal class type is used in a context where an
13969     //   integral constant expression is required, then that class type shall
13970     //   have a single non-explicit conversion function to an integral or
13971     //   unscoped enumeration type
13972     ExprResult Converted;
13973     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13974     public:
13975       CXX11ConvertDiagnoser(bool Silent)
13976           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13977                                 Silent, true) {}
13978 
13979       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13980                                            QualType T) override {
13981         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13982       }
13983 
13984       SemaDiagnosticBuilder diagnoseIncomplete(
13985           Sema &S, SourceLocation Loc, QualType T) override {
13986         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13987       }
13988 
13989       SemaDiagnosticBuilder diagnoseExplicitConv(
13990           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13991         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13992       }
13993 
13994       SemaDiagnosticBuilder noteExplicitConv(
13995           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13996         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13997                  << ConvTy->isEnumeralType() << ConvTy;
13998       }
13999 
14000       SemaDiagnosticBuilder diagnoseAmbiguous(
14001           Sema &S, SourceLocation Loc, QualType T) override {
14002         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14003       }
14004 
14005       SemaDiagnosticBuilder noteAmbiguous(
14006           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14007         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14008                  << ConvTy->isEnumeralType() << ConvTy;
14009       }
14010 
14011       SemaDiagnosticBuilder diagnoseConversion(
14012           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14013         llvm_unreachable("conversion functions are permitted");
14014       }
14015     } ConvertDiagnoser(Diagnoser.Suppress);
14016 
14017     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14018                                                     ConvertDiagnoser);
14019     if (Converted.isInvalid())
14020       return Converted;
14021     E = Converted.get();
14022     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14023       return ExprError();
14024   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14025     // An ICE must be of integral or unscoped enumeration type.
14026     if (!Diagnoser.Suppress)
14027       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14028     return ExprError();
14029   }
14030 
14031   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14032   // in the non-ICE case.
14033   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14034     if (Result)
14035       *Result = E->EvaluateKnownConstInt(Context);
14036     return E;
14037   }
14038 
14039   Expr::EvalResult EvalResult;
14040   SmallVector<PartialDiagnosticAt, 8> Notes;
14041   EvalResult.Diag = &Notes;
14042 
14043   // Try to evaluate the expression, and produce diagnostics explaining why it's
14044   // not a constant expression as a side-effect.
14045   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14046                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14047 
14048   // In C++11, we can rely on diagnostics being produced for any expression
14049   // which is not a constant expression. If no diagnostics were produced, then
14050   // this is a constant expression.
14051   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14052     if (Result)
14053       *Result = EvalResult.Val.getInt();
14054     return E;
14055   }
14056 
14057   // If our only note is the usual "invalid subexpression" note, just point
14058   // the caret at its location rather than producing an essentially
14059   // redundant note.
14060   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14061         diag::note_invalid_subexpr_in_const_expr) {
14062     DiagLoc = Notes[0].first;
14063     Notes.clear();
14064   }
14065 
14066   if (!Folded || !AllowFold) {
14067     if (!Diagnoser.Suppress) {
14068       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14069       for (const PartialDiagnosticAt &Note : Notes)
14070         Diag(Note.first, Note.second);
14071     }
14072 
14073     return ExprError();
14074   }
14075 
14076   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14077   for (const PartialDiagnosticAt &Note : Notes)
14078     Diag(Note.first, Note.second);
14079 
14080   if (Result)
14081     *Result = EvalResult.Val.getInt();
14082   return E;
14083 }
14084 
14085 namespace {
14086   // Handle the case where we conclude a expression which we speculatively
14087   // considered to be unevaluated is actually evaluated.
14088   class TransformToPE : public TreeTransform<TransformToPE> {
14089     typedef TreeTransform<TransformToPE> BaseTransform;
14090 
14091   public:
14092     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14093 
14094     // Make sure we redo semantic analysis
14095     bool AlwaysRebuild() { return true; }
14096 
14097     // Make sure we handle LabelStmts correctly.
14098     // FIXME: This does the right thing, but maybe we need a more general
14099     // fix to TreeTransform?
14100     StmtResult TransformLabelStmt(LabelStmt *S) {
14101       S->getDecl()->setStmt(nullptr);
14102       return BaseTransform::TransformLabelStmt(S);
14103     }
14104 
14105     // We need to special-case DeclRefExprs referring to FieldDecls which
14106     // are not part of a member pointer formation; normal TreeTransforming
14107     // doesn't catch this case because of the way we represent them in the AST.
14108     // FIXME: This is a bit ugly; is it really the best way to handle this
14109     // case?
14110     //
14111     // Error on DeclRefExprs referring to FieldDecls.
14112     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14113       if (isa<FieldDecl>(E->getDecl()) &&
14114           !SemaRef.isUnevaluatedContext())
14115         return SemaRef.Diag(E->getLocation(),
14116                             diag::err_invalid_non_static_member_use)
14117             << E->getDecl() << E->getSourceRange();
14118 
14119       return BaseTransform::TransformDeclRefExpr(E);
14120     }
14121 
14122     // Exception: filter out member pointer formation
14123     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14124       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14125         return E;
14126 
14127       return BaseTransform::TransformUnaryOperator(E);
14128     }
14129 
14130     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14131       // Lambdas never need to be transformed.
14132       return E;
14133     }
14134   };
14135 }
14136 
14137 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14138   assert(isUnevaluatedContext() &&
14139          "Should only transform unevaluated expressions");
14140   ExprEvalContexts.back().Context =
14141       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14142   if (isUnevaluatedContext())
14143     return E;
14144   return TransformToPE(*this).TransformExpr(E);
14145 }
14146 
14147 void
14148 Sema::PushExpressionEvaluationContext(
14149     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14150     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14151   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14152                                 LambdaContextDecl, ExprContext);
14153   Cleanup.reset();
14154   if (!MaybeODRUseExprs.empty())
14155     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14156 }
14157 
14158 void
14159 Sema::PushExpressionEvaluationContext(
14160     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14161     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14162   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14163   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14164 }
14165 
14166 void Sema::PopExpressionEvaluationContext() {
14167   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14168   unsigned NumTypos = Rec.NumTypos;
14169 
14170   if (!Rec.Lambdas.empty()) {
14171     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14172     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14173         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14174       unsigned D;
14175       if (Rec.isUnevaluated()) {
14176         // C++11 [expr.prim.lambda]p2:
14177         //   A lambda-expression shall not appear in an unevaluated operand
14178         //   (Clause 5).
14179         D = diag::err_lambda_unevaluated_operand;
14180       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14181         // C++1y [expr.const]p2:
14182         //   A conditional-expression e is a core constant expression unless the
14183         //   evaluation of e, following the rules of the abstract machine, would
14184         //   evaluate [...] a lambda-expression.
14185         D = diag::err_lambda_in_constant_expression;
14186       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14187         // C++17 [expr.prim.lamda]p2:
14188         // A lambda-expression shall not appear [...] in a template-argument.
14189         D = diag::err_lambda_in_invalid_context;
14190       } else
14191         llvm_unreachable("Couldn't infer lambda error message.");
14192 
14193       for (const auto *L : Rec.Lambdas)
14194         Diag(L->getLocStart(), D);
14195     } else {
14196       // Mark the capture expressions odr-used. This was deferred
14197       // during lambda expression creation.
14198       for (auto *Lambda : Rec.Lambdas) {
14199         for (auto *C : Lambda->capture_inits())
14200           MarkDeclarationsReferencedInExpr(C);
14201       }
14202     }
14203   }
14204 
14205   // When are coming out of an unevaluated context, clear out any
14206   // temporaries that we may have created as part of the evaluation of
14207   // the expression in that context: they aren't relevant because they
14208   // will never be constructed.
14209   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14210     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14211                              ExprCleanupObjects.end());
14212     Cleanup = Rec.ParentCleanup;
14213     CleanupVarDeclMarking();
14214     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14215   // Otherwise, merge the contexts together.
14216   } else {
14217     Cleanup.mergeFrom(Rec.ParentCleanup);
14218     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14219                             Rec.SavedMaybeODRUseExprs.end());
14220   }
14221 
14222   // Pop the current expression evaluation context off the stack.
14223   ExprEvalContexts.pop_back();
14224 
14225   if (!ExprEvalContexts.empty())
14226     ExprEvalContexts.back().NumTypos += NumTypos;
14227   else
14228     assert(NumTypos == 0 && "There are outstanding typos after popping the "
14229                             "last ExpressionEvaluationContextRecord");
14230 }
14231 
14232 void Sema::DiscardCleanupsInEvaluationContext() {
14233   ExprCleanupObjects.erase(
14234          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14235          ExprCleanupObjects.end());
14236   Cleanup.reset();
14237   MaybeODRUseExprs.clear();
14238 }
14239 
14240 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14241   if (!E->getType()->isVariablyModifiedType())
14242     return E;
14243   return TransformToPotentiallyEvaluated(E);
14244 }
14245 
14246 /// Are we within a context in which some evaluation could be performed (be it
14247 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14248 /// captured by C++'s idea of an "unevaluated context".
14249 static bool isEvaluatableContext(Sema &SemaRef) {
14250   switch (SemaRef.ExprEvalContexts.back().Context) {
14251     case Sema::ExpressionEvaluationContext::Unevaluated:
14252     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14253       // Expressions in this context are never evaluated.
14254       return false;
14255 
14256     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14257     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14258     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14259     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14260       // Expressions in this context could be evaluated.
14261       return true;
14262 
14263     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14264       // Referenced declarations will only be used if the construct in the
14265       // containing expression is used, at which point we'll be given another
14266       // turn to mark them.
14267       return false;
14268   }
14269   llvm_unreachable("Invalid context");
14270 }
14271 
14272 /// Are we within a context in which references to resolved functions or to
14273 /// variables result in odr-use?
14274 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14275   // An expression in a template is not really an expression until it's been
14276   // instantiated, so it doesn't trigger odr-use.
14277   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14278     return false;
14279 
14280   switch (SemaRef.ExprEvalContexts.back().Context) {
14281     case Sema::ExpressionEvaluationContext::Unevaluated:
14282     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14283     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14284     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14285       return false;
14286 
14287     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14288     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14289       return true;
14290 
14291     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14292       return false;
14293   }
14294   llvm_unreachable("Invalid context");
14295 }
14296 
14297 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14298   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14299   return Func->isConstexpr() &&
14300          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14301 }
14302 
14303 /// Mark a function referenced, and check whether it is odr-used
14304 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14305 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14306                                   bool MightBeOdrUse) {
14307   assert(Func && "No function?");
14308 
14309   Func->setReferenced();
14310 
14311   // C++11 [basic.def.odr]p3:
14312   //   A function whose name appears as a potentially-evaluated expression is
14313   //   odr-used if it is the unique lookup result or the selected member of a
14314   //   set of overloaded functions [...].
14315   //
14316   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14317   // can just check that here.
14318   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14319 
14320   // Determine whether we require a function definition to exist, per
14321   // C++11 [temp.inst]p3:
14322   //   Unless a function template specialization has been explicitly
14323   //   instantiated or explicitly specialized, the function template
14324   //   specialization is implicitly instantiated when the specialization is
14325   //   referenced in a context that requires a function definition to exist.
14326   //
14327   // That is either when this is an odr-use, or when a usage of a constexpr
14328   // function occurs within an evaluatable context.
14329   bool NeedDefinition =
14330       OdrUse || (isEvaluatableContext(*this) &&
14331                  isImplicitlyDefinableConstexprFunction(Func));
14332 
14333   // C++14 [temp.expl.spec]p6:
14334   //   If a template [...] is explicitly specialized then that specialization
14335   //   shall be declared before the first use of that specialization that would
14336   //   cause an implicit instantiation to take place, in every translation unit
14337   //   in which such a use occurs
14338   if (NeedDefinition &&
14339       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14340        Func->getMemberSpecializationInfo()))
14341     checkSpecializationVisibility(Loc, Func);
14342 
14343   // C++14 [except.spec]p17:
14344   //   An exception-specification is considered to be needed when:
14345   //   - the function is odr-used or, if it appears in an unevaluated operand,
14346   //     would be odr-used if the expression were potentially-evaluated;
14347   //
14348   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14349   // function is a pure virtual function we're calling, and in that case the
14350   // function was selected by overload resolution and we need to resolve its
14351   // exception specification for a different reason.
14352   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14353   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14354     ResolveExceptionSpec(Loc, FPT);
14355 
14356   // If we don't need to mark the function as used, and we don't need to
14357   // try to provide a definition, there's nothing more to do.
14358   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14359       (!NeedDefinition || Func->getBody()))
14360     return;
14361 
14362   // Note that this declaration has been used.
14363   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14364     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14365     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14366       if (Constructor->isDefaultConstructor()) {
14367         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14368           return;
14369         DefineImplicitDefaultConstructor(Loc, Constructor);
14370       } else if (Constructor->isCopyConstructor()) {
14371         DefineImplicitCopyConstructor(Loc, Constructor);
14372       } else if (Constructor->isMoveConstructor()) {
14373         DefineImplicitMoveConstructor(Loc, Constructor);
14374       }
14375     } else if (Constructor->getInheritedConstructor()) {
14376       DefineInheritingConstructor(Loc, Constructor);
14377     }
14378   } else if (CXXDestructorDecl *Destructor =
14379                  dyn_cast<CXXDestructorDecl>(Func)) {
14380     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14381     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14382       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14383         return;
14384       DefineImplicitDestructor(Loc, Destructor);
14385     }
14386     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14387       MarkVTableUsed(Loc, Destructor->getParent());
14388   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14389     if (MethodDecl->isOverloadedOperator() &&
14390         MethodDecl->getOverloadedOperator() == OO_Equal) {
14391       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14392       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14393         if (MethodDecl->isCopyAssignmentOperator())
14394           DefineImplicitCopyAssignment(Loc, MethodDecl);
14395         else if (MethodDecl->isMoveAssignmentOperator())
14396           DefineImplicitMoveAssignment(Loc, MethodDecl);
14397       }
14398     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14399                MethodDecl->getParent()->isLambda()) {
14400       CXXConversionDecl *Conversion =
14401           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14402       if (Conversion->isLambdaToBlockPointerConversion())
14403         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14404       else
14405         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14406     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14407       MarkVTableUsed(Loc, MethodDecl->getParent());
14408   }
14409 
14410   // Recursive functions should be marked when used from another function.
14411   // FIXME: Is this really right?
14412   if (CurContext == Func) return;
14413 
14414   // Implicit instantiation of function templates and member functions of
14415   // class templates.
14416   if (Func->isImplicitlyInstantiable()) {
14417     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14418     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14419     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14420     if (FirstInstantiation) {
14421       PointOfInstantiation = Loc;
14422       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14423     } else if (TSK != TSK_ImplicitInstantiation) {
14424       // Use the point of use as the point of instantiation, instead of the
14425       // point of explicit instantiation (which we track as the actual point of
14426       // instantiation). This gives better backtraces in diagnostics.
14427       PointOfInstantiation = Loc;
14428     }
14429 
14430     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14431         Func->isConstexpr()) {
14432       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14433           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14434           CodeSynthesisContexts.size())
14435         PendingLocalImplicitInstantiations.push_back(
14436             std::make_pair(Func, PointOfInstantiation));
14437       else if (Func->isConstexpr())
14438         // Do not defer instantiations of constexpr functions, to avoid the
14439         // expression evaluator needing to call back into Sema if it sees a
14440         // call to such a function.
14441         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14442       else {
14443         Func->setInstantiationIsPending(true);
14444         PendingInstantiations.push_back(std::make_pair(Func,
14445                                                        PointOfInstantiation));
14446         // Notify the consumer that a function was implicitly instantiated.
14447         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14448       }
14449     }
14450   } else {
14451     // Walk redefinitions, as some of them may be instantiable.
14452     for (auto i : Func->redecls()) {
14453       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14454         MarkFunctionReferenced(Loc, i, OdrUse);
14455     }
14456   }
14457 
14458   if (!OdrUse) return;
14459 
14460   // Keep track of used but undefined functions.
14461   if (!Func->isDefined()) {
14462     if (mightHaveNonExternalLinkage(Func))
14463       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14464     else if (Func->getMostRecentDecl()->isInlined() &&
14465              !LangOpts.GNUInline &&
14466              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14467       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14468     else if (isExternalWithNoLinkageType(Func))
14469       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14470   }
14471 
14472   Func->markUsed(Context);
14473 }
14474 
14475 static void
14476 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14477                                    ValueDecl *var, DeclContext *DC) {
14478   DeclContext *VarDC = var->getDeclContext();
14479 
14480   //  If the parameter still belongs to the translation unit, then
14481   //  we're actually just using one parameter in the declaration of
14482   //  the next.
14483   if (isa<ParmVarDecl>(var) &&
14484       isa<TranslationUnitDecl>(VarDC))
14485     return;
14486 
14487   // For C code, don't diagnose about capture if we're not actually in code
14488   // right now; it's impossible to write a non-constant expression outside of
14489   // function context, so we'll get other (more useful) diagnostics later.
14490   //
14491   // For C++, things get a bit more nasty... it would be nice to suppress this
14492   // diagnostic for certain cases like using a local variable in an array bound
14493   // for a member of a local class, but the correct predicate is not obvious.
14494   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14495     return;
14496 
14497   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14498   unsigned ContextKind = 3; // unknown
14499   if (isa<CXXMethodDecl>(VarDC) &&
14500       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14501     ContextKind = 2;
14502   } else if (isa<FunctionDecl>(VarDC)) {
14503     ContextKind = 0;
14504   } else if (isa<BlockDecl>(VarDC)) {
14505     ContextKind = 1;
14506   }
14507 
14508   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14509     << var << ValueKind << ContextKind << VarDC;
14510   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14511       << var;
14512 
14513   // FIXME: Add additional diagnostic info about class etc. which prevents
14514   // capture.
14515 }
14516 
14517 
14518 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14519                                       bool &SubCapturesAreNested,
14520                                       QualType &CaptureType,
14521                                       QualType &DeclRefType) {
14522    // Check whether we've already captured it.
14523   if (CSI->CaptureMap.count(Var)) {
14524     // If we found a capture, any subcaptures are nested.
14525     SubCapturesAreNested = true;
14526 
14527     // Retrieve the capture type for this variable.
14528     CaptureType = CSI->getCapture(Var).getCaptureType();
14529 
14530     // Compute the type of an expression that refers to this variable.
14531     DeclRefType = CaptureType.getNonReferenceType();
14532 
14533     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14534     // are mutable in the sense that user can change their value - they are
14535     // private instances of the captured declarations.
14536     const Capture &Cap = CSI->getCapture(Var);
14537     if (Cap.isCopyCapture() &&
14538         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14539         !(isa<CapturedRegionScopeInfo>(CSI) &&
14540           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14541       DeclRefType.addConst();
14542     return true;
14543   }
14544   return false;
14545 }
14546 
14547 // Only block literals, captured statements, and lambda expressions can
14548 // capture; other scopes don't work.
14549 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14550                                  SourceLocation Loc,
14551                                  const bool Diagnose, Sema &S) {
14552   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14553     return getLambdaAwareParentOfDeclContext(DC);
14554   else if (Var->hasLocalStorage()) {
14555     if (Diagnose)
14556        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14557   }
14558   return nullptr;
14559 }
14560 
14561 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14562 // certain types of variables (unnamed, variably modified types etc.)
14563 // so check for eligibility.
14564 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14565                                  SourceLocation Loc,
14566                                  const bool Diagnose, Sema &S) {
14567 
14568   bool IsBlock = isa<BlockScopeInfo>(CSI);
14569   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14570 
14571   // Lambdas are not allowed to capture unnamed variables
14572   // (e.g. anonymous unions).
14573   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14574   // assuming that's the intent.
14575   if (IsLambda && !Var->getDeclName()) {
14576     if (Diagnose) {
14577       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14578       S.Diag(Var->getLocation(), diag::note_declared_at);
14579     }
14580     return false;
14581   }
14582 
14583   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14584   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14585     if (Diagnose) {
14586       S.Diag(Loc, diag::err_ref_vm_type);
14587       S.Diag(Var->getLocation(), diag::note_previous_decl)
14588         << Var->getDeclName();
14589     }
14590     return false;
14591   }
14592   // Prohibit structs with flexible array members too.
14593   // We cannot capture what is in the tail end of the struct.
14594   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14595     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14596       if (Diagnose) {
14597         if (IsBlock)
14598           S.Diag(Loc, diag::err_ref_flexarray_type);
14599         else
14600           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14601             << Var->getDeclName();
14602         S.Diag(Var->getLocation(), diag::note_previous_decl)
14603           << Var->getDeclName();
14604       }
14605       return false;
14606     }
14607   }
14608   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14609   // Lambdas and captured statements are not allowed to capture __block
14610   // variables; they don't support the expected semantics.
14611   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14612     if (Diagnose) {
14613       S.Diag(Loc, diag::err_capture_block_variable)
14614         << Var->getDeclName() << !IsLambda;
14615       S.Diag(Var->getLocation(), diag::note_previous_decl)
14616         << Var->getDeclName();
14617     }
14618     return false;
14619   }
14620   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14621   if (S.getLangOpts().OpenCL && IsBlock &&
14622       Var->getType()->isBlockPointerType()) {
14623     if (Diagnose)
14624       S.Diag(Loc, diag::err_opencl_block_ref_block);
14625     return false;
14626   }
14627 
14628   return true;
14629 }
14630 
14631 // Returns true if the capture by block was successful.
14632 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14633                                  SourceLocation Loc,
14634                                  const bool BuildAndDiagnose,
14635                                  QualType &CaptureType,
14636                                  QualType &DeclRefType,
14637                                  const bool Nested,
14638                                  Sema &S) {
14639   Expr *CopyExpr = nullptr;
14640   bool ByRef = false;
14641 
14642   // Blocks are not allowed to capture arrays.
14643   if (CaptureType->isArrayType()) {
14644     if (BuildAndDiagnose) {
14645       S.Diag(Loc, diag::err_ref_array_type);
14646       S.Diag(Var->getLocation(), diag::note_previous_decl)
14647       << Var->getDeclName();
14648     }
14649     return false;
14650   }
14651 
14652   // Forbid the block-capture of autoreleasing variables.
14653   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14654     if (BuildAndDiagnose) {
14655       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14656         << /*block*/ 0;
14657       S.Diag(Var->getLocation(), diag::note_previous_decl)
14658         << Var->getDeclName();
14659     }
14660     return false;
14661   }
14662 
14663   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14664   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14665     // This function finds out whether there is an AttributedType of kind
14666     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14667     // attr_objc_ownership implies __autoreleasing was explicitly specified
14668     // rather than being added implicitly by the compiler.
14669     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14670       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14671         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14672           return true;
14673 
14674         // Peel off AttributedTypes that are not of kind objc_ownership.
14675         Ty = AttrTy->getModifiedType();
14676       }
14677 
14678       return false;
14679     };
14680 
14681     QualType PointeeTy = PT->getPointeeType();
14682 
14683     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14684         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14685         !IsObjCOwnershipAttributedType(PointeeTy)) {
14686       if (BuildAndDiagnose) {
14687         SourceLocation VarLoc = Var->getLocation();
14688         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14689         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14690       }
14691     }
14692   }
14693 
14694   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14695   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14696       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14697     // Block capture by reference does not change the capture or
14698     // declaration reference types.
14699     ByRef = true;
14700   } else {
14701     // Block capture by copy introduces 'const'.
14702     CaptureType = CaptureType.getNonReferenceType().withConst();
14703     DeclRefType = CaptureType;
14704 
14705     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14706       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14707         // The capture logic needs the destructor, so make sure we mark it.
14708         // Usually this is unnecessary because most local variables have
14709         // their destructors marked at declaration time, but parameters are
14710         // an exception because it's technically only the call site that
14711         // actually requires the destructor.
14712         if (isa<ParmVarDecl>(Var))
14713           S.FinalizeVarWithDestructor(Var, Record);
14714 
14715         // Enter a new evaluation context to insulate the copy
14716         // full-expression.
14717         EnterExpressionEvaluationContext scope(
14718             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14719 
14720         // According to the blocks spec, the capture of a variable from
14721         // the stack requires a const copy constructor.  This is not true
14722         // of the copy/move done to move a __block variable to the heap.
14723         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14724                                                   DeclRefType.withConst(),
14725                                                   VK_LValue, Loc);
14726 
14727         ExprResult Result
14728           = S.PerformCopyInitialization(
14729               InitializedEntity::InitializeBlock(Var->getLocation(),
14730                                                   CaptureType, false),
14731               Loc, DeclRef);
14732 
14733         // Build a full-expression copy expression if initialization
14734         // succeeded and used a non-trivial constructor.  Recover from
14735         // errors by pretending that the copy isn't necessary.
14736         if (!Result.isInvalid() &&
14737             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14738                 ->isTrivial()) {
14739           Result = S.MaybeCreateExprWithCleanups(Result);
14740           CopyExpr = Result.get();
14741         }
14742       }
14743     }
14744   }
14745 
14746   // Actually capture the variable.
14747   if (BuildAndDiagnose)
14748     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14749                     SourceLocation(), CaptureType, CopyExpr);
14750 
14751   return true;
14752 
14753 }
14754 
14755 
14756 /// Capture the given variable in the captured region.
14757 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14758                                     VarDecl *Var,
14759                                     SourceLocation Loc,
14760                                     const bool BuildAndDiagnose,
14761                                     QualType &CaptureType,
14762                                     QualType &DeclRefType,
14763                                     const bool RefersToCapturedVariable,
14764                                     Sema &S) {
14765   // By default, capture variables by reference.
14766   bool ByRef = true;
14767   // Using an LValue reference type is consistent with Lambdas (see below).
14768   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14769     if (S.isOpenMPCapturedDecl(Var)) {
14770       bool HasConst = DeclRefType.isConstQualified();
14771       DeclRefType = DeclRefType.getUnqualifiedType();
14772       // Don't lose diagnostics about assignments to const.
14773       if (HasConst)
14774         DeclRefType.addConst();
14775     }
14776     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14777   }
14778 
14779   if (ByRef)
14780     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14781   else
14782     CaptureType = DeclRefType;
14783 
14784   Expr *CopyExpr = nullptr;
14785   if (BuildAndDiagnose) {
14786     // The current implementation assumes that all variables are captured
14787     // by references. Since there is no capture by copy, no expression
14788     // evaluation will be needed.
14789     RecordDecl *RD = RSI->TheRecordDecl;
14790 
14791     FieldDecl *Field
14792       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14793                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14794                           nullptr, false, ICIS_NoInit);
14795     Field->setImplicit(true);
14796     Field->setAccess(AS_private);
14797     RD->addDecl(Field);
14798     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14799       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14800 
14801     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14802                                             DeclRefType, VK_LValue, Loc);
14803     Var->setReferenced(true);
14804     Var->markUsed(S.Context);
14805   }
14806 
14807   // Actually capture the variable.
14808   if (BuildAndDiagnose)
14809     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14810                     SourceLocation(), CaptureType, CopyExpr);
14811 
14812 
14813   return true;
14814 }
14815 
14816 /// Create a field within the lambda class for the variable
14817 /// being captured.
14818 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14819                                     QualType FieldType, QualType DeclRefType,
14820                                     SourceLocation Loc,
14821                                     bool RefersToCapturedVariable) {
14822   CXXRecordDecl *Lambda = LSI->Lambda;
14823 
14824   // Build the non-static data member.
14825   FieldDecl *Field
14826     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14827                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14828                         nullptr, false, ICIS_NoInit);
14829   Field->setImplicit(true);
14830   Field->setAccess(AS_private);
14831   Lambda->addDecl(Field);
14832 }
14833 
14834 /// Capture the given variable in the lambda.
14835 static bool captureInLambda(LambdaScopeInfo *LSI,
14836                             VarDecl *Var,
14837                             SourceLocation Loc,
14838                             const bool BuildAndDiagnose,
14839                             QualType &CaptureType,
14840                             QualType &DeclRefType,
14841                             const bool RefersToCapturedVariable,
14842                             const Sema::TryCaptureKind Kind,
14843                             SourceLocation EllipsisLoc,
14844                             const bool IsTopScope,
14845                             Sema &S) {
14846 
14847   // Determine whether we are capturing by reference or by value.
14848   bool ByRef = false;
14849   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14850     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14851   } else {
14852     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14853   }
14854 
14855   // Compute the type of the field that will capture this variable.
14856   if (ByRef) {
14857     // C++11 [expr.prim.lambda]p15:
14858     //   An entity is captured by reference if it is implicitly or
14859     //   explicitly captured but not captured by copy. It is
14860     //   unspecified whether additional unnamed non-static data
14861     //   members are declared in the closure type for entities
14862     //   captured by reference.
14863     //
14864     // FIXME: It is not clear whether we want to build an lvalue reference
14865     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14866     // to do the former, while EDG does the latter. Core issue 1249 will
14867     // clarify, but for now we follow GCC because it's a more permissive and
14868     // easily defensible position.
14869     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14870   } else {
14871     // C++11 [expr.prim.lambda]p14:
14872     //   For each entity captured by copy, an unnamed non-static
14873     //   data member is declared in the closure type. The
14874     //   declaration order of these members is unspecified. The type
14875     //   of such a data member is the type of the corresponding
14876     //   captured entity if the entity is not a reference to an
14877     //   object, or the referenced type otherwise. [Note: If the
14878     //   captured entity is a reference to a function, the
14879     //   corresponding data member is also a reference to a
14880     //   function. - end note ]
14881     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14882       if (!RefType->getPointeeType()->isFunctionType())
14883         CaptureType = RefType->getPointeeType();
14884     }
14885 
14886     // Forbid the lambda copy-capture of autoreleasing variables.
14887     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14888       if (BuildAndDiagnose) {
14889         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14890         S.Diag(Var->getLocation(), diag::note_previous_decl)
14891           << Var->getDeclName();
14892       }
14893       return false;
14894     }
14895 
14896     // Make sure that by-copy captures are of a complete and non-abstract type.
14897     if (BuildAndDiagnose) {
14898       if (!CaptureType->isDependentType() &&
14899           S.RequireCompleteType(Loc, CaptureType,
14900                                 diag::err_capture_of_incomplete_type,
14901                                 Var->getDeclName()))
14902         return false;
14903 
14904       if (S.RequireNonAbstractType(Loc, CaptureType,
14905                                    diag::err_capture_of_abstract_type))
14906         return false;
14907     }
14908   }
14909 
14910   // Capture this variable in the lambda.
14911   if (BuildAndDiagnose)
14912     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14913                             RefersToCapturedVariable);
14914 
14915   // Compute the type of a reference to this captured variable.
14916   if (ByRef)
14917     DeclRefType = CaptureType.getNonReferenceType();
14918   else {
14919     // C++ [expr.prim.lambda]p5:
14920     //   The closure type for a lambda-expression has a public inline
14921     //   function call operator [...]. This function call operator is
14922     //   declared const (9.3.1) if and only if the lambda-expression's
14923     //   parameter-declaration-clause is not followed by mutable.
14924     DeclRefType = CaptureType.getNonReferenceType();
14925     if (!LSI->Mutable && !CaptureType->isReferenceType())
14926       DeclRefType.addConst();
14927   }
14928 
14929   // Add the capture.
14930   if (BuildAndDiagnose)
14931     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14932                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14933 
14934   return true;
14935 }
14936 
14937 bool Sema::tryCaptureVariable(
14938     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14939     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14940     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14941   // An init-capture is notionally from the context surrounding its
14942   // declaration, but its parent DC is the lambda class.
14943   DeclContext *VarDC = Var->getDeclContext();
14944   if (Var->isInitCapture())
14945     VarDC = VarDC->getParent();
14946 
14947   DeclContext *DC = CurContext;
14948   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14949       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14950   // We need to sync up the Declaration Context with the
14951   // FunctionScopeIndexToStopAt
14952   if (FunctionScopeIndexToStopAt) {
14953     unsigned FSIndex = FunctionScopes.size() - 1;
14954     while (FSIndex != MaxFunctionScopesIndex) {
14955       DC = getLambdaAwareParentOfDeclContext(DC);
14956       --FSIndex;
14957     }
14958   }
14959 
14960 
14961   // If the variable is declared in the current context, there is no need to
14962   // capture it.
14963   if (VarDC == DC) return true;
14964 
14965   // Capture global variables if it is required to use private copy of this
14966   // variable.
14967   bool IsGlobal = !Var->hasLocalStorage();
14968   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14969     return true;
14970   Var = Var->getCanonicalDecl();
14971 
14972   // Walk up the stack to determine whether we can capture the variable,
14973   // performing the "simple" checks that don't depend on type. We stop when
14974   // we've either hit the declared scope of the variable or find an existing
14975   // capture of that variable.  We start from the innermost capturing-entity
14976   // (the DC) and ensure that all intervening capturing-entities
14977   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14978   // declcontext can either capture the variable or have already captured
14979   // the variable.
14980   CaptureType = Var->getType();
14981   DeclRefType = CaptureType.getNonReferenceType();
14982   bool Nested = false;
14983   bool Explicit = (Kind != TryCapture_Implicit);
14984   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14985   do {
14986     // Only block literals, captured statements, and lambda expressions can
14987     // capture; other scopes don't work.
14988     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14989                                                               ExprLoc,
14990                                                               BuildAndDiagnose,
14991                                                               *this);
14992     // We need to check for the parent *first* because, if we *have*
14993     // private-captured a global variable, we need to recursively capture it in
14994     // intermediate blocks, lambdas, etc.
14995     if (!ParentDC) {
14996       if (IsGlobal) {
14997         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14998         break;
14999       }
15000       return true;
15001     }
15002 
15003     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15004     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15005 
15006 
15007     // Check whether we've already captured it.
15008     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15009                                              DeclRefType)) {
15010       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15011       break;
15012     }
15013     // If we are instantiating a generic lambda call operator body,
15014     // we do not want to capture new variables.  What was captured
15015     // during either a lambdas transformation or initial parsing
15016     // should be used.
15017     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15018       if (BuildAndDiagnose) {
15019         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15020         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15021           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15022           Diag(Var->getLocation(), diag::note_previous_decl)
15023              << Var->getDeclName();
15024           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
15025         } else
15026           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15027       }
15028       return true;
15029     }
15030     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15031     // certain types of variables (unnamed, variably modified types etc.)
15032     // so check for eligibility.
15033     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15034        return true;
15035 
15036     // Try to capture variable-length arrays types.
15037     if (Var->getType()->isVariablyModifiedType()) {
15038       // We're going to walk down into the type and look for VLA
15039       // expressions.
15040       QualType QTy = Var->getType();
15041       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15042         QTy = PVD->getOriginalType();
15043       captureVariablyModifiedType(Context, QTy, CSI);
15044     }
15045 
15046     if (getLangOpts().OpenMP) {
15047       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15048         // OpenMP private variables should not be captured in outer scope, so
15049         // just break here. Similarly, global variables that are captured in a
15050         // target region should not be captured outside the scope of the region.
15051         if (RSI->CapRegionKind == CR_OpenMP) {
15052           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15053           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15054                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15055           // When we detect target captures we are looking from inside the
15056           // target region, therefore we need to propagate the capture from the
15057           // enclosing region. Therefore, the capture is not initially nested.
15058           if (IsTargetCap)
15059             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15060 
15061           if (IsTargetCap || IsOpenMPPrivateDecl) {
15062             Nested = !IsTargetCap;
15063             DeclRefType = DeclRefType.getUnqualifiedType();
15064             CaptureType = Context.getLValueReferenceType(DeclRefType);
15065             break;
15066           }
15067         }
15068       }
15069     }
15070     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15071       // No capture-default, and this is not an explicit capture
15072       // so cannot capture this variable.
15073       if (BuildAndDiagnose) {
15074         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15075         Diag(Var->getLocation(), diag::note_previous_decl)
15076           << Var->getDeclName();
15077         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15078           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
15079                diag::note_lambda_decl);
15080         // FIXME: If we error out because an outer lambda can not implicitly
15081         // capture a variable that an inner lambda explicitly captures, we
15082         // should have the inner lambda do the explicit capture - because
15083         // it makes for cleaner diagnostics later.  This would purely be done
15084         // so that the diagnostic does not misleadingly claim that a variable
15085         // can not be captured by a lambda implicitly even though it is captured
15086         // explicitly.  Suggestion:
15087         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15088         //    at the function head
15089         //  - cache the StartingDeclContext - this must be a lambda
15090         //  - captureInLambda in the innermost lambda the variable.
15091       }
15092       return true;
15093     }
15094 
15095     FunctionScopesIndex--;
15096     DC = ParentDC;
15097     Explicit = false;
15098   } while (!VarDC->Equals(DC));
15099 
15100   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15101   // computing the type of the capture at each step, checking type-specific
15102   // requirements, and adding captures if requested.
15103   // If the variable had already been captured previously, we start capturing
15104   // at the lambda nested within that one.
15105   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15106        ++I) {
15107     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15108 
15109     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15110       if (!captureInBlock(BSI, Var, ExprLoc,
15111                           BuildAndDiagnose, CaptureType,
15112                           DeclRefType, Nested, *this))
15113         return true;
15114       Nested = true;
15115     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15116       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15117                                    BuildAndDiagnose, CaptureType,
15118                                    DeclRefType, Nested, *this))
15119         return true;
15120       Nested = true;
15121     } else {
15122       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15123       if (!captureInLambda(LSI, Var, ExprLoc,
15124                            BuildAndDiagnose, CaptureType,
15125                            DeclRefType, Nested, Kind, EllipsisLoc,
15126                             /*IsTopScope*/I == N - 1, *this))
15127         return true;
15128       Nested = true;
15129     }
15130   }
15131   return false;
15132 }
15133 
15134 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15135                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15136   QualType CaptureType;
15137   QualType DeclRefType;
15138   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15139                             /*BuildAndDiagnose=*/true, CaptureType,
15140                             DeclRefType, nullptr);
15141 }
15142 
15143 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15144   QualType CaptureType;
15145   QualType DeclRefType;
15146   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15147                              /*BuildAndDiagnose=*/false, CaptureType,
15148                              DeclRefType, nullptr);
15149 }
15150 
15151 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15152   QualType CaptureType;
15153   QualType DeclRefType;
15154 
15155   // Determine whether we can capture this variable.
15156   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15157                          /*BuildAndDiagnose=*/false, CaptureType,
15158                          DeclRefType, nullptr))
15159     return QualType();
15160 
15161   return DeclRefType;
15162 }
15163 
15164 
15165 
15166 // If either the type of the variable or the initializer is dependent,
15167 // return false. Otherwise, determine whether the variable is a constant
15168 // expression. Use this if you need to know if a variable that might or
15169 // might not be dependent is truly a constant expression.
15170 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15171     ASTContext &Context) {
15172 
15173   if (Var->getType()->isDependentType())
15174     return false;
15175   const VarDecl *DefVD = nullptr;
15176   Var->getAnyInitializer(DefVD);
15177   if (!DefVD)
15178     return false;
15179   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15180   Expr *Init = cast<Expr>(Eval->Value);
15181   if (Init->isValueDependent())
15182     return false;
15183   return IsVariableAConstantExpression(Var, Context);
15184 }
15185 
15186 
15187 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15188   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15189   // an object that satisfies the requirements for appearing in a
15190   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15191   // is immediately applied."  This function handles the lvalue-to-rvalue
15192   // conversion part.
15193   MaybeODRUseExprs.erase(E->IgnoreParens());
15194 
15195   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15196   // to a variable that is a constant expression, and if so, identify it as
15197   // a reference to a variable that does not involve an odr-use of that
15198   // variable.
15199   if (LambdaScopeInfo *LSI = getCurLambda()) {
15200     Expr *SansParensExpr = E->IgnoreParens();
15201     VarDecl *Var = nullptr;
15202     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15203       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15204     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15205       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15206 
15207     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15208       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15209   }
15210 }
15211 
15212 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15213   Res = CorrectDelayedTyposInExpr(Res);
15214 
15215   if (!Res.isUsable())
15216     return Res;
15217 
15218   // If a constant-expression is a reference to a variable where we delay
15219   // deciding whether it is an odr-use, just assume we will apply the
15220   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15221   // (a non-type template argument), we have special handling anyway.
15222   UpdateMarkingForLValueToRValue(Res.get());
15223   return Res;
15224 }
15225 
15226 void Sema::CleanupVarDeclMarking() {
15227   for (Expr *E : MaybeODRUseExprs) {
15228     VarDecl *Var;
15229     SourceLocation Loc;
15230     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15231       Var = cast<VarDecl>(DRE->getDecl());
15232       Loc = DRE->getLocation();
15233     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15234       Var = cast<VarDecl>(ME->getMemberDecl());
15235       Loc = ME->getMemberLoc();
15236     } else {
15237       llvm_unreachable("Unexpected expression");
15238     }
15239 
15240     MarkVarDeclODRUsed(Var, Loc, *this,
15241                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15242   }
15243 
15244   MaybeODRUseExprs.clear();
15245 }
15246 
15247 
15248 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15249                                     VarDecl *Var, Expr *E) {
15250   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15251          "Invalid Expr argument to DoMarkVarDeclReferenced");
15252   Var->setReferenced();
15253 
15254   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15255 
15256   bool OdrUseContext = isOdrUseContext(SemaRef);
15257   bool UsableInConstantExpr =
15258       Var->isUsableInConstantExpressions(SemaRef.Context);
15259   bool NeedDefinition =
15260       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15261 
15262   VarTemplateSpecializationDecl *VarSpec =
15263       dyn_cast<VarTemplateSpecializationDecl>(Var);
15264   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15265          "Can't instantiate a partial template specialization.");
15266 
15267   // If this might be a member specialization of a static data member, check
15268   // the specialization is visible. We already did the checks for variable
15269   // template specializations when we created them.
15270   if (NeedDefinition && TSK != TSK_Undeclared &&
15271       !isa<VarTemplateSpecializationDecl>(Var))
15272     SemaRef.checkSpecializationVisibility(Loc, Var);
15273 
15274   // Perform implicit instantiation of static data members, static data member
15275   // templates of class templates, and variable template specializations. Delay
15276   // instantiations of variable templates, except for those that could be used
15277   // in a constant expression.
15278   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15279     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15280     // instantiation declaration if a variable is usable in a constant
15281     // expression (among other cases).
15282     bool TryInstantiating =
15283         TSK == TSK_ImplicitInstantiation ||
15284         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15285 
15286     if (TryInstantiating) {
15287       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15288       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15289       if (FirstInstantiation) {
15290         PointOfInstantiation = Loc;
15291         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15292       }
15293 
15294       bool InstantiationDependent = false;
15295       bool IsNonDependent =
15296           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15297                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15298                   : true;
15299 
15300       // Do not instantiate specializations that are still type-dependent.
15301       if (IsNonDependent) {
15302         if (UsableInConstantExpr) {
15303           // Do not defer instantiations of variables that could be used in a
15304           // constant expression.
15305           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15306         } else if (FirstInstantiation ||
15307                    isa<VarTemplateSpecializationDecl>(Var)) {
15308           // FIXME: For a specialization of a variable template, we don't
15309           // distinguish between "declaration and type implicitly instantiated"
15310           // and "implicit instantiation of definition requested", so we have
15311           // no direct way to avoid enqueueing the pending instantiation
15312           // multiple times.
15313           SemaRef.PendingInstantiations
15314               .push_back(std::make_pair(Var, PointOfInstantiation));
15315         }
15316       }
15317     }
15318   }
15319 
15320   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15321   // the requirements for appearing in a constant expression (5.19) and, if
15322   // it is an object, the lvalue-to-rvalue conversion (4.1)
15323   // is immediately applied."  We check the first part here, and
15324   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15325   // Note that we use the C++11 definition everywhere because nothing in
15326   // C++03 depends on whether we get the C++03 version correct. The second
15327   // part does not apply to references, since they are not objects.
15328   if (OdrUseContext && E &&
15329       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15330     // A reference initialized by a constant expression can never be
15331     // odr-used, so simply ignore it.
15332     if (!Var->getType()->isReferenceType() ||
15333         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15334       SemaRef.MaybeODRUseExprs.insert(E);
15335   } else if (OdrUseContext) {
15336     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15337                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15338   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15339     // If this is a dependent context, we don't need to mark variables as
15340     // odr-used, but we may still need to track them for lambda capture.
15341     // FIXME: Do we also need to do this inside dependent typeid expressions
15342     // (which are modeled as unevaluated at this point)?
15343     const bool RefersToEnclosingScope =
15344         (SemaRef.CurContext != Var->getDeclContext() &&
15345          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15346     if (RefersToEnclosingScope) {
15347       LambdaScopeInfo *const LSI =
15348           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15349       if (LSI && (!LSI->CallOperator ||
15350                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15351         // If a variable could potentially be odr-used, defer marking it so
15352         // until we finish analyzing the full expression for any
15353         // lvalue-to-rvalue
15354         // or discarded value conversions that would obviate odr-use.
15355         // Add it to the list of potential captures that will be analyzed
15356         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15357         // unless the variable is a reference that was initialized by a constant
15358         // expression (this will never need to be captured or odr-used).
15359         assert(E && "Capture variable should be used in an expression.");
15360         if (!Var->getType()->isReferenceType() ||
15361             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15362           LSI->addPotentialCapture(E->IgnoreParens());
15363       }
15364     }
15365   }
15366 }
15367 
15368 /// Mark a variable referenced, and check whether it is odr-used
15369 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15370 /// used directly for normal expressions referring to VarDecl.
15371 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15372   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15373 }
15374 
15375 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15376                                Decl *D, Expr *E, bool MightBeOdrUse) {
15377   if (SemaRef.isInOpenMPDeclareTargetContext())
15378     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15379 
15380   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15381     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15382     return;
15383   }
15384 
15385   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15386 
15387   // If this is a call to a method via a cast, also mark the method in the
15388   // derived class used in case codegen can devirtualize the call.
15389   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15390   if (!ME)
15391     return;
15392   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15393   if (!MD)
15394     return;
15395   // Only attempt to devirtualize if this is truly a virtual call.
15396   bool IsVirtualCall = MD->isVirtual() &&
15397                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15398   if (!IsVirtualCall)
15399     return;
15400 
15401   // If it's possible to devirtualize the call, mark the called function
15402   // referenced.
15403   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15404       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15405   if (DM)
15406     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15407 }
15408 
15409 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15410 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15411   // TODO: update this with DR# once a defect report is filed.
15412   // C++11 defect. The address of a pure member should not be an ODR use, even
15413   // if it's a qualified reference.
15414   bool OdrUse = true;
15415   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15416     if (Method->isVirtual() &&
15417         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15418       OdrUse = false;
15419   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15420 }
15421 
15422 /// Perform reference-marking and odr-use handling for a MemberExpr.
15423 void Sema::MarkMemberReferenced(MemberExpr *E) {
15424   // C++11 [basic.def.odr]p2:
15425   //   A non-overloaded function whose name appears as a potentially-evaluated
15426   //   expression or a member of a set of candidate functions, if selected by
15427   //   overload resolution when referred to from a potentially-evaluated
15428   //   expression, is odr-used, unless it is a pure virtual function and its
15429   //   name is not explicitly qualified.
15430   bool MightBeOdrUse = true;
15431   if (E->performsVirtualDispatch(getLangOpts())) {
15432     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15433       if (Method->isPure())
15434         MightBeOdrUse = false;
15435   }
15436   SourceLocation Loc = E->getMemberLoc().isValid() ?
15437                             E->getMemberLoc() : E->getLocStart();
15438   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15439 }
15440 
15441 /// Perform marking for a reference to an arbitrary declaration.  It
15442 /// marks the declaration referenced, and performs odr-use checking for
15443 /// functions and variables. This method should not be used when building a
15444 /// normal expression which refers to a variable.
15445 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15446                                  bool MightBeOdrUse) {
15447   if (MightBeOdrUse) {
15448     if (auto *VD = dyn_cast<VarDecl>(D)) {
15449       MarkVariableReferenced(Loc, VD);
15450       return;
15451     }
15452   }
15453   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15454     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15455     return;
15456   }
15457   D->setReferenced();
15458 }
15459 
15460 namespace {
15461   // Mark all of the declarations used by a type as referenced.
15462   // FIXME: Not fully implemented yet! We need to have a better understanding
15463   // of when we're entering a context we should not recurse into.
15464   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15465   // TreeTransforms rebuilding the type in a new context. Rather than
15466   // duplicating the TreeTransform logic, we should consider reusing it here.
15467   // Currently that causes problems when rebuilding LambdaExprs.
15468   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15469     Sema &S;
15470     SourceLocation Loc;
15471 
15472   public:
15473     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15474 
15475     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15476 
15477     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15478   };
15479 }
15480 
15481 bool MarkReferencedDecls::TraverseTemplateArgument(
15482     const TemplateArgument &Arg) {
15483   {
15484     // A non-type template argument is a constant-evaluated context.
15485     EnterExpressionEvaluationContext Evaluated(
15486         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15487     if (Arg.getKind() == TemplateArgument::Declaration) {
15488       if (Decl *D = Arg.getAsDecl())
15489         S.MarkAnyDeclReferenced(Loc, D, true);
15490     } else if (Arg.getKind() == TemplateArgument::Expression) {
15491       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15492     }
15493   }
15494 
15495   return Inherited::TraverseTemplateArgument(Arg);
15496 }
15497 
15498 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15499   MarkReferencedDecls Marker(*this, Loc);
15500   Marker.TraverseType(T);
15501 }
15502 
15503 namespace {
15504   /// Helper class that marks all of the declarations referenced by
15505   /// potentially-evaluated subexpressions as "referenced".
15506   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15507     Sema &S;
15508     bool SkipLocalVariables;
15509 
15510   public:
15511     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15512 
15513     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15514       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15515 
15516     void VisitDeclRefExpr(DeclRefExpr *E) {
15517       // If we were asked not to visit local variables, don't.
15518       if (SkipLocalVariables) {
15519         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15520           if (VD->hasLocalStorage())
15521             return;
15522       }
15523 
15524       S.MarkDeclRefReferenced(E);
15525     }
15526 
15527     void VisitMemberExpr(MemberExpr *E) {
15528       S.MarkMemberReferenced(E);
15529       Inherited::VisitMemberExpr(E);
15530     }
15531 
15532     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15533       S.MarkFunctionReferenced(E->getLocStart(),
15534             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15535       Visit(E->getSubExpr());
15536     }
15537 
15538     void VisitCXXNewExpr(CXXNewExpr *E) {
15539       if (E->getOperatorNew())
15540         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15541       if (E->getOperatorDelete())
15542         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15543       Inherited::VisitCXXNewExpr(E);
15544     }
15545 
15546     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15547       if (E->getOperatorDelete())
15548         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15549       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15550       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15551         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15552         S.MarkFunctionReferenced(E->getLocStart(),
15553                                     S.LookupDestructor(Record));
15554       }
15555 
15556       Inherited::VisitCXXDeleteExpr(E);
15557     }
15558 
15559     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15560       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15561       Inherited::VisitCXXConstructExpr(E);
15562     }
15563 
15564     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15565       Visit(E->getExpr());
15566     }
15567 
15568     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15569       Inherited::VisitImplicitCastExpr(E);
15570 
15571       if (E->getCastKind() == CK_LValueToRValue)
15572         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15573     }
15574   };
15575 }
15576 
15577 /// Mark any declarations that appear within this expression or any
15578 /// potentially-evaluated subexpressions as "referenced".
15579 ///
15580 /// \param SkipLocalVariables If true, don't mark local variables as
15581 /// 'referenced'.
15582 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15583                                             bool SkipLocalVariables) {
15584   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15585 }
15586 
15587 /// Emit a diagnostic that describes an effect on the run-time behavior
15588 /// of the program being compiled.
15589 ///
15590 /// This routine emits the given diagnostic when the code currently being
15591 /// type-checked is "potentially evaluated", meaning that there is a
15592 /// possibility that the code will actually be executable. Code in sizeof()
15593 /// expressions, code used only during overload resolution, etc., are not
15594 /// potentially evaluated. This routine will suppress such diagnostics or,
15595 /// in the absolutely nutty case of potentially potentially evaluated
15596 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15597 /// later.
15598 ///
15599 /// This routine should be used for all diagnostics that describe the run-time
15600 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15601 /// Failure to do so will likely result in spurious diagnostics or failures
15602 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15603 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15604                                const PartialDiagnostic &PD) {
15605   switch (ExprEvalContexts.back().Context) {
15606   case ExpressionEvaluationContext::Unevaluated:
15607   case ExpressionEvaluationContext::UnevaluatedList:
15608   case ExpressionEvaluationContext::UnevaluatedAbstract:
15609   case ExpressionEvaluationContext::DiscardedStatement:
15610     // The argument will never be evaluated, so don't complain.
15611     break;
15612 
15613   case ExpressionEvaluationContext::ConstantEvaluated:
15614     // Relevant diagnostics should be produced by constant evaluation.
15615     break;
15616 
15617   case ExpressionEvaluationContext::PotentiallyEvaluated:
15618   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15619     if (Statement && getCurFunctionOrMethodDecl()) {
15620       FunctionScopes.back()->PossiblyUnreachableDiags.
15621         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15622       return true;
15623     }
15624 
15625     // The initializer of a constexpr variable or of the first declaration of a
15626     // static data member is not syntactically a constant evaluated constant,
15627     // but nonetheless is always required to be a constant expression, so we
15628     // can skip diagnosing.
15629     // FIXME: Using the mangling context here is a hack.
15630     if (auto *VD = dyn_cast_or_null<VarDecl>(
15631             ExprEvalContexts.back().ManglingContextDecl)) {
15632       if (VD->isConstexpr() ||
15633           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15634         break;
15635       // FIXME: For any other kind of variable, we should build a CFG for its
15636       // initializer and check whether the context in question is reachable.
15637     }
15638 
15639     Diag(Loc, PD);
15640     return true;
15641   }
15642 
15643   return false;
15644 }
15645 
15646 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15647                                CallExpr *CE, FunctionDecl *FD) {
15648   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15649     return false;
15650 
15651   // If we're inside a decltype's expression, don't check for a valid return
15652   // type or construct temporaries until we know whether this is the last call.
15653   if (ExprEvalContexts.back().ExprContext ==
15654       ExpressionEvaluationContextRecord::EK_Decltype) {
15655     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15656     return false;
15657   }
15658 
15659   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15660     FunctionDecl *FD;
15661     CallExpr *CE;
15662 
15663   public:
15664     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15665       : FD(FD), CE(CE) { }
15666 
15667     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15668       if (!FD) {
15669         S.Diag(Loc, diag::err_call_incomplete_return)
15670           << T << CE->getSourceRange();
15671         return;
15672       }
15673 
15674       S.Diag(Loc, diag::err_call_function_incomplete_return)
15675         << CE->getSourceRange() << FD->getDeclName() << T;
15676       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15677           << FD->getDeclName();
15678     }
15679   } Diagnoser(FD, CE);
15680 
15681   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15682     return true;
15683 
15684   return false;
15685 }
15686 
15687 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15688 // will prevent this condition from triggering, which is what we want.
15689 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15690   SourceLocation Loc;
15691 
15692   unsigned diagnostic = diag::warn_condition_is_assignment;
15693   bool IsOrAssign = false;
15694 
15695   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15696     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15697       return;
15698 
15699     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15700 
15701     // Greylist some idioms by putting them into a warning subcategory.
15702     if (ObjCMessageExpr *ME
15703           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15704       Selector Sel = ME->getSelector();
15705 
15706       // self = [<foo> init...]
15707       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15708         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15709 
15710       // <foo> = [<bar> nextObject]
15711       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15712         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15713     }
15714 
15715     Loc = Op->getOperatorLoc();
15716   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15717     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15718       return;
15719 
15720     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15721     Loc = Op->getOperatorLoc();
15722   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15723     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15724   else {
15725     // Not an assignment.
15726     return;
15727   }
15728 
15729   Diag(Loc, diagnostic) << E->getSourceRange();
15730 
15731   SourceLocation Open = E->getLocStart();
15732   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15733   Diag(Loc, diag::note_condition_assign_silence)
15734         << FixItHint::CreateInsertion(Open, "(")
15735         << FixItHint::CreateInsertion(Close, ")");
15736 
15737   if (IsOrAssign)
15738     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15739       << FixItHint::CreateReplacement(Loc, "!=");
15740   else
15741     Diag(Loc, diag::note_condition_assign_to_comparison)
15742       << FixItHint::CreateReplacement(Loc, "==");
15743 }
15744 
15745 /// Redundant parentheses over an equality comparison can indicate
15746 /// that the user intended an assignment used as condition.
15747 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15748   // Don't warn if the parens came from a macro.
15749   SourceLocation parenLoc = ParenE->getLocStart();
15750   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15751     return;
15752   // Don't warn for dependent expressions.
15753   if (ParenE->isTypeDependent())
15754     return;
15755 
15756   Expr *E = ParenE->IgnoreParens();
15757 
15758   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15759     if (opE->getOpcode() == BO_EQ &&
15760         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15761                                                            == Expr::MLV_Valid) {
15762       SourceLocation Loc = opE->getOperatorLoc();
15763 
15764       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15765       SourceRange ParenERange = ParenE->getSourceRange();
15766       Diag(Loc, diag::note_equality_comparison_silence)
15767         << FixItHint::CreateRemoval(ParenERange.getBegin())
15768         << FixItHint::CreateRemoval(ParenERange.getEnd());
15769       Diag(Loc, diag::note_equality_comparison_to_assign)
15770         << FixItHint::CreateReplacement(Loc, "=");
15771     }
15772 }
15773 
15774 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15775                                        bool IsConstexpr) {
15776   DiagnoseAssignmentAsCondition(E);
15777   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15778     DiagnoseEqualityWithExtraParens(parenE);
15779 
15780   ExprResult result = CheckPlaceholderExpr(E);
15781   if (result.isInvalid()) return ExprError();
15782   E = result.get();
15783 
15784   if (!E->isTypeDependent()) {
15785     if (getLangOpts().CPlusPlus)
15786       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15787 
15788     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15789     if (ERes.isInvalid())
15790       return ExprError();
15791     E = ERes.get();
15792 
15793     QualType T = E->getType();
15794     if (!T->isScalarType()) { // C99 6.8.4.1p1
15795       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15796         << T << E->getSourceRange();
15797       return ExprError();
15798     }
15799     CheckBoolLikeConversion(E, Loc);
15800   }
15801 
15802   return E;
15803 }
15804 
15805 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15806                                            Expr *SubExpr, ConditionKind CK) {
15807   // Empty conditions are valid in for-statements.
15808   if (!SubExpr)
15809     return ConditionResult();
15810 
15811   ExprResult Cond;
15812   switch (CK) {
15813   case ConditionKind::Boolean:
15814     Cond = CheckBooleanCondition(Loc, SubExpr);
15815     break;
15816 
15817   case ConditionKind::ConstexprIf:
15818     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15819     break;
15820 
15821   case ConditionKind::Switch:
15822     Cond = CheckSwitchCondition(Loc, SubExpr);
15823     break;
15824   }
15825   if (Cond.isInvalid())
15826     return ConditionError();
15827 
15828   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15829   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15830   if (!FullExpr.get())
15831     return ConditionError();
15832 
15833   return ConditionResult(*this, nullptr, FullExpr,
15834                          CK == ConditionKind::ConstexprIf);
15835 }
15836 
15837 namespace {
15838   /// A visitor for rebuilding a call to an __unknown_any expression
15839   /// to have an appropriate type.
15840   struct RebuildUnknownAnyFunction
15841     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15842 
15843     Sema &S;
15844 
15845     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15846 
15847     ExprResult VisitStmt(Stmt *S) {
15848       llvm_unreachable("unexpected statement!");
15849     }
15850 
15851     ExprResult VisitExpr(Expr *E) {
15852       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15853         << E->getSourceRange();
15854       return ExprError();
15855     }
15856 
15857     /// Rebuild an expression which simply semantically wraps another
15858     /// expression which it shares the type and value kind of.
15859     template <class T> ExprResult rebuildSugarExpr(T *E) {
15860       ExprResult SubResult = Visit(E->getSubExpr());
15861       if (SubResult.isInvalid()) return ExprError();
15862 
15863       Expr *SubExpr = SubResult.get();
15864       E->setSubExpr(SubExpr);
15865       E->setType(SubExpr->getType());
15866       E->setValueKind(SubExpr->getValueKind());
15867       assert(E->getObjectKind() == OK_Ordinary);
15868       return E;
15869     }
15870 
15871     ExprResult VisitParenExpr(ParenExpr *E) {
15872       return rebuildSugarExpr(E);
15873     }
15874 
15875     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15876       return rebuildSugarExpr(E);
15877     }
15878 
15879     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15880       ExprResult SubResult = Visit(E->getSubExpr());
15881       if (SubResult.isInvalid()) return ExprError();
15882 
15883       Expr *SubExpr = SubResult.get();
15884       E->setSubExpr(SubExpr);
15885       E->setType(S.Context.getPointerType(SubExpr->getType()));
15886       assert(E->getValueKind() == VK_RValue);
15887       assert(E->getObjectKind() == OK_Ordinary);
15888       return E;
15889     }
15890 
15891     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15892       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15893 
15894       E->setType(VD->getType());
15895 
15896       assert(E->getValueKind() == VK_RValue);
15897       if (S.getLangOpts().CPlusPlus &&
15898           !(isa<CXXMethodDecl>(VD) &&
15899             cast<CXXMethodDecl>(VD)->isInstance()))
15900         E->setValueKind(VK_LValue);
15901 
15902       return E;
15903     }
15904 
15905     ExprResult VisitMemberExpr(MemberExpr *E) {
15906       return resolveDecl(E, E->getMemberDecl());
15907     }
15908 
15909     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15910       return resolveDecl(E, E->getDecl());
15911     }
15912   };
15913 }
15914 
15915 /// Given a function expression of unknown-any type, try to rebuild it
15916 /// to have a function type.
15917 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15918   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15919   if (Result.isInvalid()) return ExprError();
15920   return S.DefaultFunctionArrayConversion(Result.get());
15921 }
15922 
15923 namespace {
15924   /// A visitor for rebuilding an expression of type __unknown_anytype
15925   /// into one which resolves the type directly on the referring
15926   /// expression.  Strict preservation of the original source
15927   /// structure is not a goal.
15928   struct RebuildUnknownAnyExpr
15929     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15930 
15931     Sema &S;
15932 
15933     /// The current destination type.
15934     QualType DestType;
15935 
15936     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15937       : S(S), DestType(CastType) {}
15938 
15939     ExprResult VisitStmt(Stmt *S) {
15940       llvm_unreachable("unexpected statement!");
15941     }
15942 
15943     ExprResult VisitExpr(Expr *E) {
15944       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15945         << E->getSourceRange();
15946       return ExprError();
15947     }
15948 
15949     ExprResult VisitCallExpr(CallExpr *E);
15950     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15951 
15952     /// Rebuild an expression which simply semantically wraps another
15953     /// expression which it shares the type and value kind of.
15954     template <class T> ExprResult rebuildSugarExpr(T *E) {
15955       ExprResult SubResult = Visit(E->getSubExpr());
15956       if (SubResult.isInvalid()) return ExprError();
15957       Expr *SubExpr = SubResult.get();
15958       E->setSubExpr(SubExpr);
15959       E->setType(SubExpr->getType());
15960       E->setValueKind(SubExpr->getValueKind());
15961       assert(E->getObjectKind() == OK_Ordinary);
15962       return E;
15963     }
15964 
15965     ExprResult VisitParenExpr(ParenExpr *E) {
15966       return rebuildSugarExpr(E);
15967     }
15968 
15969     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15970       return rebuildSugarExpr(E);
15971     }
15972 
15973     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15974       const PointerType *Ptr = DestType->getAs<PointerType>();
15975       if (!Ptr) {
15976         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15977           << E->getSourceRange();
15978         return ExprError();
15979       }
15980 
15981       if (isa<CallExpr>(E->getSubExpr())) {
15982         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15983           << E->getSourceRange();
15984         return ExprError();
15985       }
15986 
15987       assert(E->getValueKind() == VK_RValue);
15988       assert(E->getObjectKind() == OK_Ordinary);
15989       E->setType(DestType);
15990 
15991       // Build the sub-expression as if it were an object of the pointee type.
15992       DestType = Ptr->getPointeeType();
15993       ExprResult SubResult = Visit(E->getSubExpr());
15994       if (SubResult.isInvalid()) return ExprError();
15995       E->setSubExpr(SubResult.get());
15996       return E;
15997     }
15998 
15999     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16000 
16001     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16002 
16003     ExprResult VisitMemberExpr(MemberExpr *E) {
16004       return resolveDecl(E, E->getMemberDecl());
16005     }
16006 
16007     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16008       return resolveDecl(E, E->getDecl());
16009     }
16010   };
16011 }
16012 
16013 /// Rebuilds a call expression which yielded __unknown_anytype.
16014 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16015   Expr *CalleeExpr = E->getCallee();
16016 
16017   enum FnKind {
16018     FK_MemberFunction,
16019     FK_FunctionPointer,
16020     FK_BlockPointer
16021   };
16022 
16023   FnKind Kind;
16024   QualType CalleeType = CalleeExpr->getType();
16025   if (CalleeType == S.Context.BoundMemberTy) {
16026     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16027     Kind = FK_MemberFunction;
16028     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16029   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16030     CalleeType = Ptr->getPointeeType();
16031     Kind = FK_FunctionPointer;
16032   } else {
16033     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16034     Kind = FK_BlockPointer;
16035   }
16036   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16037 
16038   // Verify that this is a legal result type of a function.
16039   if (DestType->isArrayType() || DestType->isFunctionType()) {
16040     unsigned diagID = diag::err_func_returning_array_function;
16041     if (Kind == FK_BlockPointer)
16042       diagID = diag::err_block_returning_array_function;
16043 
16044     S.Diag(E->getExprLoc(), diagID)
16045       << DestType->isFunctionType() << DestType;
16046     return ExprError();
16047   }
16048 
16049   // Otherwise, go ahead and set DestType as the call's result.
16050   E->setType(DestType.getNonLValueExprType(S.Context));
16051   E->setValueKind(Expr::getValueKindForType(DestType));
16052   assert(E->getObjectKind() == OK_Ordinary);
16053 
16054   // Rebuild the function type, replacing the result type with DestType.
16055   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16056   if (Proto) {
16057     // __unknown_anytype(...) is a special case used by the debugger when
16058     // it has no idea what a function's signature is.
16059     //
16060     // We want to build this call essentially under the K&R
16061     // unprototyped rules, but making a FunctionNoProtoType in C++
16062     // would foul up all sorts of assumptions.  However, we cannot
16063     // simply pass all arguments as variadic arguments, nor can we
16064     // portably just call the function under a non-variadic type; see
16065     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16066     // However, it turns out that in practice it is generally safe to
16067     // call a function declared as "A foo(B,C,D);" under the prototype
16068     // "A foo(B,C,D,...);".  The only known exception is with the
16069     // Windows ABI, where any variadic function is implicitly cdecl
16070     // regardless of its normal CC.  Therefore we change the parameter
16071     // types to match the types of the arguments.
16072     //
16073     // This is a hack, but it is far superior to moving the
16074     // corresponding target-specific code from IR-gen to Sema/AST.
16075 
16076     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16077     SmallVector<QualType, 8> ArgTypes;
16078     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16079       ArgTypes.reserve(E->getNumArgs());
16080       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16081         Expr *Arg = E->getArg(i);
16082         QualType ArgType = Arg->getType();
16083         if (E->isLValue()) {
16084           ArgType = S.Context.getLValueReferenceType(ArgType);
16085         } else if (E->isXValue()) {
16086           ArgType = S.Context.getRValueReferenceType(ArgType);
16087         }
16088         ArgTypes.push_back(ArgType);
16089       }
16090       ParamTypes = ArgTypes;
16091     }
16092     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16093                                          Proto->getExtProtoInfo());
16094   } else {
16095     DestType = S.Context.getFunctionNoProtoType(DestType,
16096                                                 FnType->getExtInfo());
16097   }
16098 
16099   // Rebuild the appropriate pointer-to-function type.
16100   switch (Kind) {
16101   case FK_MemberFunction:
16102     // Nothing to do.
16103     break;
16104 
16105   case FK_FunctionPointer:
16106     DestType = S.Context.getPointerType(DestType);
16107     break;
16108 
16109   case FK_BlockPointer:
16110     DestType = S.Context.getBlockPointerType(DestType);
16111     break;
16112   }
16113 
16114   // Finally, we can recurse.
16115   ExprResult CalleeResult = Visit(CalleeExpr);
16116   if (!CalleeResult.isUsable()) return ExprError();
16117   E->setCallee(CalleeResult.get());
16118 
16119   // Bind a temporary if necessary.
16120   return S.MaybeBindToTemporary(E);
16121 }
16122 
16123 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16124   // Verify that this is a legal result type of a call.
16125   if (DestType->isArrayType() || DestType->isFunctionType()) {
16126     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16127       << DestType->isFunctionType() << DestType;
16128     return ExprError();
16129   }
16130 
16131   // Rewrite the method result type if available.
16132   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16133     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16134     Method->setReturnType(DestType);
16135   }
16136 
16137   // Change the type of the message.
16138   E->setType(DestType.getNonReferenceType());
16139   E->setValueKind(Expr::getValueKindForType(DestType));
16140 
16141   return S.MaybeBindToTemporary(E);
16142 }
16143 
16144 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16145   // The only case we should ever see here is a function-to-pointer decay.
16146   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16147     assert(E->getValueKind() == VK_RValue);
16148     assert(E->getObjectKind() == OK_Ordinary);
16149 
16150     E->setType(DestType);
16151 
16152     // Rebuild the sub-expression as the pointee (function) type.
16153     DestType = DestType->castAs<PointerType>()->getPointeeType();
16154 
16155     ExprResult Result = Visit(E->getSubExpr());
16156     if (!Result.isUsable()) return ExprError();
16157 
16158     E->setSubExpr(Result.get());
16159     return E;
16160   } else if (E->getCastKind() == CK_LValueToRValue) {
16161     assert(E->getValueKind() == VK_RValue);
16162     assert(E->getObjectKind() == OK_Ordinary);
16163 
16164     assert(isa<BlockPointerType>(E->getType()));
16165 
16166     E->setType(DestType);
16167 
16168     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16169     DestType = S.Context.getLValueReferenceType(DestType);
16170 
16171     ExprResult Result = Visit(E->getSubExpr());
16172     if (!Result.isUsable()) return ExprError();
16173 
16174     E->setSubExpr(Result.get());
16175     return E;
16176   } else {
16177     llvm_unreachable("Unhandled cast type!");
16178   }
16179 }
16180 
16181 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16182   ExprValueKind ValueKind = VK_LValue;
16183   QualType Type = DestType;
16184 
16185   // We know how to make this work for certain kinds of decls:
16186 
16187   //  - functions
16188   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16189     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16190       DestType = Ptr->getPointeeType();
16191       ExprResult Result = resolveDecl(E, VD);
16192       if (Result.isInvalid()) return ExprError();
16193       return S.ImpCastExprToType(Result.get(), Type,
16194                                  CK_FunctionToPointerDecay, VK_RValue);
16195     }
16196 
16197     if (!Type->isFunctionType()) {
16198       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16199         << VD << E->getSourceRange();
16200       return ExprError();
16201     }
16202     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16203       // We must match the FunctionDecl's type to the hack introduced in
16204       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16205       // type. See the lengthy commentary in that routine.
16206       QualType FDT = FD->getType();
16207       const FunctionType *FnType = FDT->castAs<FunctionType>();
16208       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16209       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16210       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16211         SourceLocation Loc = FD->getLocation();
16212         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16213                                       FD->getDeclContext(),
16214                                       Loc, Loc, FD->getNameInfo().getName(),
16215                                       DestType, FD->getTypeSourceInfo(),
16216                                       SC_None, false/*isInlineSpecified*/,
16217                                       FD->hasPrototype(),
16218                                       false/*isConstexprSpecified*/);
16219 
16220         if (FD->getQualifier())
16221           NewFD->setQualifierInfo(FD->getQualifierLoc());
16222 
16223         SmallVector<ParmVarDecl*, 16> Params;
16224         for (const auto &AI : FT->param_types()) {
16225           ParmVarDecl *Param =
16226             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16227           Param->setScopeInfo(0, Params.size());
16228           Params.push_back(Param);
16229         }
16230         NewFD->setParams(Params);
16231         DRE->setDecl(NewFD);
16232         VD = DRE->getDecl();
16233       }
16234     }
16235 
16236     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16237       if (MD->isInstance()) {
16238         ValueKind = VK_RValue;
16239         Type = S.Context.BoundMemberTy;
16240       }
16241 
16242     // Function references aren't l-values in C.
16243     if (!S.getLangOpts().CPlusPlus)
16244       ValueKind = VK_RValue;
16245 
16246   //  - variables
16247   } else if (isa<VarDecl>(VD)) {
16248     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16249       Type = RefTy->getPointeeType();
16250     } else if (Type->isFunctionType()) {
16251       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16252         << VD << E->getSourceRange();
16253       return ExprError();
16254     }
16255 
16256   //  - nothing else
16257   } else {
16258     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16259       << VD << E->getSourceRange();
16260     return ExprError();
16261   }
16262 
16263   // Modifying the declaration like this is friendly to IR-gen but
16264   // also really dangerous.
16265   VD->setType(DestType);
16266   E->setType(Type);
16267   E->setValueKind(ValueKind);
16268   return E;
16269 }
16270 
16271 /// Check a cast of an unknown-any type.  We intentionally only
16272 /// trigger this for C-style casts.
16273 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16274                                      Expr *CastExpr, CastKind &CastKind,
16275                                      ExprValueKind &VK, CXXCastPath &Path) {
16276   // The type we're casting to must be either void or complete.
16277   if (!CastType->isVoidType() &&
16278       RequireCompleteType(TypeRange.getBegin(), CastType,
16279                           diag::err_typecheck_cast_to_incomplete))
16280     return ExprError();
16281 
16282   // Rewrite the casted expression from scratch.
16283   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16284   if (!result.isUsable()) return ExprError();
16285 
16286   CastExpr = result.get();
16287   VK = CastExpr->getValueKind();
16288   CastKind = CK_NoOp;
16289 
16290   return CastExpr;
16291 }
16292 
16293 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16294   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16295 }
16296 
16297 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16298                                     Expr *arg, QualType &paramType) {
16299   // If the syntactic form of the argument is not an explicit cast of
16300   // any sort, just do default argument promotion.
16301   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16302   if (!castArg) {
16303     ExprResult result = DefaultArgumentPromotion(arg);
16304     if (result.isInvalid()) return ExprError();
16305     paramType = result.get()->getType();
16306     return result;
16307   }
16308 
16309   // Otherwise, use the type that was written in the explicit cast.
16310   assert(!arg->hasPlaceholderType());
16311   paramType = castArg->getTypeAsWritten();
16312 
16313   // Copy-initialize a parameter of that type.
16314   InitializedEntity entity =
16315     InitializedEntity::InitializeParameter(Context, paramType,
16316                                            /*consumed*/ false);
16317   return PerformCopyInitialization(entity, callLoc, arg);
16318 }
16319 
16320 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16321   Expr *orig = E;
16322   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16323   while (true) {
16324     E = E->IgnoreParenImpCasts();
16325     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16326       E = call->getCallee();
16327       diagID = diag::err_uncasted_call_of_unknown_any;
16328     } else {
16329       break;
16330     }
16331   }
16332 
16333   SourceLocation loc;
16334   NamedDecl *d;
16335   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16336     loc = ref->getLocation();
16337     d = ref->getDecl();
16338   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16339     loc = mem->getMemberLoc();
16340     d = mem->getMemberDecl();
16341   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16342     diagID = diag::err_uncasted_call_of_unknown_any;
16343     loc = msg->getSelectorStartLoc();
16344     d = msg->getMethodDecl();
16345     if (!d) {
16346       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16347         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16348         << orig->getSourceRange();
16349       return ExprError();
16350     }
16351   } else {
16352     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16353       << E->getSourceRange();
16354     return ExprError();
16355   }
16356 
16357   S.Diag(loc, diagID) << d << orig->getSourceRange();
16358 
16359   // Never recoverable.
16360   return ExprError();
16361 }
16362 
16363 /// Check for operands with placeholder types and complain if found.
16364 /// Returns ExprError() if there was an error and no recovery was possible.
16365 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16366   if (!getLangOpts().CPlusPlus) {
16367     // C cannot handle TypoExpr nodes on either side of a binop because it
16368     // doesn't handle dependent types properly, so make sure any TypoExprs have
16369     // been dealt with before checking the operands.
16370     ExprResult Result = CorrectDelayedTyposInExpr(E);
16371     if (!Result.isUsable()) return ExprError();
16372     E = Result.get();
16373   }
16374 
16375   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16376   if (!placeholderType) return E;
16377 
16378   switch (placeholderType->getKind()) {
16379 
16380   // Overloaded expressions.
16381   case BuiltinType::Overload: {
16382     // Try to resolve a single function template specialization.
16383     // This is obligatory.
16384     ExprResult Result = E;
16385     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16386       return Result;
16387 
16388     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16389     // leaves Result unchanged on failure.
16390     Result = E;
16391     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16392       return Result;
16393 
16394     // If that failed, try to recover with a call.
16395     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16396                          /*complain*/ true);
16397     return Result;
16398   }
16399 
16400   // Bound member functions.
16401   case BuiltinType::BoundMember: {
16402     ExprResult result = E;
16403     const Expr *BME = E->IgnoreParens();
16404     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16405     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16406     if (isa<CXXPseudoDestructorExpr>(BME)) {
16407       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16408     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16409       if (ME->getMemberNameInfo().getName().getNameKind() ==
16410           DeclarationName::CXXDestructorName)
16411         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16412     }
16413     tryToRecoverWithCall(result, PD,
16414                          /*complain*/ true);
16415     return result;
16416   }
16417 
16418   // ARC unbridged casts.
16419   case BuiltinType::ARCUnbridgedCast: {
16420     Expr *realCast = stripARCUnbridgedCast(E);
16421     diagnoseARCUnbridgedCast(realCast);
16422     return realCast;
16423   }
16424 
16425   // Expressions of unknown type.
16426   case BuiltinType::UnknownAny:
16427     return diagnoseUnknownAnyExpr(*this, E);
16428 
16429   // Pseudo-objects.
16430   case BuiltinType::PseudoObject:
16431     return checkPseudoObjectRValue(E);
16432 
16433   case BuiltinType::BuiltinFn: {
16434     // Accept __noop without parens by implicitly converting it to a call expr.
16435     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16436     if (DRE) {
16437       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16438       if (FD->getBuiltinID() == Builtin::BI__noop) {
16439         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16440                               CK_BuiltinFnToFnPtr).get();
16441         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16442                                       VK_RValue, SourceLocation());
16443       }
16444     }
16445 
16446     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16447     return ExprError();
16448   }
16449 
16450   // Expressions of unknown type.
16451   case BuiltinType::OMPArraySection:
16452     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16453     return ExprError();
16454 
16455   // Everything else should be impossible.
16456 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16457   case BuiltinType::Id:
16458 #include "clang/Basic/OpenCLImageTypes.def"
16459 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16460 #define PLACEHOLDER_TYPE(Id, SingletonId)
16461 #include "clang/AST/BuiltinTypes.def"
16462     break;
16463   }
16464 
16465   llvm_unreachable("invalid placeholder type!");
16466 }
16467 
16468 bool Sema::CheckCaseExpression(Expr *E) {
16469   if (E->isTypeDependent())
16470     return true;
16471   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16472     return E->getType()->isIntegralOrEnumerationType();
16473   return false;
16474 }
16475 
16476 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16477 ExprResult
16478 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16479   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16480          "Unknown Objective-C Boolean value!");
16481   QualType BoolT = Context.ObjCBuiltinBoolTy;
16482   if (!Context.getBOOLDecl()) {
16483     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16484                         Sema::LookupOrdinaryName);
16485     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16486       NamedDecl *ND = Result.getFoundDecl();
16487       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16488         Context.setBOOLDecl(TD);
16489     }
16490   }
16491   if (Context.getBOOLDecl())
16492     BoolT = Context.getBOOLType();
16493   return new (Context)
16494       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16495 }
16496 
16497 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16498     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16499     SourceLocation RParen) {
16500 
16501   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16502 
16503   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16504                            [&](const AvailabilitySpec &Spec) {
16505                              return Spec.getPlatform() == Platform;
16506                            });
16507 
16508   VersionTuple Version;
16509   if (Spec != AvailSpecs.end())
16510     Version = Spec->getVersion();
16511 
16512   // The use of `@available` in the enclosing function should be analyzed to
16513   // warn when it's used inappropriately (i.e. not if(@available)).
16514   if (getCurFunctionOrMethodDecl())
16515     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16516   else if (getCurBlock() || getCurLambda())
16517     getCurFunction()->HasPotentialAvailabilityViolations = true;
16518 
16519   return new (Context)
16520       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16521 }
16522