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/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68   }
69 
70   // See if this function is unavailable.
71   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
72       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
73     return false;
74 
75   return true;
76 }
77 
78 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
79   // Warn if this is used but marked unused.
80   if (const auto *A = D->getAttr<UnusedAttr>()) {
81     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
82     // should diagnose them.
83     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
84         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
85       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
86       if (DC && !DC->hasAttr<UnusedAttr>())
87         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
88     }
89   }
90 }
91 
92 /// Emit a note explaining that this function is deleted.
93 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
94   assert(Decl->isDeleted());
95 
96   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
97 
98   if (Method && Method->isDeleted() && Method->isDefaulted()) {
99     // If the method was explicitly defaulted, point at that declaration.
100     if (!Method->isImplicit())
101       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
102 
103     // Try to diagnose why this special member function was implicitly
104     // deleted. This might fail, if that reason no longer applies.
105     CXXSpecialMember CSM = getSpecialMember(Method);
106     if (CSM != CXXInvalid)
107       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
108 
109     return;
110   }
111 
112   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
113   if (Ctor && Ctor->isInheritingConstructor())
114     return NoteDeletedInheritingConstructor(Ctor);
115 
116   Diag(Decl->getLocation(), diag::note_availability_specified_here)
117     << Decl << true;
118 }
119 
120 /// Determine whether a FunctionDecl was ever declared with an
121 /// explicit storage class.
122 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
123   for (auto I : D->redecls()) {
124     if (I->getStorageClass() != SC_None)
125       return true;
126   }
127   return false;
128 }
129 
130 /// Check whether we're in an extern inline function and referring to a
131 /// variable or function with internal linkage (C11 6.7.4p3).
132 ///
133 /// This is only a warning because we used to silently accept this code, but
134 /// in many cases it will not behave correctly. This is not enabled in C++ mode
135 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
136 /// and so while there may still be user mistakes, most of the time we can't
137 /// prove that there are errors.
138 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
139                                                       const NamedDecl *D,
140                                                       SourceLocation Loc) {
141   // This is disabled under C++; there are too many ways for this to fire in
142   // contexts where the warning is a false positive, or where it is technically
143   // correct but benign.
144   if (S.getLangOpts().CPlusPlus)
145     return;
146 
147   // Check if this is an inlined function or method.
148   FunctionDecl *Current = S.getCurFunctionDecl();
149   if (!Current)
150     return;
151   if (!Current->isInlined())
152     return;
153   if (!Current->isExternallyVisible())
154     return;
155 
156   // Check if the decl has internal linkage.
157   if (D->getFormalLinkage() != InternalLinkage)
158     return;
159 
160   // Downgrade from ExtWarn to Extension if
161   //  (1) the supposedly external inline function is in the main file,
162   //      and probably won't be included anywhere else.
163   //  (2) the thing we're referencing is a pure function.
164   //  (3) the thing we're referencing is another inline function.
165   // This last can give us false negatives, but it's better than warning on
166   // wrappers for simple C library functions.
167   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
168   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
169   if (!DowngradeWarning && UsedFn)
170     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
171 
172   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
173                                : diag::ext_internal_in_extern_inline)
174     << /*IsVar=*/!UsedFn << D;
175 
176   S.MaybeSuggestAddingStaticToDecl(Current);
177 
178   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
179       << D;
180 }
181 
182 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
183   const FunctionDecl *First = Cur->getFirstDecl();
184 
185   // Suggest "static" on the function, if possible.
186   if (!hasAnyExplicitStorageClass(First)) {
187     SourceLocation DeclBegin = First->getSourceRange().getBegin();
188     Diag(DeclBegin, diag::note_convert_inline_to_static)
189       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
190   }
191 }
192 
193 /// Determine whether the use of this declaration is valid, and
194 /// emit any corresponding diagnostics.
195 ///
196 /// This routine diagnoses various problems with referencing
197 /// declarations that can occur when using a declaration. For example,
198 /// it might warn if a deprecated or unavailable declaration is being
199 /// used, or produce an error (and return true) if a C++0x deleted
200 /// function is being used.
201 ///
202 /// \returns true if there was an error (this declaration cannot be
203 /// referenced), false otherwise.
204 ///
205 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
206                              const ObjCInterfaceDecl *UnknownObjCClass,
207                              bool ObjCPropertyAccess,
208                              bool AvoidPartialAvailabilityChecks) {
209   SourceLocation Loc = Locs.front();
210   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
211     // If there were any diagnostics suppressed by template argument deduction,
212     // emit them now.
213     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
214     if (Pos != SuppressedDiagnostics.end()) {
215       for (const PartialDiagnosticAt &Suppressed : Pos->second)
216         Diag(Suppressed.first, Suppressed.second);
217 
218       // Clear out the list of suppressed diagnostics, so that we don't emit
219       // them again for this specialization. However, we don't obsolete this
220       // entry from the table, because we want to avoid ever emitting these
221       // diagnostics again.
222       Pos->second.clear();
223     }
224 
225     // C++ [basic.start.main]p3:
226     //   The function 'main' shall not be used within a program.
227     if (cast<FunctionDecl>(D)->isMain())
228       Diag(Loc, diag::ext_main_used);
229   }
230 
231   // See if this is an auto-typed variable whose initializer we are parsing.
232   if (ParsingInitForAutoVars.count(D)) {
233     if (isa<BindingDecl>(D)) {
234       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
235         << D->getDeclName();
236     } else {
237       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
238         << D->getDeclName() << cast<VarDecl>(D)->getType();
239     }
240     return true;
241   }
242 
243   // See if this is a deleted function.
244   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245     if (FD->isDeleted()) {
246       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
247       if (Ctor && Ctor->isInheritingConstructor())
248         Diag(Loc, diag::err_deleted_inherited_ctor_use)
249             << Ctor->getParent()
250             << Ctor->getInheritedConstructor().getConstructor()->getParent();
251       else
252         Diag(Loc, diag::err_deleted_function_use);
253       NoteDeletedFunction(FD);
254       return true;
255     }
256 
257     // If the function has a deduced return type, and we can't deduce it,
258     // then we can't use it either.
259     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
260         DeduceReturnType(FD, Loc))
261       return true;
262 
263     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
264       return true;
265   }
266 
267   auto getReferencedObjCProp = [](const NamedDecl *D) ->
268                                       const ObjCPropertyDecl * {
269     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
270       return MD->findPropertyDecl();
271     return nullptr;
272   };
273   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
274     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
275       return true;
276   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
277       return true;
278   }
279 
280   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
281   // Only the variables omp_in and omp_out are allowed in the combiner.
282   // Only the variables omp_priv and omp_orig are allowed in the
283   // initializer-clause.
284   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
285   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
286       isa<VarDecl>(D)) {
287     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
288         << getCurFunction()->HasOMPDeclareReductionCombiner;
289     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
290     return true;
291   }
292 
293   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
294                              AvoidPartialAvailabilityChecks);
295 
296   DiagnoseUnusedOfDecl(*this, D, Loc);
297 
298   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
299 
300   return false;
301 }
302 
303 /// Retrieve the message suffix that should be added to a
304 /// diagnostic complaining about the given function being deleted or
305 /// unavailable.
306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
307   std::string Message;
308   if (FD->getAvailability(&Message))
309     return ": " + Message;
310 
311   return std::string();
312 }
313 
314 /// DiagnoseSentinelCalls - This routine checks whether a call or
315 /// message-send is to a declaration with the sentinel attribute, and
316 /// if so, it checks that the requirements of the sentinel are
317 /// satisfied.
318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
319                                  ArrayRef<Expr *> Args) {
320   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
321   if (!attr)
322     return;
323 
324   // The number of formal parameters of the declaration.
325   unsigned numFormalParams;
326 
327   // The kind of declaration.  This is also an index into a %select in
328   // the diagnostic.
329   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
330 
331   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
332     numFormalParams = MD->param_size();
333     calleeType = CT_Method;
334   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
335     numFormalParams = FD->param_size();
336     calleeType = CT_Function;
337   } else if (isa<VarDecl>(D)) {
338     QualType type = cast<ValueDecl>(D)->getType();
339     const FunctionType *fn = nullptr;
340     if (const PointerType *ptr = type->getAs<PointerType>()) {
341       fn = ptr->getPointeeType()->getAs<FunctionType>();
342       if (!fn) return;
343       calleeType = CT_Function;
344     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
345       fn = ptr->getPointeeType()->castAs<FunctionType>();
346       calleeType = CT_Block;
347     } else {
348       return;
349     }
350 
351     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
352       numFormalParams = proto->getNumParams();
353     } else {
354       numFormalParams = 0;
355     }
356   } else {
357     return;
358   }
359 
360   // "nullPos" is the number of formal parameters at the end which
361   // effectively count as part of the variadic arguments.  This is
362   // useful if you would prefer to not have *any* formal parameters,
363   // but the language forces you to have at least one.
364   unsigned nullPos = attr->getNullPos();
365   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
366   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
367 
368   // The number of arguments which should follow the sentinel.
369   unsigned numArgsAfterSentinel = attr->getSentinel();
370 
371   // If there aren't enough arguments for all the formal parameters,
372   // the sentinel, and the args after the sentinel, complain.
373   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
374     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
375     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
376     return;
377   }
378 
379   // Otherwise, find the sentinel expression.
380   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
381   if (!sentinelExpr) return;
382   if (sentinelExpr->isValueDependent()) return;
383   if (Context.isSentinelNullExpr(sentinelExpr)) return;
384 
385   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
386   // or 'NULL' if those are actually defined in the context.  Only use
387   // 'nil' for ObjC methods, where it's much more likely that the
388   // variadic arguments form a list of object pointers.
389   SourceLocation MissingNilLoc
390     = getLocForEndOfToken(sentinelExpr->getLocEnd());
391   std::string NullValue;
392   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
393     NullValue = "nil";
394   else if (getLangOpts().CPlusPlus11)
395     NullValue = "nullptr";
396   else if (PP.isMacroDefined("NULL"))
397     NullValue = "NULL";
398   else
399     NullValue = "(void*) 0";
400 
401   if (MissingNilLoc.isInvalid())
402     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
403   else
404     Diag(MissingNilLoc, diag::warn_missing_sentinel)
405       << int(calleeType)
406       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
407   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
408 }
409 
410 SourceRange Sema::getExprRange(Expr *E) const {
411   return E ? E->getSourceRange() : SourceRange();
412 }
413 
414 //===----------------------------------------------------------------------===//
415 //  Standard Promotions and Conversions
416 //===----------------------------------------------------------------------===//
417 
418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
419 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
420   // Handle any placeholder expressions which made it here.
421   if (E->getType()->isPlaceholderType()) {
422     ExprResult result = CheckPlaceholderExpr(E);
423     if (result.isInvalid()) return ExprError();
424     E = result.get();
425   }
426 
427   QualType Ty = E->getType();
428   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
429 
430   if (Ty->isFunctionType()) {
431     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
432       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
433         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
434           return ExprError();
435 
436     E = ImpCastExprToType(E, Context.getPointerType(Ty),
437                           CK_FunctionToPointerDecay).get();
438   } else if (Ty->isArrayType()) {
439     // In C90 mode, arrays only promote to pointers if the array expression is
440     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
441     // type 'array of type' is converted to an expression that has type 'pointer
442     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
443     // that has type 'array of type' ...".  The relevant change is "an lvalue"
444     // (C90) to "an expression" (C99).
445     //
446     // C++ 4.2p1:
447     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
448     // T" can be converted to an rvalue of type "pointer to T".
449     //
450     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
451       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
452                             CK_ArrayToPointerDecay).get();
453   }
454   return E;
455 }
456 
457 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
458   // Check to see if we are dereferencing a null pointer.  If so,
459   // and if not volatile-qualified, this is undefined behavior that the
460   // optimizer will delete, so warn about it.  People sometimes try to use this
461   // to get a deterministic trap and are surprised by clang's behavior.  This
462   // only handles the pattern "*null", which is a very syntactic check.
463   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
464     if (UO->getOpcode() == UO_Deref &&
465         UO->getSubExpr()->IgnoreParenCasts()->
466           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
467         !UO->getType().isVolatileQualified()) {
468     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
469                           S.PDiag(diag::warn_indirection_through_null)
470                             << UO->getSubExpr()->getSourceRange());
471     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
472                         S.PDiag(diag::note_indirection_through_null));
473   }
474 }
475 
476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
477                                     SourceLocation AssignLoc,
478                                     const Expr* RHS) {
479   const ObjCIvarDecl *IV = OIRE->getDecl();
480   if (!IV)
481     return;
482 
483   DeclarationName MemberName = IV->getDeclName();
484   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
485   if (!Member || !Member->isStr("isa"))
486     return;
487 
488   const Expr *Base = OIRE->getBase();
489   QualType BaseType = Base->getType();
490   if (OIRE->isArrow())
491     BaseType = BaseType->getPointeeType();
492   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
493     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
494       ObjCInterfaceDecl *ClassDeclared = nullptr;
495       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
496       if (!ClassDeclared->getSuperClass()
497           && (*ClassDeclared->ivar_begin()) == IV) {
498         if (RHS) {
499           NamedDecl *ObjectSetClass =
500             S.LookupSingleName(S.TUScope,
501                                &S.Context.Idents.get("object_setClass"),
502                                SourceLocation(), S.LookupOrdinaryName);
503           if (ObjectSetClass) {
504             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
505             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
506             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
507             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
508                                                      AssignLoc), ",") <<
509             FixItHint::CreateInsertion(RHSLocEnd, ")");
510           }
511           else
512             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
513         } else {
514           NamedDecl *ObjectGetClass =
515             S.LookupSingleName(S.TUScope,
516                                &S.Context.Idents.get("object_getClass"),
517                                SourceLocation(), S.LookupOrdinaryName);
518           if (ObjectGetClass)
519             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
520             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
521             FixItHint::CreateReplacement(
522                                          SourceRange(OIRE->getOpLoc(),
523                                                      OIRE->getLocEnd()), ")");
524           else
525             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
526         }
527         S.Diag(IV->getLocation(), diag::note_ivar_decl);
528       }
529     }
530 }
531 
532 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
533   // Handle any placeholder expressions which made it here.
534   if (E->getType()->isPlaceholderType()) {
535     ExprResult result = CheckPlaceholderExpr(E);
536     if (result.isInvalid()) return ExprError();
537     E = result.get();
538   }
539 
540   // C++ [conv.lval]p1:
541   //   A glvalue of a non-function, non-array type T can be
542   //   converted to a prvalue.
543   if (!E->isGLValue()) return E;
544 
545   QualType T = E->getType();
546   assert(!T.isNull() && "r-value conversion on typeless expression?");
547 
548   // We don't want to throw lvalue-to-rvalue casts on top of
549   // expressions of certain types in C++.
550   if (getLangOpts().CPlusPlus &&
551       (E->getType() == Context.OverloadTy ||
552        T->isDependentType() ||
553        T->isRecordType()))
554     return E;
555 
556   // The C standard is actually really unclear on this point, and
557   // DR106 tells us what the result should be but not why.  It's
558   // generally best to say that void types just doesn't undergo
559   // lvalue-to-rvalue at all.  Note that expressions of unqualified
560   // 'void' type are never l-values, but qualified void can be.
561   if (T->isVoidType())
562     return E;
563 
564   // OpenCL usually rejects direct accesses to values of 'half' type.
565   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
566       T->isHalfType()) {
567     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
568       << 0 << T;
569     return ExprError();
570   }
571 
572   CheckForNullPointerDereference(*this, E);
573   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
574     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
575                                      &Context.Idents.get("object_getClass"),
576                                      SourceLocation(), LookupOrdinaryName);
577     if (ObjectGetClass)
578       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
579         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
580         FixItHint::CreateReplacement(
581                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
582     else
583       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
584   }
585   else if (const ObjCIvarRefExpr *OIRE =
586             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
587     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
588 
589   // C++ [conv.lval]p1:
590   //   [...] If T is a non-class type, the type of the prvalue is the
591   //   cv-unqualified version of T. Otherwise, the type of the
592   //   rvalue is T.
593   //
594   // C99 6.3.2.1p2:
595   //   If the lvalue has qualified type, the value has the unqualified
596   //   version of the type of the lvalue; otherwise, the value has the
597   //   type of the lvalue.
598   if (T.hasQualifiers())
599     T = T.getUnqualifiedType();
600 
601   // Under the MS ABI, lock down the inheritance model now.
602   if (T->isMemberPointerType() &&
603       Context.getTargetInfo().getCXXABI().isMicrosoft())
604     (void)isCompleteType(E->getExprLoc(), T);
605 
606   UpdateMarkingForLValueToRValue(E);
607 
608   // Loading a __weak object implicitly retains the value, so we need a cleanup to
609   // balance that.
610   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
611     Cleanup.setExprNeedsCleanups(true);
612 
613   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
614                                             nullptr, VK_RValue);
615 
616   // C11 6.3.2.1p2:
617   //   ... if the lvalue has atomic type, the value has the non-atomic version
618   //   of the type of the lvalue ...
619   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
620     T = Atomic->getValueType().getUnqualifiedType();
621     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
622                                    nullptr, VK_RValue);
623   }
624 
625   return Res;
626 }
627 
628 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
629   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
630   if (Res.isInvalid())
631     return ExprError();
632   Res = DefaultLvalueConversion(Res.get());
633   if (Res.isInvalid())
634     return ExprError();
635   return Res;
636 }
637 
638 /// CallExprUnaryConversions - a special case of an unary conversion
639 /// performed on a function designator of a call expression.
640 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
641   QualType Ty = E->getType();
642   ExprResult Res = E;
643   // Only do implicit cast for a function type, but not for a pointer
644   // to function type.
645   if (Ty->isFunctionType()) {
646     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
647                             CK_FunctionToPointerDecay).get();
648     if (Res.isInvalid())
649       return ExprError();
650   }
651   Res = DefaultLvalueConversion(Res.get());
652   if (Res.isInvalid())
653     return ExprError();
654   return Res.get();
655 }
656 
657 /// UsualUnaryConversions - Performs various conversions that are common to most
658 /// operators (C99 6.3). The conversions of array and function types are
659 /// sometimes suppressed. For example, the array->pointer conversion doesn't
660 /// apply if the array is an argument to the sizeof or address (&) operators.
661 /// In these instances, this routine should *not* be called.
662 ExprResult Sema::UsualUnaryConversions(Expr *E) {
663   // First, convert to an r-value.
664   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
665   if (Res.isInvalid())
666     return ExprError();
667   E = Res.get();
668 
669   QualType Ty = E->getType();
670   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
671 
672   // Half FP have to be promoted to float unless it is natively supported
673   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
674     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
675 
676   // Try to perform integral promotions if the object has a theoretically
677   // promotable type.
678   if (Ty->isIntegralOrUnscopedEnumerationType()) {
679     // C99 6.3.1.1p2:
680     //
681     //   The following may be used in an expression wherever an int or
682     //   unsigned int may be used:
683     //     - an object or expression with an integer type whose integer
684     //       conversion rank is less than or equal to the rank of int
685     //       and unsigned int.
686     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
687     //
688     //   If an int can represent all values of the original type, the
689     //   value is converted to an int; otherwise, it is converted to an
690     //   unsigned int. These are called the integer promotions. All
691     //   other types are unchanged by the integer promotions.
692 
693     QualType PTy = Context.isPromotableBitField(E);
694     if (!PTy.isNull()) {
695       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
696       return E;
697     }
698     if (Ty->isPromotableIntegerType()) {
699       QualType PT = Context.getPromotedIntegerType(Ty);
700       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
701       return E;
702     }
703   }
704   return E;
705 }
706 
707 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
708 /// do not have a prototype. Arguments that have type float or __fp16
709 /// are promoted to double. All other argument types are converted by
710 /// UsualUnaryConversions().
711 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
712   QualType Ty = E->getType();
713   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
714 
715   ExprResult Res = UsualUnaryConversions(E);
716   if (Res.isInvalid())
717     return ExprError();
718   E = Res.get();
719 
720   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
721   // promote to double.
722   // Note that default argument promotion applies only to float (and
723   // half/fp16); it does not apply to _Float16.
724   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
725   if (BTy && (BTy->getKind() == BuiltinType::Half ||
726               BTy->getKind() == BuiltinType::Float)) {
727     if (getLangOpts().OpenCL &&
728         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
729         if (BTy->getKind() == BuiltinType::Half) {
730             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
731         }
732     } else {
733       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
734     }
735   }
736 
737   // C++ performs lvalue-to-rvalue conversion as a default argument
738   // promotion, even on class types, but note:
739   //   C++11 [conv.lval]p2:
740   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
741   //     operand or a subexpression thereof the value contained in the
742   //     referenced object is not accessed. Otherwise, if the glvalue
743   //     has a class type, the conversion copy-initializes a temporary
744   //     of type T from the glvalue and the result of the conversion
745   //     is a prvalue for the temporary.
746   // FIXME: add some way to gate this entire thing for correctness in
747   // potentially potentially evaluated contexts.
748   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
749     ExprResult Temp = PerformCopyInitialization(
750                        InitializedEntity::InitializeTemporary(E->getType()),
751                                                 E->getExprLoc(), E);
752     if (Temp.isInvalid())
753       return ExprError();
754     E = Temp.get();
755   }
756 
757   return E;
758 }
759 
760 /// Determine the degree of POD-ness for an expression.
761 /// Incomplete types are considered POD, since this check can be performed
762 /// when we're in an unevaluated context.
763 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
764   if (Ty->isIncompleteType()) {
765     // C++11 [expr.call]p7:
766     //   After these conversions, if the argument does not have arithmetic,
767     //   enumeration, pointer, pointer to member, or class type, the program
768     //   is ill-formed.
769     //
770     // Since we've already performed array-to-pointer and function-to-pointer
771     // decay, the only such type in C++ is cv void. This also handles
772     // initializer lists as variadic arguments.
773     if (Ty->isVoidType())
774       return VAK_Invalid;
775 
776     if (Ty->isObjCObjectType())
777       return VAK_Invalid;
778     return VAK_Valid;
779   }
780 
781   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
782     return VAK_Invalid;
783 
784   if (Ty.isCXX98PODType(Context))
785     return VAK_Valid;
786 
787   // C++11 [expr.call]p7:
788   //   Passing a potentially-evaluated argument of class type (Clause 9)
789   //   having a non-trivial copy constructor, a non-trivial move constructor,
790   //   or a non-trivial destructor, with no corresponding parameter,
791   //   is conditionally-supported with implementation-defined semantics.
792   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
793     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
794       if (!Record->hasNonTrivialCopyConstructor() &&
795           !Record->hasNonTrivialMoveConstructor() &&
796           !Record->hasNonTrivialDestructor())
797         return VAK_ValidInCXX11;
798 
799   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
800     return VAK_Valid;
801 
802   if (Ty->isObjCObjectType())
803     return VAK_Invalid;
804 
805   if (getLangOpts().MSVCCompat)
806     return VAK_MSVCUndefined;
807 
808   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
809   // permitted to reject them. We should consider doing so.
810   return VAK_Undefined;
811 }
812 
813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
814   // Don't allow one to pass an Objective-C interface to a vararg.
815   const QualType &Ty = E->getType();
816   VarArgKind VAK = isValidVarArgType(Ty);
817 
818   // Complain about passing non-POD types through varargs.
819   switch (VAK) {
820   case VAK_ValidInCXX11:
821     DiagRuntimeBehavior(
822         E->getLocStart(), nullptr,
823         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
824           << Ty << CT);
825     LLVM_FALLTHROUGH;
826   case VAK_Valid:
827     if (Ty->isRecordType()) {
828       // This is unlikely to be what the user intended. If the class has a
829       // 'c_str' member function, the user probably meant to call that.
830       DiagRuntimeBehavior(E->getLocStart(), nullptr,
831                           PDiag(diag::warn_pass_class_arg_to_vararg)
832                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
833     }
834     break;
835 
836   case VAK_Undefined:
837   case VAK_MSVCUndefined:
838     DiagRuntimeBehavior(
839         E->getLocStart(), nullptr,
840         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
841           << getLangOpts().CPlusPlus11 << Ty << CT);
842     break;
843 
844   case VAK_Invalid:
845     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
846       Diag(E->getLocStart(),
847            diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
848     else if (Ty->isObjCObjectType())
849       DiagRuntimeBehavior(
850           E->getLocStart(), nullptr,
851           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
852             << Ty << CT);
853     else
854       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
855         << isa<InitListExpr>(E) << Ty << CT;
856     break;
857   }
858 }
859 
860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
861 /// will create a trap if the resulting type is not a POD type.
862 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
863                                                   FunctionDecl *FDecl) {
864   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
865     // Strip the unbridged-cast placeholder expression off, if applicable.
866     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
867         (CT == VariadicMethod ||
868          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
869       E = stripARCUnbridgedCast(E);
870 
871     // Otherwise, do normal placeholder checking.
872     } else {
873       ExprResult ExprRes = CheckPlaceholderExpr(E);
874       if (ExprRes.isInvalid())
875         return ExprError();
876       E = ExprRes.get();
877     }
878   }
879 
880   ExprResult ExprRes = DefaultArgumentPromotion(E);
881   if (ExprRes.isInvalid())
882     return ExprError();
883   E = ExprRes.get();
884 
885   // Diagnostics regarding non-POD argument types are
886   // emitted along with format string checking in Sema::CheckFunctionCall().
887   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
888     // Turn this into a trap.
889     CXXScopeSpec SS;
890     SourceLocation TemplateKWLoc;
891     UnqualifiedId Name;
892     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
893                        E->getLocStart());
894     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
895                                           Name, true, false);
896     if (TrapFn.isInvalid())
897       return ExprError();
898 
899     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
900                                     E->getLocStart(), None,
901                                     E->getLocEnd());
902     if (Call.isInvalid())
903       return ExprError();
904 
905     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
906                                   Call.get(), E);
907     if (Comma.isInvalid())
908       return ExprError();
909     return Comma.get();
910   }
911 
912   if (!getLangOpts().CPlusPlus &&
913       RequireCompleteType(E->getExprLoc(), E->getType(),
914                           diag::err_call_incomplete_argument))
915     return ExprError();
916 
917   return E;
918 }
919 
920 /// Converts an integer to complex float type.  Helper function of
921 /// UsualArithmeticConversions()
922 ///
923 /// \return false if the integer expression is an integer type and is
924 /// successfully converted to the complex type.
925 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
926                                                   ExprResult &ComplexExpr,
927                                                   QualType IntTy,
928                                                   QualType ComplexTy,
929                                                   bool SkipCast) {
930   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
931   if (SkipCast) return false;
932   if (IntTy->isIntegerType()) {
933     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
934     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
935     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
936                                   CK_FloatingRealToComplex);
937   } else {
938     assert(IntTy->isComplexIntegerType());
939     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
940                                   CK_IntegralComplexToFloatingComplex);
941   }
942   return false;
943 }
944 
945 /// Handle arithmetic conversion with complex types.  Helper function of
946 /// UsualArithmeticConversions()
947 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
948                                              ExprResult &RHS, QualType LHSType,
949                                              QualType RHSType,
950                                              bool IsCompAssign) {
951   // if we have an integer operand, the result is the complex type.
952   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
953                                              /*skipCast*/false))
954     return LHSType;
955   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
956                                              /*skipCast*/IsCompAssign))
957     return RHSType;
958 
959   // This handles complex/complex, complex/float, or float/complex.
960   // When both operands are complex, the shorter operand is converted to the
961   // type of the longer, and that is the type of the result. This corresponds
962   // to what is done when combining two real floating-point operands.
963   // The fun begins when size promotion occur across type domains.
964   // From H&S 6.3.4: When one operand is complex and the other is a real
965   // floating-point type, the less precise type is converted, within it's
966   // real or complex domain, to the precision of the other type. For example,
967   // when combining a "long double" with a "double _Complex", the
968   // "double _Complex" is promoted to "long double _Complex".
969 
970   // Compute the rank of the two types, regardless of whether they are complex.
971   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
972 
973   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
974   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
975   QualType LHSElementType =
976       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
977   QualType RHSElementType =
978       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
979 
980   QualType ResultType = S.Context.getComplexType(LHSElementType);
981   if (Order < 0) {
982     // Promote the precision of the LHS if not an assignment.
983     ResultType = S.Context.getComplexType(RHSElementType);
984     if (!IsCompAssign) {
985       if (LHSComplexType)
986         LHS =
987             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
988       else
989         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
990     }
991   } else if (Order > 0) {
992     // Promote the precision of the RHS.
993     if (RHSComplexType)
994       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
995     else
996       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
997   }
998   return ResultType;
999 }
1000 
1001 /// Handle arithmetic conversion from integer to float.  Helper function
1002 /// of UsualArithmeticConversions()
1003 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1004                                            ExprResult &IntExpr,
1005                                            QualType FloatTy, QualType IntTy,
1006                                            bool ConvertFloat, bool ConvertInt) {
1007   if (IntTy->isIntegerType()) {
1008     if (ConvertInt)
1009       // Convert intExpr to the lhs floating point type.
1010       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1011                                     CK_IntegralToFloating);
1012     return FloatTy;
1013   }
1014 
1015   // Convert both sides to the appropriate complex float.
1016   assert(IntTy->isComplexIntegerType());
1017   QualType result = S.Context.getComplexType(FloatTy);
1018 
1019   // _Complex int -> _Complex float
1020   if (ConvertInt)
1021     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1022                                   CK_IntegralComplexToFloatingComplex);
1023 
1024   // float -> _Complex float
1025   if (ConvertFloat)
1026     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1027                                     CK_FloatingRealToComplex);
1028 
1029   return result;
1030 }
1031 
1032 /// Handle arithmethic conversion with floating point types.  Helper
1033 /// function of UsualArithmeticConversions()
1034 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1035                                       ExprResult &RHS, QualType LHSType,
1036                                       QualType RHSType, bool IsCompAssign) {
1037   bool LHSFloat = LHSType->isRealFloatingType();
1038   bool RHSFloat = RHSType->isRealFloatingType();
1039 
1040   // If we have two real floating types, convert the smaller operand
1041   // to the bigger result.
1042   if (LHSFloat && RHSFloat) {
1043     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1044     if (order > 0) {
1045       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1046       return LHSType;
1047     }
1048 
1049     assert(order < 0 && "illegal float comparison");
1050     if (!IsCompAssign)
1051       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1052     return RHSType;
1053   }
1054 
1055   if (LHSFloat) {
1056     // Half FP has to be promoted to float unless it is natively supported
1057     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1058       LHSType = S.Context.FloatTy;
1059 
1060     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1061                                       /*convertFloat=*/!IsCompAssign,
1062                                       /*convertInt=*/ true);
1063   }
1064   assert(RHSFloat);
1065   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1066                                     /*convertInt=*/ true,
1067                                     /*convertFloat=*/!IsCompAssign);
1068 }
1069 
1070 /// Diagnose attempts to convert between __float128 and long double if
1071 /// there is no support for such conversion. Helper function of
1072 /// UsualArithmeticConversions().
1073 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1074                                       QualType RHSType) {
1075   /*  No issue converting if at least one of the types is not a floating point
1076       type or the two types have the same rank.
1077   */
1078   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1079       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1080     return false;
1081 
1082   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1083          "The remaining types must be floating point types.");
1084 
1085   auto *LHSComplex = LHSType->getAs<ComplexType>();
1086   auto *RHSComplex = RHSType->getAs<ComplexType>();
1087 
1088   QualType LHSElemType = LHSComplex ?
1089     LHSComplex->getElementType() : LHSType;
1090   QualType RHSElemType = RHSComplex ?
1091     RHSComplex->getElementType() : RHSType;
1092 
1093   // No issue if the two types have the same representation
1094   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1095       &S.Context.getFloatTypeSemantics(RHSElemType))
1096     return false;
1097 
1098   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1099                                 RHSElemType == S.Context.LongDoubleTy);
1100   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1101                             RHSElemType == S.Context.Float128Ty);
1102 
1103   // We've handled the situation where __float128 and long double have the same
1104   // representation. We allow all conversions for all possible long double types
1105   // except PPC's double double.
1106   return Float128AndLongDouble &&
1107     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1108      &llvm::APFloat::PPCDoubleDouble());
1109 }
1110 
1111 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1112 
1113 namespace {
1114 /// These helper callbacks are placed in an anonymous namespace to
1115 /// permit their use as function template parameters.
1116 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1117   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1118 }
1119 
1120 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1121   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1122                              CK_IntegralComplexCast);
1123 }
1124 }
1125 
1126 /// Handle integer arithmetic conversions.  Helper function of
1127 /// UsualArithmeticConversions()
1128 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1129 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1130                                         ExprResult &RHS, QualType LHSType,
1131                                         QualType RHSType, bool IsCompAssign) {
1132   // The rules for this case are in C99 6.3.1.8
1133   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1134   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1135   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1136   if (LHSSigned == RHSSigned) {
1137     // Same signedness; use the higher-ranked type
1138     if (order >= 0) {
1139       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1140       return LHSType;
1141     } else if (!IsCompAssign)
1142       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1143     return RHSType;
1144   } else if (order != (LHSSigned ? 1 : -1)) {
1145     // The unsigned type has greater than or equal rank to the
1146     // signed type, so use the unsigned type
1147     if (RHSSigned) {
1148       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1149       return LHSType;
1150     } else if (!IsCompAssign)
1151       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1152     return RHSType;
1153   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1154     // The two types are different widths; if we are here, that
1155     // means the signed type is larger than the unsigned type, so
1156     // use the signed type.
1157     if (LHSSigned) {
1158       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159       return LHSType;
1160     } else if (!IsCompAssign)
1161       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162     return RHSType;
1163   } else {
1164     // The signed type is higher-ranked than the unsigned type,
1165     // but isn't actually any bigger (like unsigned int and long
1166     // on most 32-bit systems).  Use the unsigned type corresponding
1167     // to the signed type.
1168     QualType result =
1169       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1170     RHS = (*doRHSCast)(S, RHS.get(), result);
1171     if (!IsCompAssign)
1172       LHS = (*doLHSCast)(S, LHS.get(), result);
1173     return result;
1174   }
1175 }
1176 
1177 /// Handle conversions with GCC complex int extension.  Helper function
1178 /// of UsualArithmeticConversions()
1179 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1180                                            ExprResult &RHS, QualType LHSType,
1181                                            QualType RHSType,
1182                                            bool IsCompAssign) {
1183   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1184   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1185 
1186   if (LHSComplexInt && RHSComplexInt) {
1187     QualType LHSEltType = LHSComplexInt->getElementType();
1188     QualType RHSEltType = RHSComplexInt->getElementType();
1189     QualType ScalarType =
1190       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1191         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1192 
1193     return S.Context.getComplexType(ScalarType);
1194   }
1195 
1196   if (LHSComplexInt) {
1197     QualType LHSEltType = LHSComplexInt->getElementType();
1198     QualType ScalarType =
1199       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1200         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1201     QualType ComplexType = S.Context.getComplexType(ScalarType);
1202     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1203                               CK_IntegralRealToComplex);
1204 
1205     return ComplexType;
1206   }
1207 
1208   assert(RHSComplexInt);
1209 
1210   QualType RHSEltType = RHSComplexInt->getElementType();
1211   QualType ScalarType =
1212     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1213       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1214   QualType ComplexType = S.Context.getComplexType(ScalarType);
1215 
1216   if (!IsCompAssign)
1217     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1218                               CK_IntegralRealToComplex);
1219   return ComplexType;
1220 }
1221 
1222 /// UsualArithmeticConversions - Performs various conversions that are common to
1223 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1224 /// routine returns the first non-arithmetic type found. The client is
1225 /// responsible for emitting appropriate error diagnostics.
1226 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1227                                           bool IsCompAssign) {
1228   if (!IsCompAssign) {
1229     LHS = UsualUnaryConversions(LHS.get());
1230     if (LHS.isInvalid())
1231       return QualType();
1232   }
1233 
1234   RHS = UsualUnaryConversions(RHS.get());
1235   if (RHS.isInvalid())
1236     return QualType();
1237 
1238   // For conversion purposes, we ignore any qualifiers.
1239   // For example, "const float" and "float" are equivalent.
1240   QualType LHSType =
1241     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1242   QualType RHSType =
1243     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1244 
1245   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1246   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1247     LHSType = AtomicLHS->getValueType();
1248 
1249   // If both types are identical, no conversion is needed.
1250   if (LHSType == RHSType)
1251     return LHSType;
1252 
1253   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1254   // The caller can deal with this (e.g. pointer + int).
1255   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1256     return QualType();
1257 
1258   // Apply unary and bitfield promotions to the LHS's type.
1259   QualType LHSUnpromotedType = LHSType;
1260   if (LHSType->isPromotableIntegerType())
1261     LHSType = Context.getPromotedIntegerType(LHSType);
1262   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1263   if (!LHSBitfieldPromoteTy.isNull())
1264     LHSType = LHSBitfieldPromoteTy;
1265   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1266     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1267 
1268   // If both types are identical, no conversion is needed.
1269   if (LHSType == RHSType)
1270     return LHSType;
1271 
1272   // At this point, we have two different arithmetic types.
1273 
1274   // Diagnose attempts to convert between __float128 and long double where
1275   // such conversions currently can't be handled.
1276   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1277     return QualType();
1278 
1279   // Handle complex types first (C99 6.3.1.8p1).
1280   if (LHSType->isComplexType() || RHSType->isComplexType())
1281     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1282                                         IsCompAssign);
1283 
1284   // Now handle "real" floating types (i.e. float, double, long double).
1285   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1286     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1287                                  IsCompAssign);
1288 
1289   // Handle GCC complex int extension.
1290   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1291     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1292                                       IsCompAssign);
1293 
1294   // Finally, we have two differing integer types.
1295   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1296            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1297 }
1298 
1299 
1300 //===----------------------------------------------------------------------===//
1301 //  Semantic Analysis for various Expression Types
1302 //===----------------------------------------------------------------------===//
1303 
1304 
1305 ExprResult
1306 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1307                                 SourceLocation DefaultLoc,
1308                                 SourceLocation RParenLoc,
1309                                 Expr *ControllingExpr,
1310                                 ArrayRef<ParsedType> ArgTypes,
1311                                 ArrayRef<Expr *> ArgExprs) {
1312   unsigned NumAssocs = ArgTypes.size();
1313   assert(NumAssocs == ArgExprs.size());
1314 
1315   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1316   for (unsigned i = 0; i < NumAssocs; ++i) {
1317     if (ArgTypes[i])
1318       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1319     else
1320       Types[i] = nullptr;
1321   }
1322 
1323   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1324                                              ControllingExpr,
1325                                              llvm::makeArrayRef(Types, NumAssocs),
1326                                              ArgExprs);
1327   delete [] Types;
1328   return ER;
1329 }
1330 
1331 ExprResult
1332 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1333                                  SourceLocation DefaultLoc,
1334                                  SourceLocation RParenLoc,
1335                                  Expr *ControllingExpr,
1336                                  ArrayRef<TypeSourceInfo *> Types,
1337                                  ArrayRef<Expr *> Exprs) {
1338   unsigned NumAssocs = Types.size();
1339   assert(NumAssocs == Exprs.size());
1340 
1341   // Decay and strip qualifiers for the controlling expression type, and handle
1342   // placeholder type replacement. See committee discussion from WG14 DR423.
1343   {
1344     EnterExpressionEvaluationContext Unevaluated(
1345         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1346     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1347     if (R.isInvalid())
1348       return ExprError();
1349     ControllingExpr = R.get();
1350   }
1351 
1352   // The controlling expression is an unevaluated operand, so side effects are
1353   // likely unintended.
1354   if (!inTemplateInstantiation() &&
1355       ControllingExpr->HasSideEffects(Context, false))
1356     Diag(ControllingExpr->getExprLoc(),
1357          diag::warn_side_effects_unevaluated_context);
1358 
1359   bool TypeErrorFound = false,
1360        IsResultDependent = ControllingExpr->isTypeDependent(),
1361        ContainsUnexpandedParameterPack
1362          = ControllingExpr->containsUnexpandedParameterPack();
1363 
1364   for (unsigned i = 0; i < NumAssocs; ++i) {
1365     if (Exprs[i]->containsUnexpandedParameterPack())
1366       ContainsUnexpandedParameterPack = true;
1367 
1368     if (Types[i]) {
1369       if (Types[i]->getType()->containsUnexpandedParameterPack())
1370         ContainsUnexpandedParameterPack = true;
1371 
1372       if (Types[i]->getType()->isDependentType()) {
1373         IsResultDependent = true;
1374       } else {
1375         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1376         // complete object type other than a variably modified type."
1377         unsigned D = 0;
1378         if (Types[i]->getType()->isIncompleteType())
1379           D = diag::err_assoc_type_incomplete;
1380         else if (!Types[i]->getType()->isObjectType())
1381           D = diag::err_assoc_type_nonobject;
1382         else if (Types[i]->getType()->isVariablyModifiedType())
1383           D = diag::err_assoc_type_variably_modified;
1384 
1385         if (D != 0) {
1386           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1387             << Types[i]->getTypeLoc().getSourceRange()
1388             << Types[i]->getType();
1389           TypeErrorFound = true;
1390         }
1391 
1392         // C11 6.5.1.1p2 "No two generic associations in the same generic
1393         // selection shall specify compatible types."
1394         for (unsigned j = i+1; j < NumAssocs; ++j)
1395           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1396               Context.typesAreCompatible(Types[i]->getType(),
1397                                          Types[j]->getType())) {
1398             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1399                  diag::err_assoc_compatible_types)
1400               << Types[j]->getTypeLoc().getSourceRange()
1401               << Types[j]->getType()
1402               << Types[i]->getType();
1403             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1404                  diag::note_compat_assoc)
1405               << Types[i]->getTypeLoc().getSourceRange()
1406               << Types[i]->getType();
1407             TypeErrorFound = true;
1408           }
1409       }
1410     }
1411   }
1412   if (TypeErrorFound)
1413     return ExprError();
1414 
1415   // If we determined that the generic selection is result-dependent, don't
1416   // try to compute the result expression.
1417   if (IsResultDependent)
1418     return new (Context) GenericSelectionExpr(
1419         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1420         ContainsUnexpandedParameterPack);
1421 
1422   SmallVector<unsigned, 1> CompatIndices;
1423   unsigned DefaultIndex = -1U;
1424   for (unsigned i = 0; i < NumAssocs; ++i) {
1425     if (!Types[i])
1426       DefaultIndex = i;
1427     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1428                                         Types[i]->getType()))
1429       CompatIndices.push_back(i);
1430   }
1431 
1432   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1433   // type compatible with at most one of the types named in its generic
1434   // association list."
1435   if (CompatIndices.size() > 1) {
1436     // We strip parens here because the controlling expression is typically
1437     // parenthesized in macro definitions.
1438     ControllingExpr = ControllingExpr->IgnoreParens();
1439     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1440       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1441       << (unsigned) CompatIndices.size();
1442     for (unsigned I : CompatIndices) {
1443       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1444            diag::note_compat_assoc)
1445         << Types[I]->getTypeLoc().getSourceRange()
1446         << Types[I]->getType();
1447     }
1448     return ExprError();
1449   }
1450 
1451   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1452   // its controlling expression shall have type compatible with exactly one of
1453   // the types named in its generic association list."
1454   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1455     // We strip parens here because the controlling expression is typically
1456     // parenthesized in macro definitions.
1457     ControllingExpr = ControllingExpr->IgnoreParens();
1458     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1459       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1460     return ExprError();
1461   }
1462 
1463   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1464   // type name that is compatible with the type of the controlling expression,
1465   // then the result expression of the generic selection is the expression
1466   // in that generic association. Otherwise, the result expression of the
1467   // generic selection is the expression in the default generic association."
1468   unsigned ResultIndex =
1469     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1470 
1471   return new (Context) GenericSelectionExpr(
1472       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1473       ContainsUnexpandedParameterPack, ResultIndex);
1474 }
1475 
1476 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1477 /// location of the token and the offset of the ud-suffix within it.
1478 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1479                                      unsigned Offset) {
1480   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1481                                         S.getLangOpts());
1482 }
1483 
1484 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1485 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1486 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1487                                                  IdentifierInfo *UDSuffix,
1488                                                  SourceLocation UDSuffixLoc,
1489                                                  ArrayRef<Expr*> Args,
1490                                                  SourceLocation LitEndLoc) {
1491   assert(Args.size() <= 2 && "too many arguments for literal operator");
1492 
1493   QualType ArgTy[2];
1494   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1495     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1496     if (ArgTy[ArgIdx]->isArrayType())
1497       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1498   }
1499 
1500   DeclarationName OpName =
1501     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1502   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1503   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1504 
1505   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1506   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1507                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1508                               /*AllowStringTemplate*/ false,
1509                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1510     return ExprError();
1511 
1512   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1513 }
1514 
1515 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1516 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1517 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1518 /// multiple tokens.  However, the common case is that StringToks points to one
1519 /// string.
1520 ///
1521 ExprResult
1522 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1523   assert(!StringToks.empty() && "Must have at least one string!");
1524 
1525   StringLiteralParser Literal(StringToks, PP);
1526   if (Literal.hadError)
1527     return ExprError();
1528 
1529   SmallVector<SourceLocation, 4> StringTokLocs;
1530   for (const Token &Tok : StringToks)
1531     StringTokLocs.push_back(Tok.getLocation());
1532 
1533   QualType CharTy = Context.CharTy;
1534   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1535   if (Literal.isWide()) {
1536     CharTy = Context.getWideCharType();
1537     Kind = StringLiteral::Wide;
1538   } else if (Literal.isUTF8()) {
1539     if (getLangOpts().Char8)
1540       CharTy = Context.Char8Ty;
1541     Kind = StringLiteral::UTF8;
1542   } else if (Literal.isUTF16()) {
1543     CharTy = Context.Char16Ty;
1544     Kind = StringLiteral::UTF16;
1545   } else if (Literal.isUTF32()) {
1546     CharTy = Context.Char32Ty;
1547     Kind = StringLiteral::UTF32;
1548   } else if (Literal.isPascal()) {
1549     CharTy = Context.UnsignedCharTy;
1550   }
1551 
1552   QualType CharTyConst = CharTy;
1553   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1554   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1555     CharTyConst.addConst();
1556 
1557   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1558 
1559   // Get an array type for the string, according to C99 6.4.5.  This includes
1560   // the nul terminator character as well as the string length for pascal
1561   // strings.
1562   QualType StrTy = Context.getConstantArrayType(
1563       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1564       ArrayType::Normal, 0);
1565 
1566   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1567   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1568                                              Kind, Literal.Pascal, StrTy,
1569                                              &StringTokLocs[0],
1570                                              StringTokLocs.size());
1571   if (Literal.getUDSuffix().empty())
1572     return Lit;
1573 
1574   // We're building a user-defined literal.
1575   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1576   SourceLocation UDSuffixLoc =
1577     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1578                    Literal.getUDSuffixOffset());
1579 
1580   // Make sure we're allowed user-defined literals here.
1581   if (!UDLScope)
1582     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1583 
1584   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1585   //   operator "" X (str, len)
1586   QualType SizeType = Context.getSizeType();
1587 
1588   DeclarationName OpName =
1589     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593   QualType ArgTy[] = {
1594     Context.getArrayDecayedType(StrTy), SizeType
1595   };
1596 
1597   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1598   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1599                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1600                                 /*AllowStringTemplate*/ true,
1601                                 /*DiagnoseMissing*/ true)) {
1602 
1603   case LOLR_Cooked: {
1604     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1605     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1606                                                     StringTokLocs[0]);
1607     Expr *Args[] = { Lit, LenArg };
1608 
1609     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1610   }
1611 
1612   case LOLR_StringTemplate: {
1613     TemplateArgumentListInfo ExplicitArgs;
1614 
1615     unsigned CharBits = Context.getIntWidth(CharTy);
1616     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1617     llvm::APSInt Value(CharBits, CharIsUnsigned);
1618 
1619     TemplateArgument TypeArg(CharTy);
1620     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1621     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1622 
1623     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1624       Value = Lit->getCodeUnit(I);
1625       TemplateArgument Arg(Context, Value, CharTy);
1626       TemplateArgumentLocInfo ArgInfo;
1627       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1628     }
1629     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1630                                     &ExplicitArgs);
1631   }
1632   case LOLR_Raw:
1633   case LOLR_Template:
1634   case LOLR_ErrorNoDiagnostic:
1635     llvm_unreachable("unexpected literal operator lookup result");
1636   case LOLR_Error:
1637     return ExprError();
1638   }
1639   llvm_unreachable("unexpected literal operator lookup result");
1640 }
1641 
1642 ExprResult
1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1644                        SourceLocation Loc,
1645                        const CXXScopeSpec *SS) {
1646   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1647   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1648 }
1649 
1650 /// BuildDeclRefExpr - Build an expression that references a
1651 /// declaration that does not require a closure capture.
1652 ExprResult
1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1654                        const DeclarationNameInfo &NameInfo,
1655                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1656                        const TemplateArgumentListInfo *TemplateArgs) {
1657   bool RefersToCapturedVariable =
1658       isa<VarDecl>(D) &&
1659       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1660 
1661   DeclRefExpr *E;
1662   if (isa<VarTemplateSpecializationDecl>(D)) {
1663     VarTemplateSpecializationDecl *VarSpec =
1664         cast<VarTemplateSpecializationDecl>(D);
1665 
1666     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1667                                         : NestedNameSpecifierLoc(),
1668                             VarSpec->getTemplateKeywordLoc(), D,
1669                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1670                             FoundD, TemplateArgs);
1671   } else {
1672     assert(!TemplateArgs && "No template arguments for non-variable"
1673                             " template specialization references");
1674     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1675                                         : NestedNameSpecifierLoc(),
1676                             SourceLocation(), D, RefersToCapturedVariable,
1677                             NameInfo, Ty, VK, FoundD);
1678   }
1679 
1680   MarkDeclRefReferenced(E);
1681 
1682   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1683       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1684       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1685     getCurFunction()->recordUseOfWeak(E);
1686 
1687   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1688   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1689     FD = IFD->getAnonField();
1690   if (FD) {
1691     UnusedPrivateFields.remove(FD);
1692     // Just in case we're building an illegal pointer-to-member.
1693     if (FD->isBitField())
1694       E->setObjectKind(OK_BitField);
1695   }
1696 
1697   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1698   // designates a bit-field.
1699   if (auto *BD = dyn_cast<BindingDecl>(D))
1700     if (auto *BE = BD->getBinding())
1701       E->setObjectKind(BE->getObjectKind());
1702 
1703   return E;
1704 }
1705 
1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1707 /// possibly a list of template arguments.
1708 ///
1709 /// If this produces template arguments, it is permitted to call
1710 /// DecomposeTemplateName.
1711 ///
1712 /// This actually loses a lot of source location information for
1713 /// non-standard name kinds; we should consider preserving that in
1714 /// some way.
1715 void
1716 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1717                              TemplateArgumentListInfo &Buffer,
1718                              DeclarationNameInfo &NameInfo,
1719                              const TemplateArgumentListInfo *&TemplateArgs) {
1720   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1721     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1722     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1723 
1724     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1725                                        Id.TemplateId->NumArgs);
1726     translateTemplateArguments(TemplateArgsPtr, Buffer);
1727 
1728     TemplateName TName = Id.TemplateId->Template.get();
1729     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1730     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1731     TemplateArgs = &Buffer;
1732   } else {
1733     NameInfo = GetNameFromUnqualifiedId(Id);
1734     TemplateArgs = nullptr;
1735   }
1736 }
1737 
1738 static void emitEmptyLookupTypoDiagnostic(
1739     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1740     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1741     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1742   DeclContext *Ctx =
1743       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1744   if (!TC) {
1745     // Emit a special diagnostic for failed member lookups.
1746     // FIXME: computing the declaration context might fail here (?)
1747     if (Ctx)
1748       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1749                                                  << SS.getRange();
1750     else
1751       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1752     return;
1753   }
1754 
1755   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1756   bool DroppedSpecifier =
1757       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1758   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1759                         ? diag::note_implicit_param_decl
1760                         : diag::note_previous_decl;
1761   if (!Ctx)
1762     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1763                          SemaRef.PDiag(NoteID));
1764   else
1765     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1766                                  << Typo << Ctx << DroppedSpecifier
1767                                  << SS.getRange(),
1768                          SemaRef.PDiag(NoteID));
1769 }
1770 
1771 /// Diagnose an empty lookup.
1772 ///
1773 /// \return false if new lookup candidates were found
1774 bool
1775 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1776                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1777                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1778                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1779   DeclarationName Name = R.getLookupName();
1780 
1781   unsigned diagnostic = diag::err_undeclared_var_use;
1782   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1783   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1784       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1785       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1786     diagnostic = diag::err_undeclared_use;
1787     diagnostic_suggest = diag::err_undeclared_use_suggest;
1788   }
1789 
1790   // If the original lookup was an unqualified lookup, fake an
1791   // unqualified lookup.  This is useful when (for example) the
1792   // original lookup would not have found something because it was a
1793   // dependent name.
1794   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1795   while (DC) {
1796     if (isa<CXXRecordDecl>(DC)) {
1797       LookupQualifiedName(R, DC);
1798 
1799       if (!R.empty()) {
1800         // Don't give errors about ambiguities in this lookup.
1801         R.suppressDiagnostics();
1802 
1803         // During a default argument instantiation the CurContext points
1804         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1805         // function parameter list, hence add an explicit check.
1806         bool isDefaultArgument =
1807             !CodeSynthesisContexts.empty() &&
1808             CodeSynthesisContexts.back().Kind ==
1809                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1810         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1811         bool isInstance = CurMethod &&
1812                           CurMethod->isInstance() &&
1813                           DC == CurMethod->getParent() && !isDefaultArgument;
1814 
1815         // Give a code modification hint to insert 'this->'.
1816         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1817         // Actually quite difficult!
1818         if (getLangOpts().MSVCCompat)
1819           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1820         if (isInstance) {
1821           Diag(R.getNameLoc(), diagnostic) << Name
1822             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1823           CheckCXXThisCapture(R.getNameLoc());
1824         } else {
1825           Diag(R.getNameLoc(), diagnostic) << Name;
1826         }
1827 
1828         // Do we really want to note all of these?
1829         for (NamedDecl *D : R)
1830           Diag(D->getLocation(), diag::note_dependent_var_use);
1831 
1832         // Return true if we are inside a default argument instantiation
1833         // and the found name refers to an instance member function, otherwise
1834         // the function calling DiagnoseEmptyLookup will try to create an
1835         // implicit member call and this is wrong for default argument.
1836         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1837           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1838           return true;
1839         }
1840 
1841         // Tell the callee to try to recover.
1842         return false;
1843       }
1844 
1845       R.clear();
1846     }
1847 
1848     // In Microsoft mode, if we are performing lookup from within a friend
1849     // function definition declared at class scope then we must set
1850     // DC to the lexical parent to be able to search into the parent
1851     // class.
1852     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1853         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1854         DC->getLexicalParent()->isRecord())
1855       DC = DC->getLexicalParent();
1856     else
1857       DC = DC->getParent();
1858   }
1859 
1860   // We didn't find anything, so try to correct for a typo.
1861   TypoCorrection Corrected;
1862   if (S && Out) {
1863     SourceLocation TypoLoc = R.getNameLoc();
1864     assert(!ExplicitTemplateArgs &&
1865            "Diagnosing an empty lookup with explicit template args!");
1866     *Out = CorrectTypoDelayed(
1867         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1868         [=](const TypoCorrection &TC) {
1869           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1870                                         diagnostic, diagnostic_suggest);
1871         },
1872         nullptr, CTK_ErrorRecovery);
1873     if (*Out)
1874       return true;
1875   } else if (S && (Corrected =
1876                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1877                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1878     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1879     bool DroppedSpecifier =
1880         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1881     R.setLookupName(Corrected.getCorrection());
1882 
1883     bool AcceptableWithRecovery = false;
1884     bool AcceptableWithoutRecovery = false;
1885     NamedDecl *ND = Corrected.getFoundDecl();
1886     if (ND) {
1887       if (Corrected.isOverloaded()) {
1888         OverloadCandidateSet OCS(R.getNameLoc(),
1889                                  OverloadCandidateSet::CSK_Normal);
1890         OverloadCandidateSet::iterator Best;
1891         for (NamedDecl *CD : Corrected) {
1892           if (FunctionTemplateDecl *FTD =
1893                    dyn_cast<FunctionTemplateDecl>(CD))
1894             AddTemplateOverloadCandidate(
1895                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1896                 Args, OCS);
1897           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1898             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1899               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1900                                    Args, OCS);
1901         }
1902         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1903         case OR_Success:
1904           ND = Best->FoundDecl;
1905           Corrected.setCorrectionDecl(ND);
1906           break;
1907         default:
1908           // FIXME: Arbitrarily pick the first declaration for the note.
1909           Corrected.setCorrectionDecl(ND);
1910           break;
1911         }
1912       }
1913       R.addDecl(ND);
1914       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1915         CXXRecordDecl *Record = nullptr;
1916         if (Corrected.getCorrectionSpecifier()) {
1917           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1918           Record = Ty->getAsCXXRecordDecl();
1919         }
1920         if (!Record)
1921           Record = cast<CXXRecordDecl>(
1922               ND->getDeclContext()->getRedeclContext());
1923         R.setNamingClass(Record);
1924       }
1925 
1926       auto *UnderlyingND = ND->getUnderlyingDecl();
1927       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1928                                isa<FunctionTemplateDecl>(UnderlyingND);
1929       // FIXME: If we ended up with a typo for a type name or
1930       // Objective-C class name, we're in trouble because the parser
1931       // is in the wrong place to recover. Suggest the typo
1932       // correction, but don't make it a fix-it since we're not going
1933       // to recover well anyway.
1934       AcceptableWithoutRecovery =
1935           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1936     } else {
1937       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1938       // because we aren't able to recover.
1939       AcceptableWithoutRecovery = true;
1940     }
1941 
1942     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1943       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1944                             ? diag::note_implicit_param_decl
1945                             : diag::note_previous_decl;
1946       if (SS.isEmpty())
1947         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1948                      PDiag(NoteID), AcceptableWithRecovery);
1949       else
1950         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1951                                   << Name << computeDeclContext(SS, false)
1952                                   << DroppedSpecifier << SS.getRange(),
1953                      PDiag(NoteID), AcceptableWithRecovery);
1954 
1955       // Tell the callee whether to try to recover.
1956       return !AcceptableWithRecovery;
1957     }
1958   }
1959   R.clear();
1960 
1961   // Emit a special diagnostic for failed member lookups.
1962   // FIXME: computing the declaration context might fail here (?)
1963   if (!SS.isEmpty()) {
1964     Diag(R.getNameLoc(), diag::err_no_member)
1965       << Name << computeDeclContext(SS, false)
1966       << SS.getRange();
1967     return true;
1968   }
1969 
1970   // Give up, we can't recover.
1971   Diag(R.getNameLoc(), diagnostic) << Name;
1972   return true;
1973 }
1974 
1975 /// In Microsoft mode, if we are inside a template class whose parent class has
1976 /// dependent base classes, and we can't resolve an unqualified identifier, then
1977 /// assume the identifier is a member of a dependent base class.  We can only
1978 /// recover successfully in static methods, instance methods, and other contexts
1979 /// where 'this' is available.  This doesn't precisely match MSVC's
1980 /// instantiation model, but it's close enough.
1981 static Expr *
1982 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1983                                DeclarationNameInfo &NameInfo,
1984                                SourceLocation TemplateKWLoc,
1985                                const TemplateArgumentListInfo *TemplateArgs) {
1986   // Only try to recover from lookup into dependent bases in static methods or
1987   // contexts where 'this' is available.
1988   QualType ThisType = S.getCurrentThisType();
1989   const CXXRecordDecl *RD = nullptr;
1990   if (!ThisType.isNull())
1991     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1992   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1993     RD = MD->getParent();
1994   if (!RD || !RD->hasAnyDependentBases())
1995     return nullptr;
1996 
1997   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1998   // is available, suggest inserting 'this->' as a fixit.
1999   SourceLocation Loc = NameInfo.getLoc();
2000   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2001   DB << NameInfo.getName() << RD;
2002 
2003   if (!ThisType.isNull()) {
2004     DB << FixItHint::CreateInsertion(Loc, "this->");
2005     return CXXDependentScopeMemberExpr::Create(
2006         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2007         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2008         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2009   }
2010 
2011   // Synthesize a fake NNS that points to the derived class.  This will
2012   // perform name lookup during template instantiation.
2013   CXXScopeSpec SS;
2014   auto *NNS =
2015       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2016   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2017   return DependentScopeDeclRefExpr::Create(
2018       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2019       TemplateArgs);
2020 }
2021 
2022 ExprResult
2023 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2024                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2025                         bool HasTrailingLParen, bool IsAddressOfOperand,
2026                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2027                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2028   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2029          "cannot be direct & operand and have a trailing lparen");
2030   if (SS.isInvalid())
2031     return ExprError();
2032 
2033   TemplateArgumentListInfo TemplateArgsBuffer;
2034 
2035   // Decompose the UnqualifiedId into the following data.
2036   DeclarationNameInfo NameInfo;
2037   const TemplateArgumentListInfo *TemplateArgs;
2038   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2039 
2040   DeclarationName Name = NameInfo.getName();
2041   IdentifierInfo *II = Name.getAsIdentifierInfo();
2042   SourceLocation NameLoc = NameInfo.getLoc();
2043 
2044   if (II && II->isEditorPlaceholder()) {
2045     // FIXME: When typed placeholders are supported we can create a typed
2046     // placeholder expression node.
2047     return ExprError();
2048   }
2049 
2050   // C++ [temp.dep.expr]p3:
2051   //   An id-expression is type-dependent if it contains:
2052   //     -- an identifier that was declared with a dependent type,
2053   //        (note: handled after lookup)
2054   //     -- a template-id that is dependent,
2055   //        (note: handled in BuildTemplateIdExpr)
2056   //     -- a conversion-function-id that specifies a dependent type,
2057   //     -- a nested-name-specifier that contains a class-name that
2058   //        names a dependent type.
2059   // Determine whether this is a member of an unknown specialization;
2060   // we need to handle these differently.
2061   bool DependentID = false;
2062   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2063       Name.getCXXNameType()->isDependentType()) {
2064     DependentID = true;
2065   } else if (SS.isSet()) {
2066     if (DeclContext *DC = computeDeclContext(SS, false)) {
2067       if (RequireCompleteDeclContext(SS, DC))
2068         return ExprError();
2069     } else {
2070       DependentID = true;
2071     }
2072   }
2073 
2074   if (DependentID)
2075     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2076                                       IsAddressOfOperand, TemplateArgs);
2077 
2078   // Perform the required lookup.
2079   LookupResult R(*this, NameInfo,
2080                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2081                      ? LookupObjCImplicitSelfParam
2082                      : LookupOrdinaryName);
2083   if (TemplateKWLoc.isValid() || TemplateArgs) {
2084     // Lookup the template name again to correctly establish the context in
2085     // which it was found. This is really unfortunate as we already did the
2086     // lookup to determine that it was a template name in the first place. If
2087     // this becomes a performance hit, we can work harder to preserve those
2088     // results until we get here but it's likely not worth it.
2089     bool MemberOfUnknownSpecialization;
2090     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2091                            MemberOfUnknownSpecialization, TemplateKWLoc))
2092       return ExprError();
2093 
2094     if (MemberOfUnknownSpecialization ||
2095         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2096       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2097                                         IsAddressOfOperand, TemplateArgs);
2098   } else {
2099     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2100     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2101 
2102     // If the result might be in a dependent base class, this is a dependent
2103     // id-expression.
2104     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2105       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2106                                         IsAddressOfOperand, TemplateArgs);
2107 
2108     // If this reference is in an Objective-C method, then we need to do
2109     // some special Objective-C lookup, too.
2110     if (IvarLookupFollowUp) {
2111       ExprResult E(LookupInObjCMethod(R, S, II, true));
2112       if (E.isInvalid())
2113         return ExprError();
2114 
2115       if (Expr *Ex = E.getAs<Expr>())
2116         return Ex;
2117     }
2118   }
2119 
2120   if (R.isAmbiguous())
2121     return ExprError();
2122 
2123   // This could be an implicitly declared function reference (legal in C90,
2124   // extension in C99, forbidden in C++).
2125   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2126     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2127     if (D) R.addDecl(D);
2128   }
2129 
2130   // Determine whether this name might be a candidate for
2131   // argument-dependent lookup.
2132   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2133 
2134   if (R.empty() && !ADL) {
2135     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2136       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2137                                                    TemplateKWLoc, TemplateArgs))
2138         return E;
2139     }
2140 
2141     // Don't diagnose an empty lookup for inline assembly.
2142     if (IsInlineAsmIdentifier)
2143       return ExprError();
2144 
2145     // If this name wasn't predeclared and if this is not a function
2146     // call, diagnose the problem.
2147     TypoExpr *TE = nullptr;
2148     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2149         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2150     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2151     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2152            "Typo correction callback misconfigured");
2153     if (CCC) {
2154       // Make sure the callback knows what the typo being diagnosed is.
2155       CCC->setTypoName(II);
2156       if (SS.isValid())
2157         CCC->setTypoNNS(SS.getScopeRep());
2158     }
2159     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2160     // a template name, but we happen to have always already looked up the name
2161     // before we get here if it must be a template name.
2162     if (DiagnoseEmptyLookup(S, SS, R,
2163                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2164                             nullptr, None, &TE)) {
2165       if (TE && KeywordReplacement) {
2166         auto &State = getTypoExprState(TE);
2167         auto BestTC = State.Consumer->getNextCorrection();
2168         if (BestTC.isKeyword()) {
2169           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2170           if (State.DiagHandler)
2171             State.DiagHandler(BestTC);
2172           KeywordReplacement->startToken();
2173           KeywordReplacement->setKind(II->getTokenID());
2174           KeywordReplacement->setIdentifierInfo(II);
2175           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2176           // Clean up the state associated with the TypoExpr, since it has
2177           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2178           clearDelayedTypo(TE);
2179           // Signal that a correction to a keyword was performed by returning a
2180           // valid-but-null ExprResult.
2181           return (Expr*)nullptr;
2182         }
2183         State.Consumer->resetCorrectionStream();
2184       }
2185       return TE ? TE : ExprError();
2186     }
2187 
2188     assert(!R.empty() &&
2189            "DiagnoseEmptyLookup returned false but added no results");
2190 
2191     // If we found an Objective-C instance variable, let
2192     // LookupInObjCMethod build the appropriate expression to
2193     // reference the ivar.
2194     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2195       R.clear();
2196       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2197       // In a hopelessly buggy code, Objective-C instance variable
2198       // lookup fails and no expression will be built to reference it.
2199       if (!E.isInvalid() && !E.get())
2200         return ExprError();
2201       return E;
2202     }
2203   }
2204 
2205   // This is guaranteed from this point on.
2206   assert(!R.empty() || ADL);
2207 
2208   // Check whether this might be a C++ implicit instance member access.
2209   // C++ [class.mfct.non-static]p3:
2210   //   When an id-expression that is not part of a class member access
2211   //   syntax and not used to form a pointer to member is used in the
2212   //   body of a non-static member function of class X, if name lookup
2213   //   resolves the name in the id-expression to a non-static non-type
2214   //   member of some class C, the id-expression is transformed into a
2215   //   class member access expression using (*this) as the
2216   //   postfix-expression to the left of the . operator.
2217   //
2218   // But we don't actually need to do this for '&' operands if R
2219   // resolved to a function or overloaded function set, because the
2220   // expression is ill-formed if it actually works out to be a
2221   // non-static member function:
2222   //
2223   // C++ [expr.ref]p4:
2224   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2225   //   [t]he expression can be used only as the left-hand operand of a
2226   //   member function call.
2227   //
2228   // There are other safeguards against such uses, but it's important
2229   // to get this right here so that we don't end up making a
2230   // spuriously dependent expression if we're inside a dependent
2231   // instance method.
2232   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2233     bool MightBeImplicitMember;
2234     if (!IsAddressOfOperand)
2235       MightBeImplicitMember = true;
2236     else if (!SS.isEmpty())
2237       MightBeImplicitMember = false;
2238     else if (R.isOverloadedResult())
2239       MightBeImplicitMember = false;
2240     else if (R.isUnresolvableResult())
2241       MightBeImplicitMember = true;
2242     else
2243       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2244                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2245                               isa<MSPropertyDecl>(R.getFoundDecl());
2246 
2247     if (MightBeImplicitMember)
2248       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2249                                              R, TemplateArgs, S);
2250   }
2251 
2252   if (TemplateArgs || TemplateKWLoc.isValid()) {
2253 
2254     // In C++1y, if this is a variable template id, then check it
2255     // in BuildTemplateIdExpr().
2256     // The single lookup result must be a variable template declaration.
2257     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2258         Id.TemplateId->Kind == TNK_Var_template) {
2259       assert(R.getAsSingle<VarTemplateDecl>() &&
2260              "There should only be one declaration found.");
2261     }
2262 
2263     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2264   }
2265 
2266   return BuildDeclarationNameExpr(SS, R, ADL);
2267 }
2268 
2269 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2270 /// declaration name, generally during template instantiation.
2271 /// There's a large number of things which don't need to be done along
2272 /// this path.
2273 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2274     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2275     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2276   DeclContext *DC = computeDeclContext(SS, false);
2277   if (!DC)
2278     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2279                                      NameInfo, /*TemplateArgs=*/nullptr);
2280 
2281   if (RequireCompleteDeclContext(SS, DC))
2282     return ExprError();
2283 
2284   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2285   LookupQualifiedName(R, DC);
2286 
2287   if (R.isAmbiguous())
2288     return ExprError();
2289 
2290   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2291     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2292                                      NameInfo, /*TemplateArgs=*/nullptr);
2293 
2294   if (R.empty()) {
2295     Diag(NameInfo.getLoc(), diag::err_no_member)
2296       << NameInfo.getName() << DC << SS.getRange();
2297     return ExprError();
2298   }
2299 
2300   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2301     // Diagnose a missing typename if this resolved unambiguously to a type in
2302     // a dependent context.  If we can recover with a type, downgrade this to
2303     // a warning in Microsoft compatibility mode.
2304     unsigned DiagID = diag::err_typename_missing;
2305     if (RecoveryTSI && getLangOpts().MSVCCompat)
2306       DiagID = diag::ext_typename_missing;
2307     SourceLocation Loc = SS.getBeginLoc();
2308     auto D = Diag(Loc, DiagID);
2309     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2310       << SourceRange(Loc, NameInfo.getEndLoc());
2311 
2312     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2313     // context.
2314     if (!RecoveryTSI)
2315       return ExprError();
2316 
2317     // Only issue the fixit if we're prepared to recover.
2318     D << FixItHint::CreateInsertion(Loc, "typename ");
2319 
2320     // Recover by pretending this was an elaborated type.
2321     QualType Ty = Context.getTypeDeclType(TD);
2322     TypeLocBuilder TLB;
2323     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2324 
2325     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2326     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2327     QTL.setElaboratedKeywordLoc(SourceLocation());
2328     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2329 
2330     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2331 
2332     return ExprEmpty();
2333   }
2334 
2335   // Defend against this resolving to an implicit member access. We usually
2336   // won't get here if this might be a legitimate a class member (we end up in
2337   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2338   // a pointer-to-member or in an unevaluated context in C++11.
2339   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2340     return BuildPossibleImplicitMemberExpr(SS,
2341                                            /*TemplateKWLoc=*/SourceLocation(),
2342                                            R, /*TemplateArgs=*/nullptr, S);
2343 
2344   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2345 }
2346 
2347 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2348 /// detected that we're currently inside an ObjC method.  Perform some
2349 /// additional lookup.
2350 ///
2351 /// Ideally, most of this would be done by lookup, but there's
2352 /// actually quite a lot of extra work involved.
2353 ///
2354 /// Returns a null sentinel to indicate trivial success.
2355 ExprResult
2356 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2357                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2358   SourceLocation Loc = Lookup.getNameLoc();
2359   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2360 
2361   // Check for error condition which is already reported.
2362   if (!CurMethod)
2363     return ExprError();
2364 
2365   // There are two cases to handle here.  1) scoped lookup could have failed,
2366   // in which case we should look for an ivar.  2) scoped lookup could have
2367   // found a decl, but that decl is outside the current instance method (i.e.
2368   // a global variable).  In these two cases, we do a lookup for an ivar with
2369   // this name, if the lookup sucedes, we replace it our current decl.
2370 
2371   // If we're in a class method, we don't normally want to look for
2372   // ivars.  But if we don't find anything else, and there's an
2373   // ivar, that's an error.
2374   bool IsClassMethod = CurMethod->isClassMethod();
2375 
2376   bool LookForIvars;
2377   if (Lookup.empty())
2378     LookForIvars = true;
2379   else if (IsClassMethod)
2380     LookForIvars = false;
2381   else
2382     LookForIvars = (Lookup.isSingleResult() &&
2383                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2384   ObjCInterfaceDecl *IFace = nullptr;
2385   if (LookForIvars) {
2386     IFace = CurMethod->getClassInterface();
2387     ObjCInterfaceDecl *ClassDeclared;
2388     ObjCIvarDecl *IV = nullptr;
2389     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2390       // Diagnose using an ivar in a class method.
2391       if (IsClassMethod)
2392         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2393                          << IV->getDeclName());
2394 
2395       // If we're referencing an invalid decl, just return this as a silent
2396       // error node.  The error diagnostic was already emitted on the decl.
2397       if (IV->isInvalidDecl())
2398         return ExprError();
2399 
2400       // Check if referencing a field with __attribute__((deprecated)).
2401       if (DiagnoseUseOfDecl(IV, Loc))
2402         return ExprError();
2403 
2404       // Diagnose the use of an ivar outside of the declaring class.
2405       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2406           !declaresSameEntity(ClassDeclared, IFace) &&
2407           !getLangOpts().DebuggerSupport)
2408         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2409 
2410       // FIXME: This should use a new expr for a direct reference, don't
2411       // turn this into Self->ivar, just return a BareIVarExpr or something.
2412       IdentifierInfo &II = Context.Idents.get("self");
2413       UnqualifiedId SelfName;
2414       SelfName.setIdentifier(&II, SourceLocation());
2415       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2416       CXXScopeSpec SelfScopeSpec;
2417       SourceLocation TemplateKWLoc;
2418       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2419                                               SelfName, false, false);
2420       if (SelfExpr.isInvalid())
2421         return ExprError();
2422 
2423       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2424       if (SelfExpr.isInvalid())
2425         return ExprError();
2426 
2427       MarkAnyDeclReferenced(Loc, IV, true);
2428 
2429       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2430       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2431           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2432         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2433 
2434       ObjCIvarRefExpr *Result = new (Context)
2435           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2436                           IV->getLocation(), SelfExpr.get(), true, true);
2437 
2438       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2439         if (!isUnevaluatedContext() &&
2440             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2441           getCurFunction()->recordUseOfWeak(Result);
2442       }
2443       if (getLangOpts().ObjCAutoRefCount) {
2444         if (CurContext->isClosure())
2445           Diag(Loc, diag::warn_implicitly_retains_self)
2446             << FixItHint::CreateInsertion(Loc, "self->");
2447       }
2448 
2449       return Result;
2450     }
2451   } else if (CurMethod->isInstanceMethod()) {
2452     // We should warn if a local variable hides an ivar.
2453     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2454       ObjCInterfaceDecl *ClassDeclared;
2455       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2456         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2457             declaresSameEntity(IFace, ClassDeclared))
2458           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2459       }
2460     }
2461   } else if (Lookup.isSingleResult() &&
2462              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2463     // If accessing a stand-alone ivar in a class method, this is an error.
2464     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2465       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2466                        << IV->getDeclName());
2467   }
2468 
2469   if (Lookup.empty() && II && AllowBuiltinCreation) {
2470     // FIXME. Consolidate this with similar code in LookupName.
2471     if (unsigned BuiltinID = II->getBuiltinID()) {
2472       if (!(getLangOpts().CPlusPlus &&
2473             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2474         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2475                                            S, Lookup.isForRedeclaration(),
2476                                            Lookup.getNameLoc());
2477         if (D) Lookup.addDecl(D);
2478       }
2479     }
2480   }
2481   // Sentinel value saying that we didn't do anything special.
2482   return ExprResult((Expr *)nullptr);
2483 }
2484 
2485 /// Cast a base object to a member's actual type.
2486 ///
2487 /// Logically this happens in three phases:
2488 ///
2489 /// * First we cast from the base type to the naming class.
2490 ///   The naming class is the class into which we were looking
2491 ///   when we found the member;  it's the qualifier type if a
2492 ///   qualifier was provided, and otherwise it's the base type.
2493 ///
2494 /// * Next we cast from the naming class to the declaring class.
2495 ///   If the member we found was brought into a class's scope by
2496 ///   a using declaration, this is that class;  otherwise it's
2497 ///   the class declaring the member.
2498 ///
2499 /// * Finally we cast from the declaring class to the "true"
2500 ///   declaring class of the member.  This conversion does not
2501 ///   obey access control.
2502 ExprResult
2503 Sema::PerformObjectMemberConversion(Expr *From,
2504                                     NestedNameSpecifier *Qualifier,
2505                                     NamedDecl *FoundDecl,
2506                                     NamedDecl *Member) {
2507   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2508   if (!RD)
2509     return From;
2510 
2511   QualType DestRecordType;
2512   QualType DestType;
2513   QualType FromRecordType;
2514   QualType FromType = From->getType();
2515   bool PointerConversions = false;
2516   if (isa<FieldDecl>(Member)) {
2517     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2518 
2519     if (FromType->getAs<PointerType>()) {
2520       DestType = Context.getPointerType(DestRecordType);
2521       FromRecordType = FromType->getPointeeType();
2522       PointerConversions = true;
2523     } else {
2524       DestType = DestRecordType;
2525       FromRecordType = FromType;
2526     }
2527   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2528     if (Method->isStatic())
2529       return From;
2530 
2531     DestType = Method->getThisType(Context);
2532     DestRecordType = DestType->getPointeeType();
2533 
2534     if (FromType->getAs<PointerType>()) {
2535       FromRecordType = FromType->getPointeeType();
2536       PointerConversions = true;
2537     } else {
2538       FromRecordType = FromType;
2539       DestType = DestRecordType;
2540     }
2541   } else {
2542     // No conversion necessary.
2543     return From;
2544   }
2545 
2546   if (DestType->isDependentType() || FromType->isDependentType())
2547     return From;
2548 
2549   // If the unqualified types are the same, no conversion is necessary.
2550   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2551     return From;
2552 
2553   SourceRange FromRange = From->getSourceRange();
2554   SourceLocation FromLoc = FromRange.getBegin();
2555 
2556   ExprValueKind VK = From->getValueKind();
2557 
2558   // C++ [class.member.lookup]p8:
2559   //   [...] Ambiguities can often be resolved by qualifying a name with its
2560   //   class name.
2561   //
2562   // If the member was a qualified name and the qualified referred to a
2563   // specific base subobject type, we'll cast to that intermediate type
2564   // first and then to the object in which the member is declared. That allows
2565   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2566   //
2567   //   class Base { public: int x; };
2568   //   class Derived1 : public Base { };
2569   //   class Derived2 : public Base { };
2570   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2571   //
2572   //   void VeryDerived::f() {
2573   //     x = 17; // error: ambiguous base subobjects
2574   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2575   //   }
2576   if (Qualifier && Qualifier->getAsType()) {
2577     QualType QType = QualType(Qualifier->getAsType(), 0);
2578     assert(QType->isRecordType() && "lookup done with non-record type");
2579 
2580     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2581 
2582     // In C++98, the qualifier type doesn't actually have to be a base
2583     // type of the object type, in which case we just ignore it.
2584     // Otherwise build the appropriate casts.
2585     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2586       CXXCastPath BasePath;
2587       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2588                                        FromLoc, FromRange, &BasePath))
2589         return ExprError();
2590 
2591       if (PointerConversions)
2592         QType = Context.getPointerType(QType);
2593       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2594                                VK, &BasePath).get();
2595 
2596       FromType = QType;
2597       FromRecordType = QRecordType;
2598 
2599       // If the qualifier type was the same as the destination type,
2600       // we're done.
2601       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2602         return From;
2603     }
2604   }
2605 
2606   bool IgnoreAccess = false;
2607 
2608   // If we actually found the member through a using declaration, cast
2609   // down to the using declaration's type.
2610   //
2611   // Pointer equality is fine here because only one declaration of a
2612   // class ever has member declarations.
2613   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2614     assert(isa<UsingShadowDecl>(FoundDecl));
2615     QualType URecordType = Context.getTypeDeclType(
2616                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2617 
2618     // We only need to do this if the naming-class to declaring-class
2619     // conversion is non-trivial.
2620     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2621       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2622       CXXCastPath BasePath;
2623       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2624                                        FromLoc, FromRange, &BasePath))
2625         return ExprError();
2626 
2627       QualType UType = URecordType;
2628       if (PointerConversions)
2629         UType = Context.getPointerType(UType);
2630       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2631                                VK, &BasePath).get();
2632       FromType = UType;
2633       FromRecordType = URecordType;
2634     }
2635 
2636     // We don't do access control for the conversion from the
2637     // declaring class to the true declaring class.
2638     IgnoreAccess = true;
2639   }
2640 
2641   CXXCastPath BasePath;
2642   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2643                                    FromLoc, FromRange, &BasePath,
2644                                    IgnoreAccess))
2645     return ExprError();
2646 
2647   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2648                            VK, &BasePath);
2649 }
2650 
2651 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2652                                       const LookupResult &R,
2653                                       bool HasTrailingLParen) {
2654   // Only when used directly as the postfix-expression of a call.
2655   if (!HasTrailingLParen)
2656     return false;
2657 
2658   // Never if a scope specifier was provided.
2659   if (SS.isSet())
2660     return false;
2661 
2662   // Only in C++ or ObjC++.
2663   if (!getLangOpts().CPlusPlus)
2664     return false;
2665 
2666   // Turn off ADL when we find certain kinds of declarations during
2667   // normal lookup:
2668   for (NamedDecl *D : R) {
2669     // C++0x [basic.lookup.argdep]p3:
2670     //     -- a declaration of a class member
2671     // Since using decls preserve this property, we check this on the
2672     // original decl.
2673     if (D->isCXXClassMember())
2674       return false;
2675 
2676     // C++0x [basic.lookup.argdep]p3:
2677     //     -- a block-scope function declaration that is not a
2678     //        using-declaration
2679     // NOTE: we also trigger this for function templates (in fact, we
2680     // don't check the decl type at all, since all other decl types
2681     // turn off ADL anyway).
2682     if (isa<UsingShadowDecl>(D))
2683       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2684     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2685       return false;
2686 
2687     // C++0x [basic.lookup.argdep]p3:
2688     //     -- a declaration that is neither a function or a function
2689     //        template
2690     // And also for builtin functions.
2691     if (isa<FunctionDecl>(D)) {
2692       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2693 
2694       // But also builtin functions.
2695       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2696         return false;
2697     } else if (!isa<FunctionTemplateDecl>(D))
2698       return false;
2699   }
2700 
2701   return true;
2702 }
2703 
2704 
2705 /// Diagnoses obvious problems with the use of the given declaration
2706 /// as an expression.  This is only actually called for lookups that
2707 /// were not overloaded, and it doesn't promise that the declaration
2708 /// will in fact be used.
2709 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2710   if (D->isInvalidDecl())
2711     return true;
2712 
2713   if (isa<TypedefNameDecl>(D)) {
2714     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2715     return true;
2716   }
2717 
2718   if (isa<ObjCInterfaceDecl>(D)) {
2719     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2720     return true;
2721   }
2722 
2723   if (isa<NamespaceDecl>(D)) {
2724     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2725     return true;
2726   }
2727 
2728   return false;
2729 }
2730 
2731 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2732                                           LookupResult &R, bool NeedsADL,
2733                                           bool AcceptInvalidDecl) {
2734   // If this is a single, fully-resolved result and we don't need ADL,
2735   // just build an ordinary singleton decl ref.
2736   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2737     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2738                                     R.getRepresentativeDecl(), nullptr,
2739                                     AcceptInvalidDecl);
2740 
2741   // We only need to check the declaration if there's exactly one
2742   // result, because in the overloaded case the results can only be
2743   // functions and function templates.
2744   if (R.isSingleResult() &&
2745       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2746     return ExprError();
2747 
2748   // Otherwise, just build an unresolved lookup expression.  Suppress
2749   // any lookup-related diagnostics; we'll hash these out later, when
2750   // we've picked a target.
2751   R.suppressDiagnostics();
2752 
2753   UnresolvedLookupExpr *ULE
2754     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2755                                    SS.getWithLocInContext(Context),
2756                                    R.getLookupNameInfo(),
2757                                    NeedsADL, R.isOverloadedResult(),
2758                                    R.begin(), R.end());
2759 
2760   return ULE;
2761 }
2762 
2763 static void
2764 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2765                                    ValueDecl *var, DeclContext *DC);
2766 
2767 /// Complete semantic analysis for a reference to the given declaration.
2768 ExprResult Sema::BuildDeclarationNameExpr(
2769     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2770     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2771     bool AcceptInvalidDecl) {
2772   assert(D && "Cannot refer to a NULL declaration");
2773   assert(!isa<FunctionTemplateDecl>(D) &&
2774          "Cannot refer unambiguously to a function template");
2775 
2776   SourceLocation Loc = NameInfo.getLoc();
2777   if (CheckDeclInExpr(*this, Loc, D))
2778     return ExprError();
2779 
2780   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2781     // Specifically diagnose references to class templates that are missing
2782     // a template argument list.
2783     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2784     return ExprError();
2785   }
2786 
2787   // Make sure that we're referring to a value.
2788   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2789   if (!VD) {
2790     Diag(Loc, diag::err_ref_non_value)
2791       << D << SS.getRange();
2792     Diag(D->getLocation(), diag::note_declared_at);
2793     return ExprError();
2794   }
2795 
2796   // Check whether this declaration can be used. Note that we suppress
2797   // this check when we're going to perform argument-dependent lookup
2798   // on this function name, because this might not be the function
2799   // that overload resolution actually selects.
2800   if (DiagnoseUseOfDecl(VD, Loc))
2801     return ExprError();
2802 
2803   // Only create DeclRefExpr's for valid Decl's.
2804   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2805     return ExprError();
2806 
2807   // Handle members of anonymous structs and unions.  If we got here,
2808   // and the reference is to a class member indirect field, then this
2809   // must be the subject of a pointer-to-member expression.
2810   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2811     if (!indirectField->isCXXClassMember())
2812       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2813                                                       indirectField);
2814 
2815   {
2816     QualType type = VD->getType();
2817     if (type.isNull())
2818       return ExprError();
2819     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2820       // C++ [except.spec]p17:
2821       //   An exception-specification is considered to be needed when:
2822       //   - in an expression, the function is the unique lookup result or
2823       //     the selected member of a set of overloaded functions.
2824       ResolveExceptionSpec(Loc, FPT);
2825       type = VD->getType();
2826     }
2827     ExprValueKind valueKind = VK_RValue;
2828 
2829     switch (D->getKind()) {
2830     // Ignore all the non-ValueDecl kinds.
2831 #define ABSTRACT_DECL(kind)
2832 #define VALUE(type, base)
2833 #define DECL(type, base) \
2834     case Decl::type:
2835 #include "clang/AST/DeclNodes.inc"
2836       llvm_unreachable("invalid value decl kind");
2837 
2838     // These shouldn't make it here.
2839     case Decl::ObjCAtDefsField:
2840     case Decl::ObjCIvar:
2841       llvm_unreachable("forming non-member reference to ivar?");
2842 
2843     // Enum constants are always r-values and never references.
2844     // Unresolved using declarations are dependent.
2845     case Decl::EnumConstant:
2846     case Decl::UnresolvedUsingValue:
2847     case Decl::OMPDeclareReduction:
2848       valueKind = VK_RValue;
2849       break;
2850 
2851     // Fields and indirect fields that got here must be for
2852     // pointer-to-member expressions; we just call them l-values for
2853     // internal consistency, because this subexpression doesn't really
2854     // exist in the high-level semantics.
2855     case Decl::Field:
2856     case Decl::IndirectField:
2857       assert(getLangOpts().CPlusPlus &&
2858              "building reference to field in C?");
2859 
2860       // These can't have reference type in well-formed programs, but
2861       // for internal consistency we do this anyway.
2862       type = type.getNonReferenceType();
2863       valueKind = VK_LValue;
2864       break;
2865 
2866     // Non-type template parameters are either l-values or r-values
2867     // depending on the type.
2868     case Decl::NonTypeTemplateParm: {
2869       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2870         type = reftype->getPointeeType();
2871         valueKind = VK_LValue; // even if the parameter is an r-value reference
2872         break;
2873       }
2874 
2875       // For non-references, we need to strip qualifiers just in case
2876       // the template parameter was declared as 'const int' or whatever.
2877       valueKind = VK_RValue;
2878       type = type.getUnqualifiedType();
2879       break;
2880     }
2881 
2882     case Decl::Var:
2883     case Decl::VarTemplateSpecialization:
2884     case Decl::VarTemplatePartialSpecialization:
2885     case Decl::Decomposition:
2886     case Decl::OMPCapturedExpr:
2887       // In C, "extern void blah;" is valid and is an r-value.
2888       if (!getLangOpts().CPlusPlus &&
2889           !type.hasQualifiers() &&
2890           type->isVoidType()) {
2891         valueKind = VK_RValue;
2892         break;
2893       }
2894       LLVM_FALLTHROUGH;
2895 
2896     case Decl::ImplicitParam:
2897     case Decl::ParmVar: {
2898       // These are always l-values.
2899       valueKind = VK_LValue;
2900       type = type.getNonReferenceType();
2901 
2902       // FIXME: Does the addition of const really only apply in
2903       // potentially-evaluated contexts? Since the variable isn't actually
2904       // captured in an unevaluated context, it seems that the answer is no.
2905       if (!isUnevaluatedContext()) {
2906         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2907         if (!CapturedType.isNull())
2908           type = CapturedType;
2909       }
2910 
2911       break;
2912     }
2913 
2914     case Decl::Binding: {
2915       // These are always lvalues.
2916       valueKind = VK_LValue;
2917       type = type.getNonReferenceType();
2918       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2919       // decides how that's supposed to work.
2920       auto *BD = cast<BindingDecl>(VD);
2921       if (BD->getDeclContext()->isFunctionOrMethod() &&
2922           BD->getDeclContext() != CurContext)
2923         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2924       break;
2925     }
2926 
2927     case Decl::Function: {
2928       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2929         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2930           type = Context.BuiltinFnTy;
2931           valueKind = VK_RValue;
2932           break;
2933         }
2934       }
2935 
2936       const FunctionType *fty = type->castAs<FunctionType>();
2937 
2938       // If we're referring to a function with an __unknown_anytype
2939       // result type, make the entire expression __unknown_anytype.
2940       if (fty->getReturnType() == Context.UnknownAnyTy) {
2941         type = Context.UnknownAnyTy;
2942         valueKind = VK_RValue;
2943         break;
2944       }
2945 
2946       // Functions are l-values in C++.
2947       if (getLangOpts().CPlusPlus) {
2948         valueKind = VK_LValue;
2949         break;
2950       }
2951 
2952       // C99 DR 316 says that, if a function type comes from a
2953       // function definition (without a prototype), that type is only
2954       // used for checking compatibility. Therefore, when referencing
2955       // the function, we pretend that we don't have the full function
2956       // type.
2957       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2958           isa<FunctionProtoType>(fty))
2959         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2960                                               fty->getExtInfo());
2961 
2962       // Functions are r-values in C.
2963       valueKind = VK_RValue;
2964       break;
2965     }
2966 
2967     case Decl::CXXDeductionGuide:
2968       llvm_unreachable("building reference to deduction guide");
2969 
2970     case Decl::MSProperty:
2971       valueKind = VK_LValue;
2972       break;
2973 
2974     case Decl::CXXMethod:
2975       // If we're referring to a method with an __unknown_anytype
2976       // result type, make the entire expression __unknown_anytype.
2977       // This should only be possible with a type written directly.
2978       if (const FunctionProtoType *proto
2979             = dyn_cast<FunctionProtoType>(VD->getType()))
2980         if (proto->getReturnType() == Context.UnknownAnyTy) {
2981           type = Context.UnknownAnyTy;
2982           valueKind = VK_RValue;
2983           break;
2984         }
2985 
2986       // C++ methods are l-values if static, r-values if non-static.
2987       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2988         valueKind = VK_LValue;
2989         break;
2990       }
2991       LLVM_FALLTHROUGH;
2992 
2993     case Decl::CXXConversion:
2994     case Decl::CXXDestructor:
2995     case Decl::CXXConstructor:
2996       valueKind = VK_RValue;
2997       break;
2998     }
2999 
3000     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3001                             TemplateArgs);
3002   }
3003 }
3004 
3005 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3006                                     SmallString<32> &Target) {
3007   Target.resize(CharByteWidth * (Source.size() + 1));
3008   char *ResultPtr = &Target[0];
3009   const llvm::UTF8 *ErrorPtr;
3010   bool success =
3011       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3012   (void)success;
3013   assert(success);
3014   Target.resize(ResultPtr - &Target[0]);
3015 }
3016 
3017 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3018                                      PredefinedExpr::IdentType IT) {
3019   // Pick the current block, lambda, captured statement or function.
3020   Decl *currentDecl = nullptr;
3021   if (const BlockScopeInfo *BSI = getCurBlock())
3022     currentDecl = BSI->TheDecl;
3023   else if (const LambdaScopeInfo *LSI = getCurLambda())
3024     currentDecl = LSI->CallOperator;
3025   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3026     currentDecl = CSI->TheCapturedDecl;
3027   else
3028     currentDecl = getCurFunctionOrMethodDecl();
3029 
3030   if (!currentDecl) {
3031     Diag(Loc, diag::ext_predef_outside_function);
3032     currentDecl = Context.getTranslationUnitDecl();
3033   }
3034 
3035   QualType ResTy;
3036   StringLiteral *SL = nullptr;
3037   if (cast<DeclContext>(currentDecl)->isDependentContext())
3038     ResTy = Context.DependentTy;
3039   else {
3040     // Pre-defined identifiers are of type char[x], where x is the length of
3041     // the string.
3042     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3043     unsigned Length = Str.length();
3044 
3045     llvm::APInt LengthI(32, Length + 1);
3046     if (IT == PredefinedExpr::LFunction) {
3047       ResTy =
3048           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3049       SmallString<32> RawChars;
3050       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3051                               Str, RawChars);
3052       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3053                                            /*IndexTypeQuals*/ 0);
3054       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3055                                  /*Pascal*/ false, ResTy, Loc);
3056     } else {
3057       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3058       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3059                                            /*IndexTypeQuals*/ 0);
3060       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3061                                  /*Pascal*/ false, ResTy, Loc);
3062     }
3063   }
3064 
3065   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3066 }
3067 
3068 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3069   PredefinedExpr::IdentType IT;
3070 
3071   switch (Kind) {
3072   default: llvm_unreachable("Unknown simple primary expr!");
3073   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3074   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3075   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3076   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3077   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3078   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3079   }
3080 
3081   return BuildPredefinedExpr(Loc, IT);
3082 }
3083 
3084 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3085   SmallString<16> CharBuffer;
3086   bool Invalid = false;
3087   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3088   if (Invalid)
3089     return ExprError();
3090 
3091   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3092                             PP, Tok.getKind());
3093   if (Literal.hadError())
3094     return ExprError();
3095 
3096   QualType Ty;
3097   if (Literal.isWide())
3098     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3099   else if (Literal.isUTF8() && getLangOpts().Char8)
3100     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3101   else if (Literal.isUTF16())
3102     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3103   else if (Literal.isUTF32())
3104     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3105   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3106     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3107   else
3108     Ty = Context.CharTy;  // 'x' -> char in C++
3109 
3110   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3111   if (Literal.isWide())
3112     Kind = CharacterLiteral::Wide;
3113   else if (Literal.isUTF16())
3114     Kind = CharacterLiteral::UTF16;
3115   else if (Literal.isUTF32())
3116     Kind = CharacterLiteral::UTF32;
3117   else if (Literal.isUTF8())
3118     Kind = CharacterLiteral::UTF8;
3119 
3120   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3121                                              Tok.getLocation());
3122 
3123   if (Literal.getUDSuffix().empty())
3124     return Lit;
3125 
3126   // We're building a user-defined literal.
3127   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3128   SourceLocation UDSuffixLoc =
3129     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3130 
3131   // Make sure we're allowed user-defined literals here.
3132   if (!UDLScope)
3133     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3134 
3135   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3136   //   operator "" X (ch)
3137   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3138                                         Lit, Tok.getLocation());
3139 }
3140 
3141 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3142   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3143   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3144                                 Context.IntTy, Loc);
3145 }
3146 
3147 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3148                                   QualType Ty, SourceLocation Loc) {
3149   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3150 
3151   using llvm::APFloat;
3152   APFloat Val(Format);
3153 
3154   APFloat::opStatus result = Literal.GetFloatValue(Val);
3155 
3156   // Overflow is always an error, but underflow is only an error if
3157   // we underflowed to zero (APFloat reports denormals as underflow).
3158   if ((result & APFloat::opOverflow) ||
3159       ((result & APFloat::opUnderflow) && Val.isZero())) {
3160     unsigned diagnostic;
3161     SmallString<20> buffer;
3162     if (result & APFloat::opOverflow) {
3163       diagnostic = diag::warn_float_overflow;
3164       APFloat::getLargest(Format).toString(buffer);
3165     } else {
3166       diagnostic = diag::warn_float_underflow;
3167       APFloat::getSmallest(Format).toString(buffer);
3168     }
3169 
3170     S.Diag(Loc, diagnostic)
3171       << Ty
3172       << StringRef(buffer.data(), buffer.size());
3173   }
3174 
3175   bool isExact = (result == APFloat::opOK);
3176   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3177 }
3178 
3179 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3180   assert(E && "Invalid expression");
3181 
3182   if (E->isValueDependent())
3183     return false;
3184 
3185   QualType QT = E->getType();
3186   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3187     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3188     return true;
3189   }
3190 
3191   llvm::APSInt ValueAPS;
3192   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3193 
3194   if (R.isInvalid())
3195     return true;
3196 
3197   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3198   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3199     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3200         << ValueAPS.toString(10) << ValueIsPositive;
3201     return true;
3202   }
3203 
3204   return false;
3205 }
3206 
3207 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3208   // Fast path for a single digit (which is quite common).  A single digit
3209   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3210   if (Tok.getLength() == 1) {
3211     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3212     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3213   }
3214 
3215   SmallString<128> SpellingBuffer;
3216   // NumericLiteralParser wants to overread by one character.  Add padding to
3217   // the buffer in case the token is copied to the buffer.  If getSpelling()
3218   // returns a StringRef to the memory buffer, it should have a null char at
3219   // the EOF, so it is also safe.
3220   SpellingBuffer.resize(Tok.getLength() + 1);
3221 
3222   // Get the spelling of the token, which eliminates trigraphs, etc.
3223   bool Invalid = false;
3224   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3225   if (Invalid)
3226     return ExprError();
3227 
3228   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3229   if (Literal.hadError)
3230     return ExprError();
3231 
3232   if (Literal.hasUDSuffix()) {
3233     // We're building a user-defined literal.
3234     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3235     SourceLocation UDSuffixLoc =
3236       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3237 
3238     // Make sure we're allowed user-defined literals here.
3239     if (!UDLScope)
3240       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3241 
3242     QualType CookedTy;
3243     if (Literal.isFloatingLiteral()) {
3244       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3245       // long double, the literal is treated as a call of the form
3246       //   operator "" X (f L)
3247       CookedTy = Context.LongDoubleTy;
3248     } else {
3249       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3250       // unsigned long long, the literal is treated as a call of the form
3251       //   operator "" X (n ULL)
3252       CookedTy = Context.UnsignedLongLongTy;
3253     }
3254 
3255     DeclarationName OpName =
3256       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3257     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3258     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3259 
3260     SourceLocation TokLoc = Tok.getLocation();
3261 
3262     // Perform literal operator lookup to determine if we're building a raw
3263     // literal or a cooked one.
3264     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3265     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3266                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3267                                   /*AllowStringTemplate*/ false,
3268                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3269     case LOLR_ErrorNoDiagnostic:
3270       // Lookup failure for imaginary constants isn't fatal, there's still the
3271       // GNU extension producing _Complex types.
3272       break;
3273     case LOLR_Error:
3274       return ExprError();
3275     case LOLR_Cooked: {
3276       Expr *Lit;
3277       if (Literal.isFloatingLiteral()) {
3278         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3279       } else {
3280         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3281         if (Literal.GetIntegerValue(ResultVal))
3282           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3283               << /* Unsigned */ 1;
3284         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3285                                      Tok.getLocation());
3286       }
3287       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3288     }
3289 
3290     case LOLR_Raw: {
3291       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3292       // literal is treated as a call of the form
3293       //   operator "" X ("n")
3294       unsigned Length = Literal.getUDSuffixOffset();
3295       QualType StrTy = Context.getConstantArrayType(
3296           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3297           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3298       Expr *Lit = StringLiteral::Create(
3299           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3300           /*Pascal*/false, StrTy, &TokLoc, 1);
3301       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3302     }
3303 
3304     case LOLR_Template: {
3305       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3306       // template), L is treated as a call fo the form
3307       //   operator "" X <'c1', 'c2', ... 'ck'>()
3308       // where n is the source character sequence c1 c2 ... ck.
3309       TemplateArgumentListInfo ExplicitArgs;
3310       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3311       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3312       llvm::APSInt Value(CharBits, CharIsUnsigned);
3313       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3314         Value = TokSpelling[I];
3315         TemplateArgument Arg(Context, Value, Context.CharTy);
3316         TemplateArgumentLocInfo ArgInfo;
3317         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3318       }
3319       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3320                                       &ExplicitArgs);
3321     }
3322     case LOLR_StringTemplate:
3323       llvm_unreachable("unexpected literal operator lookup result");
3324     }
3325   }
3326 
3327   Expr *Res;
3328 
3329   if (Literal.isFixedPointLiteral()) {
3330     QualType Ty;
3331 
3332     if (Literal.isAccum) {
3333       if (Literal.isHalf) {
3334         Ty = Context.ShortAccumTy;
3335       } else if (Literal.isLong) {
3336         Ty = Context.LongAccumTy;
3337       } else {
3338         Ty = Context.AccumTy;
3339       }
3340     } else if (Literal.isFract) {
3341       if (Literal.isHalf) {
3342         Ty = Context.ShortFractTy;
3343       } else if (Literal.isLong) {
3344         Ty = Context.LongFractTy;
3345       } else {
3346         Ty = Context.FractTy;
3347       }
3348     }
3349 
3350     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3351 
3352     bool isSigned = !Literal.isUnsigned;
3353     unsigned scale = Context.getFixedPointScale(Ty);
3354     unsigned ibits = Context.getFixedPointIBits(Ty);
3355     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3356 
3357     llvm::APInt Val(bit_width, 0, isSigned);
3358     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3359 
3360     // Do not use bit_width since some types may have padding like _Fract or
3361     // unsigned _Accums if SameFBits is set.
3362     auto MaxVal = llvm::APInt::getMaxValue(ibits + scale).zextOrSelf(bit_width);
3363     if (Literal.isFract && Val == MaxVal + 1)
3364       // Clause 6.4.4 - The value of a constant shall be in the range of
3365       // representable values for its type, with exception for constants of a
3366       // fract type with a value of exactly 1; such a constant shall denote
3367       // the maximal value for the type.
3368       --Val;
3369     else if (Val.ugt(MaxVal) || Overflowed)
3370       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3371 
3372     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3373                                               Tok.getLocation(), scale);
3374   } else if (Literal.isFloatingLiteral()) {
3375     QualType Ty;
3376     if (Literal.isHalf){
3377       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3378         Ty = Context.HalfTy;
3379       else {
3380         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3381         return ExprError();
3382       }
3383     } else if (Literal.isFloat)
3384       Ty = Context.FloatTy;
3385     else if (Literal.isLong)
3386       Ty = Context.LongDoubleTy;
3387     else if (Literal.isFloat16)
3388       Ty = Context.Float16Ty;
3389     else if (Literal.isFloat128)
3390       Ty = Context.Float128Ty;
3391     else
3392       Ty = Context.DoubleTy;
3393 
3394     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3395 
3396     if (Ty == Context.DoubleTy) {
3397       if (getLangOpts().SinglePrecisionConstants) {
3398         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3399         if (BTy->getKind() != BuiltinType::Float) {
3400           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3401         }
3402       } else if (getLangOpts().OpenCL &&
3403                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3404         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3405         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3406         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3407       }
3408     }
3409   } else if (!Literal.isIntegerLiteral()) {
3410     return ExprError();
3411   } else {
3412     QualType Ty;
3413 
3414     // 'long long' is a C99 or C++11 feature.
3415     if (!getLangOpts().C99 && Literal.isLongLong) {
3416       if (getLangOpts().CPlusPlus)
3417         Diag(Tok.getLocation(),
3418              getLangOpts().CPlusPlus11 ?
3419              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3420       else
3421         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3422     }
3423 
3424     // Get the value in the widest-possible width.
3425     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3426     llvm::APInt ResultVal(MaxWidth, 0);
3427 
3428     if (Literal.GetIntegerValue(ResultVal)) {
3429       // If this value didn't fit into uintmax_t, error and force to ull.
3430       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3431           << /* Unsigned */ 1;
3432       Ty = Context.UnsignedLongLongTy;
3433       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3434              "long long is not intmax_t?");
3435     } else {
3436       // If this value fits into a ULL, try to figure out what else it fits into
3437       // according to the rules of C99 6.4.4.1p5.
3438 
3439       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3440       // be an unsigned int.
3441       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3442 
3443       // Check from smallest to largest, picking the smallest type we can.
3444       unsigned Width = 0;
3445 
3446       // Microsoft specific integer suffixes are explicitly sized.
3447       if (Literal.MicrosoftInteger) {
3448         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3449           Width = 8;
3450           Ty = Context.CharTy;
3451         } else {
3452           Width = Literal.MicrosoftInteger;
3453           Ty = Context.getIntTypeForBitwidth(Width,
3454                                              /*Signed=*/!Literal.isUnsigned);
3455         }
3456       }
3457 
3458       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3459         // Are int/unsigned possibilities?
3460         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3461 
3462         // Does it fit in a unsigned int?
3463         if (ResultVal.isIntN(IntSize)) {
3464           // Does it fit in a signed int?
3465           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3466             Ty = Context.IntTy;
3467           else if (AllowUnsigned)
3468             Ty = Context.UnsignedIntTy;
3469           Width = IntSize;
3470         }
3471       }
3472 
3473       // Are long/unsigned long possibilities?
3474       if (Ty.isNull() && !Literal.isLongLong) {
3475         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3476 
3477         // Does it fit in a unsigned long?
3478         if (ResultVal.isIntN(LongSize)) {
3479           // Does it fit in a signed long?
3480           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3481             Ty = Context.LongTy;
3482           else if (AllowUnsigned)
3483             Ty = Context.UnsignedLongTy;
3484           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3485           // is compatible.
3486           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3487             const unsigned LongLongSize =
3488                 Context.getTargetInfo().getLongLongWidth();
3489             Diag(Tok.getLocation(),
3490                  getLangOpts().CPlusPlus
3491                      ? Literal.isLong
3492                            ? diag::warn_old_implicitly_unsigned_long_cxx
3493                            : /*C++98 UB*/ diag::
3494                                  ext_old_implicitly_unsigned_long_cxx
3495                      : diag::warn_old_implicitly_unsigned_long)
3496                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3497                                             : /*will be ill-formed*/ 1);
3498             Ty = Context.UnsignedLongTy;
3499           }
3500           Width = LongSize;
3501         }
3502       }
3503 
3504       // Check long long if needed.
3505       if (Ty.isNull()) {
3506         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3507 
3508         // Does it fit in a unsigned long long?
3509         if (ResultVal.isIntN(LongLongSize)) {
3510           // Does it fit in a signed long long?
3511           // To be compatible with MSVC, hex integer literals ending with the
3512           // LL or i64 suffix are always signed in Microsoft mode.
3513           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3514               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3515             Ty = Context.LongLongTy;
3516           else if (AllowUnsigned)
3517             Ty = Context.UnsignedLongLongTy;
3518           Width = LongLongSize;
3519         }
3520       }
3521 
3522       // If we still couldn't decide a type, we probably have something that
3523       // does not fit in a signed long long, but has no U suffix.
3524       if (Ty.isNull()) {
3525         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3526         Ty = Context.UnsignedLongLongTy;
3527         Width = Context.getTargetInfo().getLongLongWidth();
3528       }
3529 
3530       if (ResultVal.getBitWidth() != Width)
3531         ResultVal = ResultVal.trunc(Width);
3532     }
3533     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3534   }
3535 
3536   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3537   if (Literal.isImaginary) {
3538     Res = new (Context) ImaginaryLiteral(Res,
3539                                         Context.getComplexType(Res->getType()));
3540 
3541     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3542   }
3543   return Res;
3544 }
3545 
3546 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3547   assert(E && "ActOnParenExpr() missing expr");
3548   return new (Context) ParenExpr(L, R, E);
3549 }
3550 
3551 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3552                                          SourceLocation Loc,
3553                                          SourceRange ArgRange) {
3554   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3555   // scalar or vector data type argument..."
3556   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3557   // type (C99 6.2.5p18) or void.
3558   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3559     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3560       << T << ArgRange;
3561     return true;
3562   }
3563 
3564   assert((T->isVoidType() || !T->isIncompleteType()) &&
3565          "Scalar types should always be complete");
3566   return false;
3567 }
3568 
3569 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3570                                            SourceLocation Loc,
3571                                            SourceRange ArgRange,
3572                                            UnaryExprOrTypeTrait TraitKind) {
3573   // Invalid types must be hard errors for SFINAE in C++.
3574   if (S.LangOpts.CPlusPlus)
3575     return true;
3576 
3577   // C99 6.5.3.4p1:
3578   if (T->isFunctionType() &&
3579       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3580     // sizeof(function)/alignof(function) is allowed as an extension.
3581     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3582       << TraitKind << ArgRange;
3583     return false;
3584   }
3585 
3586   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3587   // this is an error (OpenCL v1.1 s6.3.k)
3588   if (T->isVoidType()) {
3589     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3590                                         : diag::ext_sizeof_alignof_void_type;
3591     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3592     return false;
3593   }
3594 
3595   return true;
3596 }
3597 
3598 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3599                                              SourceLocation Loc,
3600                                              SourceRange ArgRange,
3601                                              UnaryExprOrTypeTrait TraitKind) {
3602   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3603   // runtime doesn't allow it.
3604   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3605     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3606       << T << (TraitKind == UETT_SizeOf)
3607       << ArgRange;
3608     return true;
3609   }
3610 
3611   return false;
3612 }
3613 
3614 /// Check whether E is a pointer from a decayed array type (the decayed
3615 /// pointer type is equal to T) and emit a warning if it is.
3616 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3617                                      Expr *E) {
3618   // Don't warn if the operation changed the type.
3619   if (T != E->getType())
3620     return;
3621 
3622   // Now look for array decays.
3623   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3624   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3625     return;
3626 
3627   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3628                                              << ICE->getType()
3629                                              << ICE->getSubExpr()->getType();
3630 }
3631 
3632 /// Check the constraints on expression operands to unary type expression
3633 /// and type traits.
3634 ///
3635 /// Completes any types necessary and validates the constraints on the operand
3636 /// expression. The logic mostly mirrors the type-based overload, but may modify
3637 /// the expression as it completes the type for that expression through template
3638 /// instantiation, etc.
3639 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3640                                             UnaryExprOrTypeTrait ExprKind) {
3641   QualType ExprTy = E->getType();
3642   assert(!ExprTy->isReferenceType());
3643 
3644   if (ExprKind == UETT_VecStep)
3645     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3646                                         E->getSourceRange());
3647 
3648   // Whitelist some types as extensions
3649   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3650                                       E->getSourceRange(), ExprKind))
3651     return false;
3652 
3653   // 'alignof' applied to an expression only requires the base element type of
3654   // the expression to be complete. 'sizeof' requires the expression's type to
3655   // be complete (and will attempt to complete it if it's an array of unknown
3656   // bound).
3657   if (ExprKind == UETT_AlignOf) {
3658     if (RequireCompleteType(E->getExprLoc(),
3659                             Context.getBaseElementType(E->getType()),
3660                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3661                             E->getSourceRange()))
3662       return true;
3663   } else {
3664     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3665                                 ExprKind, E->getSourceRange()))
3666       return true;
3667   }
3668 
3669   // Completing the expression's type may have changed it.
3670   ExprTy = E->getType();
3671   assert(!ExprTy->isReferenceType());
3672 
3673   if (ExprTy->isFunctionType()) {
3674     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3675       << ExprKind << E->getSourceRange();
3676     return true;
3677   }
3678 
3679   // The operand for sizeof and alignof is in an unevaluated expression context,
3680   // so side effects could result in unintended consequences.
3681   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3682       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3683     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3684 
3685   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3686                                        E->getSourceRange(), ExprKind))
3687     return true;
3688 
3689   if (ExprKind == UETT_SizeOf) {
3690     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3691       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3692         QualType OType = PVD->getOriginalType();
3693         QualType Type = PVD->getType();
3694         if (Type->isPointerType() && OType->isArrayType()) {
3695           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3696             << Type << OType;
3697           Diag(PVD->getLocation(), diag::note_declared_at);
3698         }
3699       }
3700     }
3701 
3702     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3703     // decays into a pointer and returns an unintended result. This is most
3704     // likely a typo for "sizeof(array) op x".
3705     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3706       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3707                                BO->getLHS());
3708       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3709                                BO->getRHS());
3710     }
3711   }
3712 
3713   return false;
3714 }
3715 
3716 /// Check the constraints on operands to unary expression and type
3717 /// traits.
3718 ///
3719 /// This will complete any types necessary, and validate the various constraints
3720 /// on those operands.
3721 ///
3722 /// The UsualUnaryConversions() function is *not* called by this routine.
3723 /// C99 6.3.2.1p[2-4] all state:
3724 ///   Except when it is the operand of the sizeof operator ...
3725 ///
3726 /// C++ [expr.sizeof]p4
3727 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3728 ///   standard conversions are not applied to the operand of sizeof.
3729 ///
3730 /// This policy is followed for all of the unary trait expressions.
3731 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3732                                             SourceLocation OpLoc,
3733                                             SourceRange ExprRange,
3734                                             UnaryExprOrTypeTrait ExprKind) {
3735   if (ExprType->isDependentType())
3736     return false;
3737 
3738   // C++ [expr.sizeof]p2:
3739   //     When applied to a reference or a reference type, the result
3740   //     is the size of the referenced type.
3741   // C++11 [expr.alignof]p3:
3742   //     When alignof is applied to a reference type, the result
3743   //     shall be the alignment of the referenced type.
3744   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3745     ExprType = Ref->getPointeeType();
3746 
3747   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3748   //   When alignof or _Alignof is applied to an array type, the result
3749   //   is the alignment of the element type.
3750   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3751     ExprType = Context.getBaseElementType(ExprType);
3752 
3753   if (ExprKind == UETT_VecStep)
3754     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3755 
3756   // Whitelist some types as extensions
3757   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3758                                       ExprKind))
3759     return false;
3760 
3761   if (RequireCompleteType(OpLoc, ExprType,
3762                           diag::err_sizeof_alignof_incomplete_type,
3763                           ExprKind, ExprRange))
3764     return true;
3765 
3766   if (ExprType->isFunctionType()) {
3767     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3768       << ExprKind << ExprRange;
3769     return true;
3770   }
3771 
3772   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3773                                        ExprKind))
3774     return true;
3775 
3776   return false;
3777 }
3778 
3779 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3780   E = E->IgnoreParens();
3781 
3782   // Cannot know anything else if the expression is dependent.
3783   if (E->isTypeDependent())
3784     return false;
3785 
3786   if (E->getObjectKind() == OK_BitField) {
3787     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3788        << 1 << E->getSourceRange();
3789     return true;
3790   }
3791 
3792   ValueDecl *D = nullptr;
3793   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3794     D = DRE->getDecl();
3795   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3796     D = ME->getMemberDecl();
3797   }
3798 
3799   // If it's a field, require the containing struct to have a
3800   // complete definition so that we can compute the layout.
3801   //
3802   // This can happen in C++11 onwards, either by naming the member
3803   // in a way that is not transformed into a member access expression
3804   // (in an unevaluated operand, for instance), or by naming the member
3805   // in a trailing-return-type.
3806   //
3807   // For the record, since __alignof__ on expressions is a GCC
3808   // extension, GCC seems to permit this but always gives the
3809   // nonsensical answer 0.
3810   //
3811   // We don't really need the layout here --- we could instead just
3812   // directly check for all the appropriate alignment-lowing
3813   // attributes --- but that would require duplicating a lot of
3814   // logic that just isn't worth duplicating for such a marginal
3815   // use-case.
3816   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3817     // Fast path this check, since we at least know the record has a
3818     // definition if we can find a member of it.
3819     if (!FD->getParent()->isCompleteDefinition()) {
3820       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3821         << E->getSourceRange();
3822       return true;
3823     }
3824 
3825     // Otherwise, if it's a field, and the field doesn't have
3826     // reference type, then it must have a complete type (or be a
3827     // flexible array member, which we explicitly want to
3828     // white-list anyway), which makes the following checks trivial.
3829     if (!FD->getType()->isReferenceType())
3830       return false;
3831   }
3832 
3833   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3834 }
3835 
3836 bool Sema::CheckVecStepExpr(Expr *E) {
3837   E = E->IgnoreParens();
3838 
3839   // Cannot know anything else if the expression is dependent.
3840   if (E->isTypeDependent())
3841     return false;
3842 
3843   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3844 }
3845 
3846 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3847                                         CapturingScopeInfo *CSI) {
3848   assert(T->isVariablyModifiedType());
3849   assert(CSI != nullptr);
3850 
3851   // We're going to walk down into the type and look for VLA expressions.
3852   do {
3853     const Type *Ty = T.getTypePtr();
3854     switch (Ty->getTypeClass()) {
3855 #define TYPE(Class, Base)
3856 #define ABSTRACT_TYPE(Class, Base)
3857 #define NON_CANONICAL_TYPE(Class, Base)
3858 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3859 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3860 #include "clang/AST/TypeNodes.def"
3861       T = QualType();
3862       break;
3863     // These types are never variably-modified.
3864     case Type::Builtin:
3865     case Type::Complex:
3866     case Type::Vector:
3867     case Type::ExtVector:
3868     case Type::Record:
3869     case Type::Enum:
3870     case Type::Elaborated:
3871     case Type::TemplateSpecialization:
3872     case Type::ObjCObject:
3873     case Type::ObjCInterface:
3874     case Type::ObjCObjectPointer:
3875     case Type::ObjCTypeParam:
3876     case Type::Pipe:
3877       llvm_unreachable("type class is never variably-modified!");
3878     case Type::Adjusted:
3879       T = cast<AdjustedType>(Ty)->getOriginalType();
3880       break;
3881     case Type::Decayed:
3882       T = cast<DecayedType>(Ty)->getPointeeType();
3883       break;
3884     case Type::Pointer:
3885       T = cast<PointerType>(Ty)->getPointeeType();
3886       break;
3887     case Type::BlockPointer:
3888       T = cast<BlockPointerType>(Ty)->getPointeeType();
3889       break;
3890     case Type::LValueReference:
3891     case Type::RValueReference:
3892       T = cast<ReferenceType>(Ty)->getPointeeType();
3893       break;
3894     case Type::MemberPointer:
3895       T = cast<MemberPointerType>(Ty)->getPointeeType();
3896       break;
3897     case Type::ConstantArray:
3898     case Type::IncompleteArray:
3899       // Losing element qualification here is fine.
3900       T = cast<ArrayType>(Ty)->getElementType();
3901       break;
3902     case Type::VariableArray: {
3903       // Losing element qualification here is fine.
3904       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3905 
3906       // Unknown size indication requires no size computation.
3907       // Otherwise, evaluate and record it.
3908       if (auto Size = VAT->getSizeExpr()) {
3909         if (!CSI->isVLATypeCaptured(VAT)) {
3910           RecordDecl *CapRecord = nullptr;
3911           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3912             CapRecord = LSI->Lambda;
3913           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3914             CapRecord = CRSI->TheRecordDecl;
3915           }
3916           if (CapRecord) {
3917             auto ExprLoc = Size->getExprLoc();
3918             auto SizeType = Context.getSizeType();
3919             // Build the non-static data member.
3920             auto Field =
3921                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3922                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3923                                   /*BW*/ nullptr, /*Mutable*/ false,
3924                                   /*InitStyle*/ ICIS_NoInit);
3925             Field->setImplicit(true);
3926             Field->setAccess(AS_private);
3927             Field->setCapturedVLAType(VAT);
3928             CapRecord->addDecl(Field);
3929 
3930             CSI->addVLATypeCapture(ExprLoc, SizeType);
3931           }
3932         }
3933       }
3934       T = VAT->getElementType();
3935       break;
3936     }
3937     case Type::FunctionProto:
3938     case Type::FunctionNoProto:
3939       T = cast<FunctionType>(Ty)->getReturnType();
3940       break;
3941     case Type::Paren:
3942     case Type::TypeOf:
3943     case Type::UnaryTransform:
3944     case Type::Attributed:
3945     case Type::SubstTemplateTypeParm:
3946     case Type::PackExpansion:
3947       // Keep walking after single level desugaring.
3948       T = T.getSingleStepDesugaredType(Context);
3949       break;
3950     case Type::Typedef:
3951       T = cast<TypedefType>(Ty)->desugar();
3952       break;
3953     case Type::Decltype:
3954       T = cast<DecltypeType>(Ty)->desugar();
3955       break;
3956     case Type::Auto:
3957     case Type::DeducedTemplateSpecialization:
3958       T = cast<DeducedType>(Ty)->getDeducedType();
3959       break;
3960     case Type::TypeOfExpr:
3961       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3962       break;
3963     case Type::Atomic:
3964       T = cast<AtomicType>(Ty)->getValueType();
3965       break;
3966     }
3967   } while (!T.isNull() && T->isVariablyModifiedType());
3968 }
3969 
3970 /// Build a sizeof or alignof expression given a type operand.
3971 ExprResult
3972 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3973                                      SourceLocation OpLoc,
3974                                      UnaryExprOrTypeTrait ExprKind,
3975                                      SourceRange R) {
3976   if (!TInfo)
3977     return ExprError();
3978 
3979   QualType T = TInfo->getType();
3980 
3981   if (!T->isDependentType() &&
3982       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3983     return ExprError();
3984 
3985   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3986     if (auto *TT = T->getAs<TypedefType>()) {
3987       for (auto I = FunctionScopes.rbegin(),
3988                 E = std::prev(FunctionScopes.rend());
3989            I != E; ++I) {
3990         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3991         if (CSI == nullptr)
3992           break;
3993         DeclContext *DC = nullptr;
3994         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3995           DC = LSI->CallOperator;
3996         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3997           DC = CRSI->TheCapturedDecl;
3998         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3999           DC = BSI->TheDecl;
4000         if (DC) {
4001           if (DC->containsDecl(TT->getDecl()))
4002             break;
4003           captureVariablyModifiedType(Context, T, CSI);
4004         }
4005       }
4006     }
4007   }
4008 
4009   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4010   return new (Context) UnaryExprOrTypeTraitExpr(
4011       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4012 }
4013 
4014 /// Build a sizeof or alignof expression given an expression
4015 /// operand.
4016 ExprResult
4017 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4018                                      UnaryExprOrTypeTrait ExprKind) {
4019   ExprResult PE = CheckPlaceholderExpr(E);
4020   if (PE.isInvalid())
4021     return ExprError();
4022 
4023   E = PE.get();
4024 
4025   // Verify that the operand is valid.
4026   bool isInvalid = false;
4027   if (E->isTypeDependent()) {
4028     // Delay type-checking for type-dependent expressions.
4029   } else if (ExprKind == UETT_AlignOf) {
4030     isInvalid = CheckAlignOfExpr(*this, E);
4031   } else if (ExprKind == UETT_VecStep) {
4032     isInvalid = CheckVecStepExpr(E);
4033   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4034       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4035       isInvalid = true;
4036   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4037     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4038     isInvalid = true;
4039   } else {
4040     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4041   }
4042 
4043   if (isInvalid)
4044     return ExprError();
4045 
4046   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4047     PE = TransformToPotentiallyEvaluated(E);
4048     if (PE.isInvalid()) return ExprError();
4049     E = PE.get();
4050   }
4051 
4052   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4053   return new (Context) UnaryExprOrTypeTraitExpr(
4054       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4055 }
4056 
4057 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4058 /// expr and the same for @c alignof and @c __alignof
4059 /// Note that the ArgRange is invalid if isType is false.
4060 ExprResult
4061 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4062                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4063                                     void *TyOrEx, SourceRange ArgRange) {
4064   // If error parsing type, ignore.
4065   if (!TyOrEx) return ExprError();
4066 
4067   if (IsType) {
4068     TypeSourceInfo *TInfo;
4069     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4070     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4071   }
4072 
4073   Expr *ArgEx = (Expr *)TyOrEx;
4074   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4075   return Result;
4076 }
4077 
4078 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4079                                      bool IsReal) {
4080   if (V.get()->isTypeDependent())
4081     return S.Context.DependentTy;
4082 
4083   // _Real and _Imag are only l-values for normal l-values.
4084   if (V.get()->getObjectKind() != OK_Ordinary) {
4085     V = S.DefaultLvalueConversion(V.get());
4086     if (V.isInvalid())
4087       return QualType();
4088   }
4089 
4090   // These operators return the element type of a complex type.
4091   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4092     return CT->getElementType();
4093 
4094   // Otherwise they pass through real integer and floating point types here.
4095   if (V.get()->getType()->isArithmeticType())
4096     return V.get()->getType();
4097 
4098   // Test for placeholders.
4099   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4100   if (PR.isInvalid()) return QualType();
4101   if (PR.get() != V.get()) {
4102     V = PR;
4103     return CheckRealImagOperand(S, V, Loc, IsReal);
4104   }
4105 
4106   // Reject anything else.
4107   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4108     << (IsReal ? "__real" : "__imag");
4109   return QualType();
4110 }
4111 
4112 
4113 
4114 ExprResult
4115 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4116                           tok::TokenKind Kind, Expr *Input) {
4117   UnaryOperatorKind Opc;
4118   switch (Kind) {
4119   default: llvm_unreachable("Unknown unary op!");
4120   case tok::plusplus:   Opc = UO_PostInc; break;
4121   case tok::minusminus: Opc = UO_PostDec; break;
4122   }
4123 
4124   // Since this might is a postfix expression, get rid of ParenListExprs.
4125   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4126   if (Result.isInvalid()) return ExprError();
4127   Input = Result.get();
4128 
4129   return BuildUnaryOp(S, OpLoc, Opc, Input);
4130 }
4131 
4132 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4133 ///
4134 /// \return true on error
4135 static bool checkArithmeticOnObjCPointer(Sema &S,
4136                                          SourceLocation opLoc,
4137                                          Expr *op) {
4138   assert(op->getType()->isObjCObjectPointerType());
4139   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4140       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4141     return false;
4142 
4143   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4144     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4145     << op->getSourceRange();
4146   return true;
4147 }
4148 
4149 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4150   auto *BaseNoParens = Base->IgnoreParens();
4151   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4152     return MSProp->getPropertyDecl()->getType()->isArrayType();
4153   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4154 }
4155 
4156 ExprResult
4157 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4158                               Expr *idx, SourceLocation rbLoc) {
4159   if (base && !base->getType().isNull() &&
4160       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4161     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4162                                     /*Length=*/nullptr, rbLoc);
4163 
4164   // Since this might be a postfix expression, get rid of ParenListExprs.
4165   if (isa<ParenListExpr>(base)) {
4166     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4167     if (result.isInvalid()) return ExprError();
4168     base = result.get();
4169   }
4170 
4171   // Handle any non-overload placeholder types in the base and index
4172   // expressions.  We can't handle overloads here because the other
4173   // operand might be an overloadable type, in which case the overload
4174   // resolution for the operator overload should get the first crack
4175   // at the overload.
4176   bool IsMSPropertySubscript = false;
4177   if (base->getType()->isNonOverloadPlaceholderType()) {
4178     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4179     if (!IsMSPropertySubscript) {
4180       ExprResult result = CheckPlaceholderExpr(base);
4181       if (result.isInvalid())
4182         return ExprError();
4183       base = result.get();
4184     }
4185   }
4186   if (idx->getType()->isNonOverloadPlaceholderType()) {
4187     ExprResult result = CheckPlaceholderExpr(idx);
4188     if (result.isInvalid()) return ExprError();
4189     idx = result.get();
4190   }
4191 
4192   // Build an unanalyzed expression if either operand is type-dependent.
4193   if (getLangOpts().CPlusPlus &&
4194       (base->isTypeDependent() || idx->isTypeDependent())) {
4195     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4196                                             VK_LValue, OK_Ordinary, rbLoc);
4197   }
4198 
4199   // MSDN, property (C++)
4200   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4201   // This attribute can also be used in the declaration of an empty array in a
4202   // class or structure definition. For example:
4203   // __declspec(property(get=GetX, put=PutX)) int x[];
4204   // The above statement indicates that x[] can be used with one or more array
4205   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4206   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4207   if (IsMSPropertySubscript) {
4208     // Build MS property subscript expression if base is MS property reference
4209     // or MS property subscript.
4210     return new (Context) MSPropertySubscriptExpr(
4211         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4212   }
4213 
4214   // Use C++ overloaded-operator rules if either operand has record
4215   // type.  The spec says to do this if either type is *overloadable*,
4216   // but enum types can't declare subscript operators or conversion
4217   // operators, so there's nothing interesting for overload resolution
4218   // to do if there aren't any record types involved.
4219   //
4220   // ObjC pointers have their own subscripting logic that is not tied
4221   // to overload resolution and so should not take this path.
4222   if (getLangOpts().CPlusPlus &&
4223       (base->getType()->isRecordType() ||
4224        (!base->getType()->isObjCObjectPointerType() &&
4225         idx->getType()->isRecordType()))) {
4226     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4227   }
4228 
4229   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4230 }
4231 
4232 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4233                                           Expr *LowerBound,
4234                                           SourceLocation ColonLoc, Expr *Length,
4235                                           SourceLocation RBLoc) {
4236   if (Base->getType()->isPlaceholderType() &&
4237       !Base->getType()->isSpecificPlaceholderType(
4238           BuiltinType::OMPArraySection)) {
4239     ExprResult Result = CheckPlaceholderExpr(Base);
4240     if (Result.isInvalid())
4241       return ExprError();
4242     Base = Result.get();
4243   }
4244   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4245     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4246     if (Result.isInvalid())
4247       return ExprError();
4248     Result = DefaultLvalueConversion(Result.get());
4249     if (Result.isInvalid())
4250       return ExprError();
4251     LowerBound = Result.get();
4252   }
4253   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4254     ExprResult Result = CheckPlaceholderExpr(Length);
4255     if (Result.isInvalid())
4256       return ExprError();
4257     Result = DefaultLvalueConversion(Result.get());
4258     if (Result.isInvalid())
4259       return ExprError();
4260     Length = Result.get();
4261   }
4262 
4263   // Build an unanalyzed expression if either operand is type-dependent.
4264   if (Base->isTypeDependent() ||
4265       (LowerBound &&
4266        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4267       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4268     return new (Context)
4269         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4270                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4271   }
4272 
4273   // Perform default conversions.
4274   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4275   QualType ResultTy;
4276   if (OriginalTy->isAnyPointerType()) {
4277     ResultTy = OriginalTy->getPointeeType();
4278   } else if (OriginalTy->isArrayType()) {
4279     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4280   } else {
4281     return ExprError(
4282         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4283         << Base->getSourceRange());
4284   }
4285   // C99 6.5.2.1p1
4286   if (LowerBound) {
4287     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4288                                                       LowerBound);
4289     if (Res.isInvalid())
4290       return ExprError(Diag(LowerBound->getExprLoc(),
4291                             diag::err_omp_typecheck_section_not_integer)
4292                        << 0 << LowerBound->getSourceRange());
4293     LowerBound = Res.get();
4294 
4295     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4296         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4297       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4298           << 0 << LowerBound->getSourceRange();
4299   }
4300   if (Length) {
4301     auto Res =
4302         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4303     if (Res.isInvalid())
4304       return ExprError(Diag(Length->getExprLoc(),
4305                             diag::err_omp_typecheck_section_not_integer)
4306                        << 1 << Length->getSourceRange());
4307     Length = Res.get();
4308 
4309     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4310         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4311       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4312           << 1 << Length->getSourceRange();
4313   }
4314 
4315   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4316   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4317   // type. Note that functions are not objects, and that (in C99 parlance)
4318   // incomplete types are not object types.
4319   if (ResultTy->isFunctionType()) {
4320     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4321         << ResultTy << Base->getSourceRange();
4322     return ExprError();
4323   }
4324 
4325   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4326                           diag::err_omp_section_incomplete_type, Base))
4327     return ExprError();
4328 
4329   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4330     llvm::APSInt LowerBoundValue;
4331     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4332       // OpenMP 4.5, [2.4 Array Sections]
4333       // The array section must be a subset of the original array.
4334       if (LowerBoundValue.isNegative()) {
4335         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4336             << LowerBound->getSourceRange();
4337         return ExprError();
4338       }
4339     }
4340   }
4341 
4342   if (Length) {
4343     llvm::APSInt LengthValue;
4344     if (Length->EvaluateAsInt(LengthValue, Context)) {
4345       // OpenMP 4.5, [2.4 Array Sections]
4346       // The length must evaluate to non-negative integers.
4347       if (LengthValue.isNegative()) {
4348         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4349             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4350             << Length->getSourceRange();
4351         return ExprError();
4352       }
4353     }
4354   } else if (ColonLoc.isValid() &&
4355              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4356                                       !OriginalTy->isVariableArrayType()))) {
4357     // OpenMP 4.5, [2.4 Array Sections]
4358     // When the size of the array dimension is not known, the length must be
4359     // specified explicitly.
4360     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4361         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4362     return ExprError();
4363   }
4364 
4365   if (!Base->getType()->isSpecificPlaceholderType(
4366           BuiltinType::OMPArraySection)) {
4367     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4368     if (Result.isInvalid())
4369       return ExprError();
4370     Base = Result.get();
4371   }
4372   return new (Context)
4373       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4374                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4375 }
4376 
4377 ExprResult
4378 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4379                                       Expr *Idx, SourceLocation RLoc) {
4380   Expr *LHSExp = Base;
4381   Expr *RHSExp = Idx;
4382 
4383   ExprValueKind VK = VK_LValue;
4384   ExprObjectKind OK = OK_Ordinary;
4385 
4386   // Per C++ core issue 1213, the result is an xvalue if either operand is
4387   // a non-lvalue array, and an lvalue otherwise.
4388   if (getLangOpts().CPlusPlus11 &&
4389       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4390        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4391     VK = VK_XValue;
4392 
4393   // Perform default conversions.
4394   if (!LHSExp->getType()->getAs<VectorType>()) {
4395     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4396     if (Result.isInvalid())
4397       return ExprError();
4398     LHSExp = Result.get();
4399   }
4400   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4401   if (Result.isInvalid())
4402     return ExprError();
4403   RHSExp = Result.get();
4404 
4405   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4406 
4407   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4408   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4409   // in the subscript position. As a result, we need to derive the array base
4410   // and index from the expression types.
4411   Expr *BaseExpr, *IndexExpr;
4412   QualType ResultType;
4413   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4414     BaseExpr = LHSExp;
4415     IndexExpr = RHSExp;
4416     ResultType = Context.DependentTy;
4417   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4418     BaseExpr = LHSExp;
4419     IndexExpr = RHSExp;
4420     ResultType = PTy->getPointeeType();
4421   } else if (const ObjCObjectPointerType *PTy =
4422                LHSTy->getAs<ObjCObjectPointerType>()) {
4423     BaseExpr = LHSExp;
4424     IndexExpr = RHSExp;
4425 
4426     // Use custom logic if this should be the pseudo-object subscript
4427     // expression.
4428     if (!LangOpts.isSubscriptPointerArithmetic())
4429       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4430                                           nullptr);
4431 
4432     ResultType = PTy->getPointeeType();
4433   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4434      // Handle the uncommon case of "123[Ptr]".
4435     BaseExpr = RHSExp;
4436     IndexExpr = LHSExp;
4437     ResultType = PTy->getPointeeType();
4438   } else if (const ObjCObjectPointerType *PTy =
4439                RHSTy->getAs<ObjCObjectPointerType>()) {
4440      // Handle the uncommon case of "123[Ptr]".
4441     BaseExpr = RHSExp;
4442     IndexExpr = LHSExp;
4443     ResultType = PTy->getPointeeType();
4444     if (!LangOpts.isSubscriptPointerArithmetic()) {
4445       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4446         << ResultType << BaseExpr->getSourceRange();
4447       return ExprError();
4448     }
4449   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4450     BaseExpr = LHSExp;    // vectors: V[123]
4451     IndexExpr = RHSExp;
4452     VK = LHSExp->getValueKind();
4453     if (VK != VK_RValue)
4454       OK = OK_VectorComponent;
4455 
4456     ResultType = VTy->getElementType();
4457     QualType BaseType = BaseExpr->getType();
4458     Qualifiers BaseQuals = BaseType.getQualifiers();
4459     Qualifiers MemberQuals = ResultType.getQualifiers();
4460     Qualifiers Combined = BaseQuals + MemberQuals;
4461     if (Combined != MemberQuals)
4462       ResultType = Context.getQualifiedType(ResultType, Combined);
4463   } else if (LHSTy->isArrayType()) {
4464     // If we see an array that wasn't promoted by
4465     // DefaultFunctionArrayLvalueConversion, it must be an array that
4466     // wasn't promoted because of the C90 rule that doesn't
4467     // allow promoting non-lvalue arrays.  Warn, then
4468     // force the promotion here.
4469     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4470         LHSExp->getSourceRange();
4471     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4472                                CK_ArrayToPointerDecay).get();
4473     LHSTy = LHSExp->getType();
4474 
4475     BaseExpr = LHSExp;
4476     IndexExpr = RHSExp;
4477     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4478   } else if (RHSTy->isArrayType()) {
4479     // Same as previous, except for 123[f().a] case
4480     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4481         RHSExp->getSourceRange();
4482     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4483                                CK_ArrayToPointerDecay).get();
4484     RHSTy = RHSExp->getType();
4485 
4486     BaseExpr = RHSExp;
4487     IndexExpr = LHSExp;
4488     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4489   } else {
4490     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4491        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4492   }
4493   // C99 6.5.2.1p1
4494   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4495     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4496                      << IndexExpr->getSourceRange());
4497 
4498   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4499        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4500          && !IndexExpr->isTypeDependent())
4501     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4502 
4503   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4504   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4505   // type. Note that Functions are not objects, and that (in C99 parlance)
4506   // incomplete types are not object types.
4507   if (ResultType->isFunctionType()) {
4508     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4509       << ResultType << BaseExpr->getSourceRange();
4510     return ExprError();
4511   }
4512 
4513   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4514     // GNU extension: subscripting on pointer to void
4515     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4516       << BaseExpr->getSourceRange();
4517 
4518     // C forbids expressions of unqualified void type from being l-values.
4519     // See IsCForbiddenLValueType.
4520     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4521   } else if (!ResultType->isDependentType() &&
4522       RequireCompleteType(LLoc, ResultType,
4523                           diag::err_subscript_incomplete_type, BaseExpr))
4524     return ExprError();
4525 
4526   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4527          !ResultType.isCForbiddenLValueType());
4528 
4529   return new (Context)
4530       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4531 }
4532 
4533 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4534                                   ParmVarDecl *Param) {
4535   if (Param->hasUnparsedDefaultArg()) {
4536     Diag(CallLoc,
4537          diag::err_use_of_default_argument_to_function_declared_later) <<
4538       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4539     Diag(UnparsedDefaultArgLocs[Param],
4540          diag::note_default_argument_declared_here);
4541     return true;
4542   }
4543 
4544   if (Param->hasUninstantiatedDefaultArg()) {
4545     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4546 
4547     EnterExpressionEvaluationContext EvalContext(
4548         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4549 
4550     // Instantiate the expression.
4551     //
4552     // FIXME: Pass in a correct Pattern argument, otherwise
4553     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4554     //
4555     // template<typename T>
4556     // struct A {
4557     //   static int FooImpl();
4558     //
4559     //   template<typename Tp>
4560     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4561     //   // template argument list [[T], [Tp]], should be [[Tp]].
4562     //   friend A<Tp> Foo(int a);
4563     // };
4564     //
4565     // template<typename T>
4566     // A<T> Foo(int a = A<T>::FooImpl());
4567     MultiLevelTemplateArgumentList MutiLevelArgList
4568       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4569 
4570     InstantiatingTemplate Inst(*this, CallLoc, Param,
4571                                MutiLevelArgList.getInnermost());
4572     if (Inst.isInvalid())
4573       return true;
4574     if (Inst.isAlreadyInstantiating()) {
4575       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4576       Param->setInvalidDecl();
4577       return true;
4578     }
4579 
4580     ExprResult Result;
4581     {
4582       // C++ [dcl.fct.default]p5:
4583       //   The names in the [default argument] expression are bound, and
4584       //   the semantic constraints are checked, at the point where the
4585       //   default argument expression appears.
4586       ContextRAII SavedContext(*this, FD);
4587       LocalInstantiationScope Local(*this);
4588       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4589                                 /*DirectInit*/false);
4590     }
4591     if (Result.isInvalid())
4592       return true;
4593 
4594     // Check the expression as an initializer for the parameter.
4595     InitializedEntity Entity
4596       = InitializedEntity::InitializeParameter(Context, Param);
4597     InitializationKind Kind
4598       = InitializationKind::CreateCopy(Param->getLocation(),
4599              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4600     Expr *ResultE = Result.getAs<Expr>();
4601 
4602     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4603     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4604     if (Result.isInvalid())
4605       return true;
4606 
4607     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4608                                  Param->getOuterLocStart());
4609     if (Result.isInvalid())
4610       return true;
4611 
4612     // Remember the instantiated default argument.
4613     Param->setDefaultArg(Result.getAs<Expr>());
4614     if (ASTMutationListener *L = getASTMutationListener()) {
4615       L->DefaultArgumentInstantiated(Param);
4616     }
4617   }
4618 
4619   // If the default argument expression is not set yet, we are building it now.
4620   if (!Param->hasInit()) {
4621     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4622     Param->setInvalidDecl();
4623     return true;
4624   }
4625 
4626   // If the default expression creates temporaries, we need to
4627   // push them to the current stack of expression temporaries so they'll
4628   // be properly destroyed.
4629   // FIXME: We should really be rebuilding the default argument with new
4630   // bound temporaries; see the comment in PR5810.
4631   // We don't need to do that with block decls, though, because
4632   // blocks in default argument expression can never capture anything.
4633   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4634     // Set the "needs cleanups" bit regardless of whether there are
4635     // any explicit objects.
4636     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4637 
4638     // Append all the objects to the cleanup list.  Right now, this
4639     // should always be a no-op, because blocks in default argument
4640     // expressions should never be able to capture anything.
4641     assert(!Init->getNumObjects() &&
4642            "default argument expression has capturing blocks?");
4643   }
4644 
4645   // We already type-checked the argument, so we know it works.
4646   // Just mark all of the declarations in this potentially-evaluated expression
4647   // as being "referenced".
4648   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4649                                    /*SkipLocalVariables=*/true);
4650   return false;
4651 }
4652 
4653 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4654                                         FunctionDecl *FD, ParmVarDecl *Param) {
4655   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4656     return ExprError();
4657   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4658 }
4659 
4660 Sema::VariadicCallType
4661 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4662                           Expr *Fn) {
4663   if (Proto && Proto->isVariadic()) {
4664     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4665       return VariadicConstructor;
4666     else if (Fn && Fn->getType()->isBlockPointerType())
4667       return VariadicBlock;
4668     else if (FDecl) {
4669       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4670         if (Method->isInstance())
4671           return VariadicMethod;
4672     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4673       return VariadicMethod;
4674     return VariadicFunction;
4675   }
4676   return VariadicDoesNotApply;
4677 }
4678 
4679 namespace {
4680 class FunctionCallCCC : public FunctionCallFilterCCC {
4681 public:
4682   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4683                   unsigned NumArgs, MemberExpr *ME)
4684       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4685         FunctionName(FuncName) {}
4686 
4687   bool ValidateCandidate(const TypoCorrection &candidate) override {
4688     if (!candidate.getCorrectionSpecifier() ||
4689         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4690       return false;
4691     }
4692 
4693     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4694   }
4695 
4696 private:
4697   const IdentifierInfo *const FunctionName;
4698 };
4699 }
4700 
4701 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4702                                                FunctionDecl *FDecl,
4703                                                ArrayRef<Expr *> Args) {
4704   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4705   DeclarationName FuncName = FDecl->getDeclName();
4706   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4707 
4708   if (TypoCorrection Corrected = S.CorrectTypo(
4709           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4710           S.getScopeForContext(S.CurContext), nullptr,
4711           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4712                                              Args.size(), ME),
4713           Sema::CTK_ErrorRecovery)) {
4714     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4715       if (Corrected.isOverloaded()) {
4716         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4717         OverloadCandidateSet::iterator Best;
4718         for (NamedDecl *CD : Corrected) {
4719           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4720             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4721                                    OCS);
4722         }
4723         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4724         case OR_Success:
4725           ND = Best->FoundDecl;
4726           Corrected.setCorrectionDecl(ND);
4727           break;
4728         default:
4729           break;
4730         }
4731       }
4732       ND = ND->getUnderlyingDecl();
4733       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4734         return Corrected;
4735     }
4736   }
4737   return TypoCorrection();
4738 }
4739 
4740 /// ConvertArgumentsForCall - Converts the arguments specified in
4741 /// Args/NumArgs to the parameter types of the function FDecl with
4742 /// function prototype Proto. Call is the call expression itself, and
4743 /// Fn is the function expression. For a C++ member function, this
4744 /// routine does not attempt to convert the object argument. Returns
4745 /// true if the call is ill-formed.
4746 bool
4747 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4748                               FunctionDecl *FDecl,
4749                               const FunctionProtoType *Proto,
4750                               ArrayRef<Expr *> Args,
4751                               SourceLocation RParenLoc,
4752                               bool IsExecConfig) {
4753   // Bail out early if calling a builtin with custom typechecking.
4754   if (FDecl)
4755     if (unsigned ID = FDecl->getBuiltinID())
4756       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4757         return false;
4758 
4759   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4760   // assignment, to the types of the corresponding parameter, ...
4761   unsigned NumParams = Proto->getNumParams();
4762   bool Invalid = false;
4763   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4764   unsigned FnKind = Fn->getType()->isBlockPointerType()
4765                        ? 1 /* block */
4766                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4767                                        : 0 /* function */);
4768 
4769   // If too few arguments are available (and we don't have default
4770   // arguments for the remaining parameters), don't make the call.
4771   if (Args.size() < NumParams) {
4772     if (Args.size() < MinArgs) {
4773       TypoCorrection TC;
4774       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4775         unsigned diag_id =
4776             MinArgs == NumParams && !Proto->isVariadic()
4777                 ? diag::err_typecheck_call_too_few_args_suggest
4778                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4779         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4780                                         << static_cast<unsigned>(Args.size())
4781                                         << TC.getCorrectionRange());
4782       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4783         Diag(RParenLoc,
4784              MinArgs == NumParams && !Proto->isVariadic()
4785                  ? diag::err_typecheck_call_too_few_args_one
4786                  : diag::err_typecheck_call_too_few_args_at_least_one)
4787             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4788       else
4789         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4790                             ? diag::err_typecheck_call_too_few_args
4791                             : diag::err_typecheck_call_too_few_args_at_least)
4792             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4793             << Fn->getSourceRange();
4794 
4795       // Emit the location of the prototype.
4796       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4797         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4798           << FDecl;
4799 
4800       return true;
4801     }
4802     Call->setNumArgs(Context, NumParams);
4803   }
4804 
4805   // If too many are passed and not variadic, error on the extras and drop
4806   // them.
4807   if (Args.size() > NumParams) {
4808     if (!Proto->isVariadic()) {
4809       TypoCorrection TC;
4810       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4811         unsigned diag_id =
4812             MinArgs == NumParams && !Proto->isVariadic()
4813                 ? diag::err_typecheck_call_too_many_args_suggest
4814                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4815         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4816                                         << static_cast<unsigned>(Args.size())
4817                                         << TC.getCorrectionRange());
4818       } else if (NumParams == 1 && FDecl &&
4819                  FDecl->getParamDecl(0)->getDeclName())
4820         Diag(Args[NumParams]->getLocStart(),
4821              MinArgs == NumParams
4822                  ? diag::err_typecheck_call_too_many_args_one
4823                  : diag::err_typecheck_call_too_many_args_at_most_one)
4824             << FnKind << FDecl->getParamDecl(0)
4825             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4826             << SourceRange(Args[NumParams]->getLocStart(),
4827                            Args.back()->getLocEnd());
4828       else
4829         Diag(Args[NumParams]->getLocStart(),
4830              MinArgs == NumParams
4831                  ? diag::err_typecheck_call_too_many_args
4832                  : diag::err_typecheck_call_too_many_args_at_most)
4833             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4834             << Fn->getSourceRange()
4835             << SourceRange(Args[NumParams]->getLocStart(),
4836                            Args.back()->getLocEnd());
4837 
4838       // Emit the location of the prototype.
4839       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4840         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4841           << FDecl;
4842 
4843       // This deletes the extra arguments.
4844       Call->setNumArgs(Context, NumParams);
4845       return true;
4846     }
4847   }
4848   SmallVector<Expr *, 8> AllArgs;
4849   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4850 
4851   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4852                                    Proto, 0, Args, AllArgs, CallType);
4853   if (Invalid)
4854     return true;
4855   unsigned TotalNumArgs = AllArgs.size();
4856   for (unsigned i = 0; i < TotalNumArgs; ++i)
4857     Call->setArg(i, AllArgs[i]);
4858 
4859   return false;
4860 }
4861 
4862 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4863                                   const FunctionProtoType *Proto,
4864                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4865                                   SmallVectorImpl<Expr *> &AllArgs,
4866                                   VariadicCallType CallType, bool AllowExplicit,
4867                                   bool IsListInitialization) {
4868   unsigned NumParams = Proto->getNumParams();
4869   bool Invalid = false;
4870   size_t ArgIx = 0;
4871   // Continue to check argument types (even if we have too few/many args).
4872   for (unsigned i = FirstParam; i < NumParams; i++) {
4873     QualType ProtoArgType = Proto->getParamType(i);
4874 
4875     Expr *Arg;
4876     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4877     if (ArgIx < Args.size()) {
4878       Arg = Args[ArgIx++];
4879 
4880       if (RequireCompleteType(Arg->getLocStart(),
4881                               ProtoArgType,
4882                               diag::err_call_incomplete_argument, Arg))
4883         return true;
4884 
4885       // Strip the unbridged-cast placeholder expression off, if applicable.
4886       bool CFAudited = false;
4887       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4888           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4889           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4890         Arg = stripARCUnbridgedCast(Arg);
4891       else if (getLangOpts().ObjCAutoRefCount &&
4892                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4893                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4894         CFAudited = true;
4895 
4896       if (Proto->getExtParameterInfo(i).isNoEscape())
4897         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4898           BE->getBlockDecl()->setDoesNotEscape();
4899 
4900       InitializedEntity Entity =
4901           Param ? InitializedEntity::InitializeParameter(Context, Param,
4902                                                          ProtoArgType)
4903                 : InitializedEntity::InitializeParameter(
4904                       Context, ProtoArgType, Proto->isParamConsumed(i));
4905 
4906       // Remember that parameter belongs to a CF audited API.
4907       if (CFAudited)
4908         Entity.setParameterCFAudited();
4909 
4910       ExprResult ArgE = PerformCopyInitialization(
4911           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4912       if (ArgE.isInvalid())
4913         return true;
4914 
4915       Arg = ArgE.getAs<Expr>();
4916     } else {
4917       assert(Param && "can't use default arguments without a known callee");
4918 
4919       ExprResult ArgExpr =
4920         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4921       if (ArgExpr.isInvalid())
4922         return true;
4923 
4924       Arg = ArgExpr.getAs<Expr>();
4925     }
4926 
4927     // Check for array bounds violations for each argument to the call. This
4928     // check only triggers warnings when the argument isn't a more complex Expr
4929     // with its own checking, such as a BinaryOperator.
4930     CheckArrayAccess(Arg);
4931 
4932     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4933     CheckStaticArrayArgument(CallLoc, Param, Arg);
4934 
4935     AllArgs.push_back(Arg);
4936   }
4937 
4938   // If this is a variadic call, handle args passed through "...".
4939   if (CallType != VariadicDoesNotApply) {
4940     // Assume that extern "C" functions with variadic arguments that
4941     // return __unknown_anytype aren't *really* variadic.
4942     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4943         FDecl->isExternC()) {
4944       for (Expr *A : Args.slice(ArgIx)) {
4945         QualType paramType; // ignored
4946         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4947         Invalid |= arg.isInvalid();
4948         AllArgs.push_back(arg.get());
4949       }
4950 
4951     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4952     } else {
4953       for (Expr *A : Args.slice(ArgIx)) {
4954         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4955         Invalid |= Arg.isInvalid();
4956         AllArgs.push_back(Arg.get());
4957       }
4958     }
4959 
4960     // Check for array bounds violations.
4961     for (Expr *A : Args.slice(ArgIx))
4962       CheckArrayAccess(A);
4963   }
4964   return Invalid;
4965 }
4966 
4967 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4968   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4969   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4970     TL = DTL.getOriginalLoc();
4971   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4972     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4973       << ATL.getLocalSourceRange();
4974 }
4975 
4976 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4977 /// array parameter, check that it is non-null, and that if it is formed by
4978 /// array-to-pointer decay, the underlying array is sufficiently large.
4979 ///
4980 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4981 /// array type derivation, then for each call to the function, the value of the
4982 /// corresponding actual argument shall provide access to the first element of
4983 /// an array with at least as many elements as specified by the size expression.
4984 void
4985 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4986                                ParmVarDecl *Param,
4987                                const Expr *ArgExpr) {
4988   // Static array parameters are not supported in C++.
4989   if (!Param || getLangOpts().CPlusPlus)
4990     return;
4991 
4992   QualType OrigTy = Param->getOriginalType();
4993 
4994   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4995   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4996     return;
4997 
4998   if (ArgExpr->isNullPointerConstant(Context,
4999                                      Expr::NPC_NeverValueDependent)) {
5000     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5001     DiagnoseCalleeStaticArrayParam(*this, Param);
5002     return;
5003   }
5004 
5005   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5006   if (!CAT)
5007     return;
5008 
5009   const ConstantArrayType *ArgCAT =
5010     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5011   if (!ArgCAT)
5012     return;
5013 
5014   if (ArgCAT->getSize().ult(CAT->getSize())) {
5015     Diag(CallLoc, diag::warn_static_array_too_small)
5016       << ArgExpr->getSourceRange()
5017       << (unsigned) ArgCAT->getSize().getZExtValue()
5018       << (unsigned) CAT->getSize().getZExtValue();
5019     DiagnoseCalleeStaticArrayParam(*this, Param);
5020   }
5021 }
5022 
5023 /// Given a function expression of unknown-any type, try to rebuild it
5024 /// to have a function type.
5025 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5026 
5027 /// Is the given type a placeholder that we need to lower out
5028 /// immediately during argument processing?
5029 static bool isPlaceholderToRemoveAsArg(QualType type) {
5030   // Placeholders are never sugared.
5031   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5032   if (!placeholder) return false;
5033 
5034   switch (placeholder->getKind()) {
5035   // Ignore all the non-placeholder types.
5036 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5037   case BuiltinType::Id:
5038 #include "clang/Basic/OpenCLImageTypes.def"
5039 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5040 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5041 #include "clang/AST/BuiltinTypes.def"
5042     return false;
5043 
5044   // We cannot lower out overload sets; they might validly be resolved
5045   // by the call machinery.
5046   case BuiltinType::Overload:
5047     return false;
5048 
5049   // Unbridged casts in ARC can be handled in some call positions and
5050   // should be left in place.
5051   case BuiltinType::ARCUnbridgedCast:
5052     return false;
5053 
5054   // Pseudo-objects should be converted as soon as possible.
5055   case BuiltinType::PseudoObject:
5056     return true;
5057 
5058   // The debugger mode could theoretically but currently does not try
5059   // to resolve unknown-typed arguments based on known parameter types.
5060   case BuiltinType::UnknownAny:
5061     return true;
5062 
5063   // These are always invalid as call arguments and should be reported.
5064   case BuiltinType::BoundMember:
5065   case BuiltinType::BuiltinFn:
5066   case BuiltinType::OMPArraySection:
5067     return true;
5068 
5069   }
5070   llvm_unreachable("bad builtin type kind");
5071 }
5072 
5073 /// Check an argument list for placeholders that we won't try to
5074 /// handle later.
5075 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5076   // Apply this processing to all the arguments at once instead of
5077   // dying at the first failure.
5078   bool hasInvalid = false;
5079   for (size_t i = 0, e = args.size(); i != e; i++) {
5080     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5081       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5082       if (result.isInvalid()) hasInvalid = true;
5083       else args[i] = result.get();
5084     } else if (hasInvalid) {
5085       (void)S.CorrectDelayedTyposInExpr(args[i]);
5086     }
5087   }
5088   return hasInvalid;
5089 }
5090 
5091 /// If a builtin function has a pointer argument with no explicit address
5092 /// space, then it should be able to accept a pointer to any address
5093 /// space as input.  In order to do this, we need to replace the
5094 /// standard builtin declaration with one that uses the same address space
5095 /// as the call.
5096 ///
5097 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5098 ///                  it does not contain any pointer arguments without
5099 ///                  an address space qualifer.  Otherwise the rewritten
5100 ///                  FunctionDecl is returned.
5101 /// TODO: Handle pointer return types.
5102 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5103                                                 const FunctionDecl *FDecl,
5104                                                 MultiExprArg ArgExprs) {
5105 
5106   QualType DeclType = FDecl->getType();
5107   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5108 
5109   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5110       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5111     return nullptr;
5112 
5113   bool NeedsNewDecl = false;
5114   unsigned i = 0;
5115   SmallVector<QualType, 8> OverloadParams;
5116 
5117   for (QualType ParamType : FT->param_types()) {
5118 
5119     // Convert array arguments to pointer to simplify type lookup.
5120     ExprResult ArgRes =
5121         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5122     if (ArgRes.isInvalid())
5123       return nullptr;
5124     Expr *Arg = ArgRes.get();
5125     QualType ArgType = Arg->getType();
5126     if (!ParamType->isPointerType() ||
5127         ParamType.getQualifiers().hasAddressSpace() ||
5128         !ArgType->isPointerType() ||
5129         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5130       OverloadParams.push_back(ParamType);
5131       continue;
5132     }
5133 
5134     NeedsNewDecl = true;
5135     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5136 
5137     QualType PointeeType = ParamType->getPointeeType();
5138     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5139     OverloadParams.push_back(Context.getPointerType(PointeeType));
5140   }
5141 
5142   if (!NeedsNewDecl)
5143     return nullptr;
5144 
5145   FunctionProtoType::ExtProtoInfo EPI;
5146   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5147                                                 OverloadParams, EPI);
5148   DeclContext *Parent = Context.getTranslationUnitDecl();
5149   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5150                                                     FDecl->getLocation(),
5151                                                     FDecl->getLocation(),
5152                                                     FDecl->getIdentifier(),
5153                                                     OverloadTy,
5154                                                     /*TInfo=*/nullptr,
5155                                                     SC_Extern, false,
5156                                                     /*hasPrototype=*/true);
5157   SmallVector<ParmVarDecl*, 16> Params;
5158   FT = cast<FunctionProtoType>(OverloadTy);
5159   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5160     QualType ParamType = FT->getParamType(i);
5161     ParmVarDecl *Parm =
5162         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5163                                 SourceLocation(), nullptr, ParamType,
5164                                 /*TInfo=*/nullptr, SC_None, nullptr);
5165     Parm->setScopeInfo(0, i);
5166     Params.push_back(Parm);
5167   }
5168   OverloadDecl->setParams(Params);
5169   return OverloadDecl;
5170 }
5171 
5172 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5173                                     FunctionDecl *Callee,
5174                                     MultiExprArg ArgExprs) {
5175   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5176   // similar attributes) really don't like it when functions are called with an
5177   // invalid number of args.
5178   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5179                          /*PartialOverloading=*/false) &&
5180       !Callee->isVariadic())
5181     return;
5182   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5183     return;
5184 
5185   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5186     S.Diag(Fn->getLocStart(),
5187            isa<CXXMethodDecl>(Callee)
5188                ? diag::err_ovl_no_viable_member_function_in_call
5189                : diag::err_ovl_no_viable_function_in_call)
5190         << Callee << Callee->getSourceRange();
5191     S.Diag(Callee->getLocation(),
5192            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5193         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5194     return;
5195   }
5196 }
5197 
5198 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5199     const UnresolvedMemberExpr *const UME, Sema &S) {
5200 
5201   const auto GetFunctionLevelDCIfCXXClass =
5202       [](Sema &S) -> const CXXRecordDecl * {
5203     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5204     if (!DC || !DC->getParent())
5205       return nullptr;
5206 
5207     // If the call to some member function was made from within a member
5208     // function body 'M' return return 'M's parent.
5209     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5210       return MD->getParent()->getCanonicalDecl();
5211     // else the call was made from within a default member initializer of a
5212     // class, so return the class.
5213     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5214       return RD->getCanonicalDecl();
5215     return nullptr;
5216   };
5217   // If our DeclContext is neither a member function nor a class (in the
5218   // case of a lambda in a default member initializer), we can't have an
5219   // enclosing 'this'.
5220 
5221   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5222   if (!CurParentClass)
5223     return false;
5224 
5225   // The naming class for implicit member functions call is the class in which
5226   // name lookup starts.
5227   const CXXRecordDecl *const NamingClass =
5228       UME->getNamingClass()->getCanonicalDecl();
5229   assert(NamingClass && "Must have naming class even for implicit access");
5230 
5231   // If the unresolved member functions were found in a 'naming class' that is
5232   // related (either the same or derived from) to the class that contains the
5233   // member function that itself contained the implicit member access.
5234 
5235   return CurParentClass == NamingClass ||
5236          CurParentClass->isDerivedFrom(NamingClass);
5237 }
5238 
5239 static void
5240 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5241     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5242 
5243   if (!UME)
5244     return;
5245 
5246   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5247   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5248   // already been captured, or if this is an implicit member function call (if
5249   // it isn't, an attempt to capture 'this' should already have been made).
5250   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5251       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5252     return;
5253 
5254   // Check if the naming class in which the unresolved members were found is
5255   // related (same as or is a base of) to the enclosing class.
5256 
5257   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5258     return;
5259 
5260 
5261   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5262   // If the enclosing function is not dependent, then this lambda is
5263   // capture ready, so if we can capture this, do so.
5264   if (!EnclosingFunctionCtx->isDependentContext()) {
5265     // If the current lambda and all enclosing lambdas can capture 'this' -
5266     // then go ahead and capture 'this' (since our unresolved overload set
5267     // contains at least one non-static member function).
5268     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5269       S.CheckCXXThisCapture(CallLoc);
5270   } else if (S.CurContext->isDependentContext()) {
5271     // ... since this is an implicit member reference, that might potentially
5272     // involve a 'this' capture, mark 'this' for potential capture in
5273     // enclosing lambdas.
5274     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5275       CurLSI->addPotentialThisCapture(CallLoc);
5276   }
5277 }
5278 
5279 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5280 /// This provides the location of the left/right parens and a list of comma
5281 /// locations.
5282 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5283                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5284                                Expr *ExecConfig, bool IsExecConfig) {
5285   // Since this might be a postfix expression, get rid of ParenListExprs.
5286   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5287   if (Result.isInvalid()) return ExprError();
5288   Fn = Result.get();
5289 
5290   if (checkArgsForPlaceholders(*this, ArgExprs))
5291     return ExprError();
5292 
5293   if (getLangOpts().CPlusPlus) {
5294     // If this is a pseudo-destructor expression, build the call immediately.
5295     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5296       if (!ArgExprs.empty()) {
5297         // Pseudo-destructor calls should not have any arguments.
5298         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5299             << FixItHint::CreateRemoval(
5300                    SourceRange(ArgExprs.front()->getLocStart(),
5301                                ArgExprs.back()->getLocEnd()));
5302       }
5303 
5304       return new (Context)
5305           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5306     }
5307     if (Fn->getType() == Context.PseudoObjectTy) {
5308       ExprResult result = CheckPlaceholderExpr(Fn);
5309       if (result.isInvalid()) return ExprError();
5310       Fn = result.get();
5311     }
5312 
5313     // Determine whether this is a dependent call inside a C++ template,
5314     // in which case we won't do any semantic analysis now.
5315     bool Dependent = false;
5316     if (Fn->isTypeDependent())
5317       Dependent = true;
5318     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5319       Dependent = true;
5320 
5321     if (Dependent) {
5322       if (ExecConfig) {
5323         return new (Context) CUDAKernelCallExpr(
5324             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5325             Context.DependentTy, VK_RValue, RParenLoc);
5326       } else {
5327 
5328        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5329             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5330             Fn->getLocStart());
5331 
5332         return new (Context) CallExpr(
5333             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5334       }
5335     }
5336 
5337     // Determine whether this is a call to an object (C++ [over.call.object]).
5338     if (Fn->getType()->isRecordType())
5339       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5340                                           RParenLoc);
5341 
5342     if (Fn->getType() == Context.UnknownAnyTy) {
5343       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5344       if (result.isInvalid()) return ExprError();
5345       Fn = result.get();
5346     }
5347 
5348     if (Fn->getType() == Context.BoundMemberTy) {
5349       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5350                                        RParenLoc);
5351     }
5352   }
5353 
5354   // Check for overloaded calls.  This can happen even in C due to extensions.
5355   if (Fn->getType() == Context.OverloadTy) {
5356     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5357 
5358     // We aren't supposed to apply this logic if there's an '&' involved.
5359     if (!find.HasFormOfMemberPointer) {
5360       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5361         return new (Context) CallExpr(
5362             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5363       OverloadExpr *ovl = find.Expression;
5364       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5365         return BuildOverloadedCallExpr(
5366             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5367             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5368       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5369                                        RParenLoc);
5370     }
5371   }
5372 
5373   // If we're directly calling a function, get the appropriate declaration.
5374   if (Fn->getType() == Context.UnknownAnyTy) {
5375     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5376     if (result.isInvalid()) return ExprError();
5377     Fn = result.get();
5378   }
5379 
5380   Expr *NakedFn = Fn->IgnoreParens();
5381 
5382   bool CallingNDeclIndirectly = false;
5383   NamedDecl *NDecl = nullptr;
5384   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5385     if (UnOp->getOpcode() == UO_AddrOf) {
5386       CallingNDeclIndirectly = true;
5387       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5388     }
5389   }
5390 
5391   if (isa<DeclRefExpr>(NakedFn)) {
5392     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5393 
5394     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5395     if (FDecl && FDecl->getBuiltinID()) {
5396       // Rewrite the function decl for this builtin by replacing parameters
5397       // with no explicit address space with the address space of the arguments
5398       // in ArgExprs.
5399       if ((FDecl =
5400                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5401         NDecl = FDecl;
5402         Fn = DeclRefExpr::Create(
5403             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5404             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5405       }
5406     }
5407   } else if (isa<MemberExpr>(NakedFn))
5408     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5409 
5410   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5411     if (CallingNDeclIndirectly &&
5412         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5413                                            Fn->getLocStart()))
5414       return ExprError();
5415 
5416     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5417       return ExprError();
5418 
5419     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5420   }
5421 
5422   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5423                                ExecConfig, IsExecConfig);
5424 }
5425 
5426 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5427 ///
5428 /// __builtin_astype( value, dst type )
5429 ///
5430 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5431                                  SourceLocation BuiltinLoc,
5432                                  SourceLocation RParenLoc) {
5433   ExprValueKind VK = VK_RValue;
5434   ExprObjectKind OK = OK_Ordinary;
5435   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5436   QualType SrcTy = E->getType();
5437   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5438     return ExprError(Diag(BuiltinLoc,
5439                           diag::err_invalid_astype_of_different_size)
5440                      << DstTy
5441                      << SrcTy
5442                      << E->getSourceRange());
5443   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5444 }
5445 
5446 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5447 /// provided arguments.
5448 ///
5449 /// __builtin_convertvector( value, dst type )
5450 ///
5451 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5452                                         SourceLocation BuiltinLoc,
5453                                         SourceLocation RParenLoc) {
5454   TypeSourceInfo *TInfo;
5455   GetTypeFromParser(ParsedDestTy, &TInfo);
5456   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5457 }
5458 
5459 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5460 /// i.e. an expression not of \p OverloadTy.  The expression should
5461 /// unary-convert to an expression of function-pointer or
5462 /// block-pointer type.
5463 ///
5464 /// \param NDecl the declaration being called, if available
5465 ExprResult
5466 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5467                             SourceLocation LParenLoc,
5468                             ArrayRef<Expr *> Args,
5469                             SourceLocation RParenLoc,
5470                             Expr *Config, bool IsExecConfig) {
5471   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5472   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5473 
5474   // Functions with 'interrupt' attribute cannot be called directly.
5475   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5476     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5477     return ExprError();
5478   }
5479 
5480   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5481   // so there's some risk when calling out to non-interrupt handler functions
5482   // that the callee might not preserve them. This is easy to diagnose here,
5483   // but can be very challenging to debug.
5484   if (auto *Caller = getCurFunctionDecl())
5485     if (Caller->hasAttr<ARMInterruptAttr>()) {
5486       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5487       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5488         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5489     }
5490 
5491   // Promote the function operand.
5492   // We special-case function promotion here because we only allow promoting
5493   // builtin functions to function pointers in the callee of a call.
5494   ExprResult Result;
5495   if (BuiltinID &&
5496       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5497     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5498                                CK_BuiltinFnToFnPtr).get();
5499   } else {
5500     Result = CallExprUnaryConversions(Fn);
5501   }
5502   if (Result.isInvalid())
5503     return ExprError();
5504   Fn = Result.get();
5505 
5506   // Make the call expr early, before semantic checks.  This guarantees cleanup
5507   // of arguments and function on error.
5508   CallExpr *TheCall;
5509   if (Config)
5510     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5511                                                cast<CallExpr>(Config), Args,
5512                                                Context.BoolTy, VK_RValue,
5513                                                RParenLoc);
5514   else
5515     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5516                                      VK_RValue, RParenLoc);
5517 
5518   if (!getLangOpts().CPlusPlus) {
5519     // C cannot always handle TypoExpr nodes in builtin calls and direct
5520     // function calls as their argument checking don't necessarily handle
5521     // dependent types properly, so make sure any TypoExprs have been
5522     // dealt with.
5523     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5524     if (!Result.isUsable()) return ExprError();
5525     TheCall = dyn_cast<CallExpr>(Result.get());
5526     if (!TheCall) return Result;
5527     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5528   }
5529 
5530   // Bail out early if calling a builtin with custom typechecking.
5531   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5532     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5533 
5534  retry:
5535   const FunctionType *FuncT;
5536   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5537     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5538     // have type pointer to function".
5539     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5540     if (!FuncT)
5541       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5542                          << Fn->getType() << Fn->getSourceRange());
5543   } else if (const BlockPointerType *BPT =
5544                Fn->getType()->getAs<BlockPointerType>()) {
5545     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5546   } else {
5547     // Handle calls to expressions of unknown-any type.
5548     if (Fn->getType() == Context.UnknownAnyTy) {
5549       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5550       if (rewrite.isInvalid()) return ExprError();
5551       Fn = rewrite.get();
5552       TheCall->setCallee(Fn);
5553       goto retry;
5554     }
5555 
5556     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5557       << Fn->getType() << Fn->getSourceRange());
5558   }
5559 
5560   if (getLangOpts().CUDA) {
5561     if (Config) {
5562       // CUDA: Kernel calls must be to global functions
5563       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5564         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5565             << FDecl << Fn->getSourceRange());
5566 
5567       // CUDA: Kernel function must have 'void' return type
5568       if (!FuncT->getReturnType()->isVoidType())
5569         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5570             << Fn->getType() << Fn->getSourceRange());
5571     } else {
5572       // CUDA: Calls to global functions must be configured
5573       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5574         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5575             << FDecl << Fn->getSourceRange());
5576     }
5577   }
5578 
5579   // Check for a valid return type
5580   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5581                           FDecl))
5582     return ExprError();
5583 
5584   // We know the result type of the call, set it.
5585   TheCall->setType(FuncT->getCallResultType(Context));
5586   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5587 
5588   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5589   if (Proto) {
5590     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5591                                 IsExecConfig))
5592       return ExprError();
5593   } else {
5594     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5595 
5596     if (FDecl) {
5597       // Check if we have too few/too many template arguments, based
5598       // on our knowledge of the function definition.
5599       const FunctionDecl *Def = nullptr;
5600       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5601         Proto = Def->getType()->getAs<FunctionProtoType>();
5602        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5603           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5604           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5605       }
5606 
5607       // If the function we're calling isn't a function prototype, but we have
5608       // a function prototype from a prior declaratiom, use that prototype.
5609       if (!FDecl->hasPrototype())
5610         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5611     }
5612 
5613     // Promote the arguments (C99 6.5.2.2p6).
5614     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5615       Expr *Arg = Args[i];
5616 
5617       if (Proto && i < Proto->getNumParams()) {
5618         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5619             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5620         ExprResult ArgE =
5621             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5622         if (ArgE.isInvalid())
5623           return true;
5624 
5625         Arg = ArgE.getAs<Expr>();
5626 
5627       } else {
5628         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5629 
5630         if (ArgE.isInvalid())
5631           return true;
5632 
5633         Arg = ArgE.getAs<Expr>();
5634       }
5635 
5636       if (RequireCompleteType(Arg->getLocStart(),
5637                               Arg->getType(),
5638                               diag::err_call_incomplete_argument, Arg))
5639         return ExprError();
5640 
5641       TheCall->setArg(i, Arg);
5642     }
5643   }
5644 
5645   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5646     if (!Method->isStatic())
5647       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5648         << Fn->getSourceRange());
5649 
5650   // Check for sentinels
5651   if (NDecl)
5652     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5653 
5654   // Do special checking on direct calls to functions.
5655   if (FDecl) {
5656     if (CheckFunctionCall(FDecl, TheCall, Proto))
5657       return ExprError();
5658 
5659     if (BuiltinID)
5660       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5661   } else if (NDecl) {
5662     if (CheckPointerCall(NDecl, TheCall, Proto))
5663       return ExprError();
5664   } else {
5665     if (CheckOtherCall(TheCall, Proto))
5666       return ExprError();
5667   }
5668 
5669   return MaybeBindToTemporary(TheCall);
5670 }
5671 
5672 ExprResult
5673 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5674                            SourceLocation RParenLoc, Expr *InitExpr) {
5675   assert(Ty && "ActOnCompoundLiteral(): missing type");
5676   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5677 
5678   TypeSourceInfo *TInfo;
5679   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5680   if (!TInfo)
5681     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5682 
5683   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5684 }
5685 
5686 ExprResult
5687 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5688                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5689   QualType literalType = TInfo->getType();
5690 
5691   if (literalType->isArrayType()) {
5692     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5693           diag::err_illegal_decl_array_incomplete_type,
5694           SourceRange(LParenLoc,
5695                       LiteralExpr->getSourceRange().getEnd())))
5696       return ExprError();
5697     if (literalType->isVariableArrayType())
5698       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5699         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5700   } else if (!literalType->isDependentType() &&
5701              RequireCompleteType(LParenLoc, literalType,
5702                diag::err_typecheck_decl_incomplete_type,
5703                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5704     return ExprError();
5705 
5706   InitializedEntity Entity
5707     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5708   InitializationKind Kind
5709     = InitializationKind::CreateCStyleCast(LParenLoc,
5710                                            SourceRange(LParenLoc, RParenLoc),
5711                                            /*InitList=*/true);
5712   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5713   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5714                                       &literalType);
5715   if (Result.isInvalid())
5716     return ExprError();
5717   LiteralExpr = Result.get();
5718 
5719   bool isFileScope = !CurContext->isFunctionOrMethod();
5720   if (isFileScope &&
5721       !LiteralExpr->isTypeDependent() &&
5722       !LiteralExpr->isValueDependent() &&
5723       !literalType->isDependentType()) { // 6.5.2.5p3
5724     if (CheckForConstantInitializer(LiteralExpr, literalType))
5725       return ExprError();
5726   }
5727 
5728   // In C, compound literals are l-values for some reason.
5729   // For GCC compatibility, in C++, file-scope array compound literals with
5730   // constant initializers are also l-values, and compound literals are
5731   // otherwise prvalues.
5732   //
5733   // (GCC also treats C++ list-initialized file-scope array prvalues with
5734   // constant initializers as l-values, but that's non-conforming, so we don't
5735   // follow it there.)
5736   //
5737   // FIXME: It would be better to handle the lvalue cases as materializing and
5738   // lifetime-extending a temporary object, but our materialized temporaries
5739   // representation only supports lifetime extension from a variable, not "out
5740   // of thin air".
5741   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5742   // is bound to the result of applying array-to-pointer decay to the compound
5743   // literal.
5744   // FIXME: GCC supports compound literals of reference type, which should
5745   // obviously have a value kind derived from the kind of reference involved.
5746   ExprValueKind VK =
5747       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5748           ? VK_RValue
5749           : VK_LValue;
5750 
5751   return MaybeBindToTemporary(
5752       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5753                                         VK, LiteralExpr, isFileScope));
5754 }
5755 
5756 ExprResult
5757 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5758                     SourceLocation RBraceLoc) {
5759   // Immediately handle non-overload placeholders.  Overloads can be
5760   // resolved contextually, but everything else here can't.
5761   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5762     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5763       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5764 
5765       // Ignore failures; dropping the entire initializer list because
5766       // of one failure would be terrible for indexing/etc.
5767       if (result.isInvalid()) continue;
5768 
5769       InitArgList[I] = result.get();
5770     }
5771   }
5772 
5773   // Semantic analysis for initializers is done by ActOnDeclarator() and
5774   // CheckInitializer() - it requires knowledge of the object being initialized.
5775 
5776   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5777                                                RBraceLoc);
5778   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5779   return E;
5780 }
5781 
5782 /// Do an explicit extend of the given block pointer if we're in ARC.
5783 void Sema::maybeExtendBlockObject(ExprResult &E) {
5784   assert(E.get()->getType()->isBlockPointerType());
5785   assert(E.get()->isRValue());
5786 
5787   // Only do this in an r-value context.
5788   if (!getLangOpts().ObjCAutoRefCount) return;
5789 
5790   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5791                                CK_ARCExtendBlockObject, E.get(),
5792                                /*base path*/ nullptr, VK_RValue);
5793   Cleanup.setExprNeedsCleanups(true);
5794 }
5795 
5796 /// Prepare a conversion of the given expression to an ObjC object
5797 /// pointer type.
5798 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5799   QualType type = E.get()->getType();
5800   if (type->isObjCObjectPointerType()) {
5801     return CK_BitCast;
5802   } else if (type->isBlockPointerType()) {
5803     maybeExtendBlockObject(E);
5804     return CK_BlockPointerToObjCPointerCast;
5805   } else {
5806     assert(type->isPointerType());
5807     return CK_CPointerToObjCPointerCast;
5808   }
5809 }
5810 
5811 /// Prepares for a scalar cast, performing all the necessary stages
5812 /// except the final cast and returning the kind required.
5813 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5814   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5815   // Also, callers should have filtered out the invalid cases with
5816   // pointers.  Everything else should be possible.
5817 
5818   QualType SrcTy = Src.get()->getType();
5819   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5820     return CK_NoOp;
5821 
5822   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5823   case Type::STK_MemberPointer:
5824     llvm_unreachable("member pointer type in C");
5825 
5826   case Type::STK_CPointer:
5827   case Type::STK_BlockPointer:
5828   case Type::STK_ObjCObjectPointer:
5829     switch (DestTy->getScalarTypeKind()) {
5830     case Type::STK_CPointer: {
5831       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5832       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5833       if (SrcAS != DestAS)
5834         return CK_AddressSpaceConversion;
5835       return CK_BitCast;
5836     }
5837     case Type::STK_BlockPointer:
5838       return (SrcKind == Type::STK_BlockPointer
5839                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5840     case Type::STK_ObjCObjectPointer:
5841       if (SrcKind == Type::STK_ObjCObjectPointer)
5842         return CK_BitCast;
5843       if (SrcKind == Type::STK_CPointer)
5844         return CK_CPointerToObjCPointerCast;
5845       maybeExtendBlockObject(Src);
5846       return CK_BlockPointerToObjCPointerCast;
5847     case Type::STK_Bool:
5848       return CK_PointerToBoolean;
5849     case Type::STK_Integral:
5850       return CK_PointerToIntegral;
5851     case Type::STK_Floating:
5852     case Type::STK_FloatingComplex:
5853     case Type::STK_IntegralComplex:
5854     case Type::STK_MemberPointer:
5855       llvm_unreachable("illegal cast from pointer");
5856     }
5857     llvm_unreachable("Should have returned before this");
5858 
5859   case Type::STK_Bool: // casting from bool is like casting from an integer
5860   case Type::STK_Integral:
5861     switch (DestTy->getScalarTypeKind()) {
5862     case Type::STK_CPointer:
5863     case Type::STK_ObjCObjectPointer:
5864     case Type::STK_BlockPointer:
5865       if (Src.get()->isNullPointerConstant(Context,
5866                                            Expr::NPC_ValueDependentIsNull))
5867         return CK_NullToPointer;
5868       return CK_IntegralToPointer;
5869     case Type::STK_Bool:
5870       return CK_IntegralToBoolean;
5871     case Type::STK_Integral:
5872       return CK_IntegralCast;
5873     case Type::STK_Floating:
5874       return CK_IntegralToFloating;
5875     case Type::STK_IntegralComplex:
5876       Src = ImpCastExprToType(Src.get(),
5877                       DestTy->castAs<ComplexType>()->getElementType(),
5878                       CK_IntegralCast);
5879       return CK_IntegralRealToComplex;
5880     case Type::STK_FloatingComplex:
5881       Src = ImpCastExprToType(Src.get(),
5882                       DestTy->castAs<ComplexType>()->getElementType(),
5883                       CK_IntegralToFloating);
5884       return CK_FloatingRealToComplex;
5885     case Type::STK_MemberPointer:
5886       llvm_unreachable("member pointer type in C");
5887     }
5888     llvm_unreachable("Should have returned before this");
5889 
5890   case Type::STK_Floating:
5891     switch (DestTy->getScalarTypeKind()) {
5892     case Type::STK_Floating:
5893       return CK_FloatingCast;
5894     case Type::STK_Bool:
5895       return CK_FloatingToBoolean;
5896     case Type::STK_Integral:
5897       return CK_FloatingToIntegral;
5898     case Type::STK_FloatingComplex:
5899       Src = ImpCastExprToType(Src.get(),
5900                               DestTy->castAs<ComplexType>()->getElementType(),
5901                               CK_FloatingCast);
5902       return CK_FloatingRealToComplex;
5903     case Type::STK_IntegralComplex:
5904       Src = ImpCastExprToType(Src.get(),
5905                               DestTy->castAs<ComplexType>()->getElementType(),
5906                               CK_FloatingToIntegral);
5907       return CK_IntegralRealToComplex;
5908     case Type::STK_CPointer:
5909     case Type::STK_ObjCObjectPointer:
5910     case Type::STK_BlockPointer:
5911       llvm_unreachable("valid float->pointer cast?");
5912     case Type::STK_MemberPointer:
5913       llvm_unreachable("member pointer type in C");
5914     }
5915     llvm_unreachable("Should have returned before this");
5916 
5917   case Type::STK_FloatingComplex:
5918     switch (DestTy->getScalarTypeKind()) {
5919     case Type::STK_FloatingComplex:
5920       return CK_FloatingComplexCast;
5921     case Type::STK_IntegralComplex:
5922       return CK_FloatingComplexToIntegralComplex;
5923     case Type::STK_Floating: {
5924       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5925       if (Context.hasSameType(ET, DestTy))
5926         return CK_FloatingComplexToReal;
5927       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5928       return CK_FloatingCast;
5929     }
5930     case Type::STK_Bool:
5931       return CK_FloatingComplexToBoolean;
5932     case Type::STK_Integral:
5933       Src = ImpCastExprToType(Src.get(),
5934                               SrcTy->castAs<ComplexType>()->getElementType(),
5935                               CK_FloatingComplexToReal);
5936       return CK_FloatingToIntegral;
5937     case Type::STK_CPointer:
5938     case Type::STK_ObjCObjectPointer:
5939     case Type::STK_BlockPointer:
5940       llvm_unreachable("valid complex float->pointer cast?");
5941     case Type::STK_MemberPointer:
5942       llvm_unreachable("member pointer type in C");
5943     }
5944     llvm_unreachable("Should have returned before this");
5945 
5946   case Type::STK_IntegralComplex:
5947     switch (DestTy->getScalarTypeKind()) {
5948     case Type::STK_FloatingComplex:
5949       return CK_IntegralComplexToFloatingComplex;
5950     case Type::STK_IntegralComplex:
5951       return CK_IntegralComplexCast;
5952     case Type::STK_Integral: {
5953       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5954       if (Context.hasSameType(ET, DestTy))
5955         return CK_IntegralComplexToReal;
5956       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5957       return CK_IntegralCast;
5958     }
5959     case Type::STK_Bool:
5960       return CK_IntegralComplexToBoolean;
5961     case Type::STK_Floating:
5962       Src = ImpCastExprToType(Src.get(),
5963                               SrcTy->castAs<ComplexType>()->getElementType(),
5964                               CK_IntegralComplexToReal);
5965       return CK_IntegralToFloating;
5966     case Type::STK_CPointer:
5967     case Type::STK_ObjCObjectPointer:
5968     case Type::STK_BlockPointer:
5969       llvm_unreachable("valid complex int->pointer cast?");
5970     case Type::STK_MemberPointer:
5971       llvm_unreachable("member pointer type in C");
5972     }
5973     llvm_unreachable("Should have returned before this");
5974   }
5975 
5976   llvm_unreachable("Unhandled scalar cast");
5977 }
5978 
5979 static bool breakDownVectorType(QualType type, uint64_t &len,
5980                                 QualType &eltType) {
5981   // Vectors are simple.
5982   if (const VectorType *vecType = type->getAs<VectorType>()) {
5983     len = vecType->getNumElements();
5984     eltType = vecType->getElementType();
5985     assert(eltType->isScalarType());
5986     return true;
5987   }
5988 
5989   // We allow lax conversion to and from non-vector types, but only if
5990   // they're real types (i.e. non-complex, non-pointer scalar types).
5991   if (!type->isRealType()) return false;
5992 
5993   len = 1;
5994   eltType = type;
5995   return true;
5996 }
5997 
5998 /// Are the two types lax-compatible vector types?  That is, given
5999 /// that one of them is a vector, do they have equal storage sizes,
6000 /// where the storage size is the number of elements times the element
6001 /// size?
6002 ///
6003 /// This will also return false if either of the types is neither a
6004 /// vector nor a real type.
6005 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6006   assert(destTy->isVectorType() || srcTy->isVectorType());
6007 
6008   // Disallow lax conversions between scalars and ExtVectors (these
6009   // conversions are allowed for other vector types because common headers
6010   // depend on them).  Most scalar OP ExtVector cases are handled by the
6011   // splat path anyway, which does what we want (convert, not bitcast).
6012   // What this rules out for ExtVectors is crazy things like char4*float.
6013   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6014   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6015 
6016   uint64_t srcLen, destLen;
6017   QualType srcEltTy, destEltTy;
6018   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6019   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6020 
6021   // ASTContext::getTypeSize will return the size rounded up to a
6022   // power of 2, so instead of using that, we need to use the raw
6023   // element size multiplied by the element count.
6024   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6025   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6026 
6027   return (srcLen * srcEltSize == destLen * destEltSize);
6028 }
6029 
6030 /// Is this a legal conversion between two types, one of which is
6031 /// known to be a vector type?
6032 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6033   assert(destTy->isVectorType() || srcTy->isVectorType());
6034 
6035   if (!Context.getLangOpts().LaxVectorConversions)
6036     return false;
6037   return areLaxCompatibleVectorTypes(srcTy, destTy);
6038 }
6039 
6040 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6041                            CastKind &Kind) {
6042   assert(VectorTy->isVectorType() && "Not a vector type!");
6043 
6044   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6045     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6046       return Diag(R.getBegin(),
6047                   Ty->isVectorType() ?
6048                   diag::err_invalid_conversion_between_vectors :
6049                   diag::err_invalid_conversion_between_vector_and_integer)
6050         << VectorTy << Ty << R;
6051   } else
6052     return Diag(R.getBegin(),
6053                 diag::err_invalid_conversion_between_vector_and_scalar)
6054       << VectorTy << Ty << R;
6055 
6056   Kind = CK_BitCast;
6057   return false;
6058 }
6059 
6060 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6061   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6062 
6063   if (DestElemTy == SplattedExpr->getType())
6064     return SplattedExpr;
6065 
6066   assert(DestElemTy->isFloatingType() ||
6067          DestElemTy->isIntegralOrEnumerationType());
6068 
6069   CastKind CK;
6070   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6071     // OpenCL requires that we convert `true` boolean expressions to -1, but
6072     // only when splatting vectors.
6073     if (DestElemTy->isFloatingType()) {
6074       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6075       // in two steps: boolean to signed integral, then to floating.
6076       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6077                                                  CK_BooleanToSignedIntegral);
6078       SplattedExpr = CastExprRes.get();
6079       CK = CK_IntegralToFloating;
6080     } else {
6081       CK = CK_BooleanToSignedIntegral;
6082     }
6083   } else {
6084     ExprResult CastExprRes = SplattedExpr;
6085     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6086     if (CastExprRes.isInvalid())
6087       return ExprError();
6088     SplattedExpr = CastExprRes.get();
6089   }
6090   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6091 }
6092 
6093 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6094                                     Expr *CastExpr, CastKind &Kind) {
6095   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6096 
6097   QualType SrcTy = CastExpr->getType();
6098 
6099   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6100   // an ExtVectorType.
6101   // In OpenCL, casts between vectors of different types are not allowed.
6102   // (See OpenCL 6.2).
6103   if (SrcTy->isVectorType()) {
6104     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6105         (getLangOpts().OpenCL &&
6106          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6107       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6108         << DestTy << SrcTy << R;
6109       return ExprError();
6110     }
6111     Kind = CK_BitCast;
6112     return CastExpr;
6113   }
6114 
6115   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6116   // conversion will take place first from scalar to elt type, and then
6117   // splat from elt type to vector.
6118   if (SrcTy->isPointerType())
6119     return Diag(R.getBegin(),
6120                 diag::err_invalid_conversion_between_vector_and_scalar)
6121       << DestTy << SrcTy << R;
6122 
6123   Kind = CK_VectorSplat;
6124   return prepareVectorSplat(DestTy, CastExpr);
6125 }
6126 
6127 ExprResult
6128 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6129                     Declarator &D, ParsedType &Ty,
6130                     SourceLocation RParenLoc, Expr *CastExpr) {
6131   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6132          "ActOnCastExpr(): missing type or expr");
6133 
6134   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6135   if (D.isInvalidType())
6136     return ExprError();
6137 
6138   if (getLangOpts().CPlusPlus) {
6139     // Check that there are no default arguments (C++ only).
6140     CheckExtraCXXDefaultArguments(D);
6141   } else {
6142     // Make sure any TypoExprs have been dealt with.
6143     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6144     if (!Res.isUsable())
6145       return ExprError();
6146     CastExpr = Res.get();
6147   }
6148 
6149   checkUnusedDeclAttributes(D);
6150 
6151   QualType castType = castTInfo->getType();
6152   Ty = CreateParsedType(castType, castTInfo);
6153 
6154   bool isVectorLiteral = false;
6155 
6156   // Check for an altivec or OpenCL literal,
6157   // i.e. all the elements are integer constants.
6158   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6159   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6160   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6161        && castType->isVectorType() && (PE || PLE)) {
6162     if (PLE && PLE->getNumExprs() == 0) {
6163       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6164       return ExprError();
6165     }
6166     if (PE || PLE->getNumExprs() == 1) {
6167       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6168       if (!E->getType()->isVectorType())
6169         isVectorLiteral = true;
6170     }
6171     else
6172       isVectorLiteral = true;
6173   }
6174 
6175   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6176   // then handle it as such.
6177   if (isVectorLiteral)
6178     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6179 
6180   // If the Expr being casted is a ParenListExpr, handle it specially.
6181   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6182   // sequence of BinOp comma operators.
6183   if (isa<ParenListExpr>(CastExpr)) {
6184     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6185     if (Result.isInvalid()) return ExprError();
6186     CastExpr = Result.get();
6187   }
6188 
6189   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6190       !getSourceManager().isInSystemMacro(LParenLoc))
6191     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6192 
6193   CheckTollFreeBridgeCast(castType, CastExpr);
6194 
6195   CheckObjCBridgeRelatedCast(castType, CastExpr);
6196 
6197   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6198 
6199   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6200 }
6201 
6202 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6203                                     SourceLocation RParenLoc, Expr *E,
6204                                     TypeSourceInfo *TInfo) {
6205   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6206          "Expected paren or paren list expression");
6207 
6208   Expr **exprs;
6209   unsigned numExprs;
6210   Expr *subExpr;
6211   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6212   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6213     LiteralLParenLoc = PE->getLParenLoc();
6214     LiteralRParenLoc = PE->getRParenLoc();
6215     exprs = PE->getExprs();
6216     numExprs = PE->getNumExprs();
6217   } else { // isa<ParenExpr> by assertion at function entrance
6218     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6219     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6220     subExpr = cast<ParenExpr>(E)->getSubExpr();
6221     exprs = &subExpr;
6222     numExprs = 1;
6223   }
6224 
6225   QualType Ty = TInfo->getType();
6226   assert(Ty->isVectorType() && "Expected vector type");
6227 
6228   SmallVector<Expr *, 8> initExprs;
6229   const VectorType *VTy = Ty->getAs<VectorType>();
6230   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6231 
6232   // '(...)' form of vector initialization in AltiVec: the number of
6233   // initializers must be one or must match the size of the vector.
6234   // If a single value is specified in the initializer then it will be
6235   // replicated to all the components of the vector
6236   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6237     // The number of initializers must be one or must match the size of the
6238     // vector. If a single value is specified in the initializer then it will
6239     // be replicated to all the components of the vector
6240     if (numExprs == 1) {
6241       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6242       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6243       if (Literal.isInvalid())
6244         return ExprError();
6245       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6246                                   PrepareScalarCast(Literal, ElemTy));
6247       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6248     }
6249     else if (numExprs < numElems) {
6250       Diag(E->getExprLoc(),
6251            diag::err_incorrect_number_of_vector_initializers);
6252       return ExprError();
6253     }
6254     else
6255       initExprs.append(exprs, exprs + numExprs);
6256   }
6257   else {
6258     // For OpenCL, when the number of initializers is a single value,
6259     // it will be replicated to all components of the vector.
6260     if (getLangOpts().OpenCL &&
6261         VTy->getVectorKind() == VectorType::GenericVector &&
6262         numExprs == 1) {
6263         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6264         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6265         if (Literal.isInvalid())
6266           return ExprError();
6267         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6268                                     PrepareScalarCast(Literal, ElemTy));
6269         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6270     }
6271 
6272     initExprs.append(exprs, exprs + numExprs);
6273   }
6274   // FIXME: This means that pretty-printing the final AST will produce curly
6275   // braces instead of the original commas.
6276   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6277                                                    initExprs, LiteralRParenLoc);
6278   initE->setType(Ty);
6279   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6280 }
6281 
6282 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6283 /// the ParenListExpr into a sequence of comma binary operators.
6284 ExprResult
6285 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6286   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6287   if (!E)
6288     return OrigExpr;
6289 
6290   ExprResult Result(E->getExpr(0));
6291 
6292   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6293     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6294                         E->getExpr(i));
6295 
6296   if (Result.isInvalid()) return ExprError();
6297 
6298   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6299 }
6300 
6301 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6302                                     SourceLocation R,
6303                                     MultiExprArg Val) {
6304   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6305   return expr;
6306 }
6307 
6308 /// Emit a specialized diagnostic when one expression is a null pointer
6309 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6310 /// emitted.
6311 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6312                                       SourceLocation QuestionLoc) {
6313   Expr *NullExpr = LHSExpr;
6314   Expr *NonPointerExpr = RHSExpr;
6315   Expr::NullPointerConstantKind NullKind =
6316       NullExpr->isNullPointerConstant(Context,
6317                                       Expr::NPC_ValueDependentIsNotNull);
6318 
6319   if (NullKind == Expr::NPCK_NotNull) {
6320     NullExpr = RHSExpr;
6321     NonPointerExpr = LHSExpr;
6322     NullKind =
6323         NullExpr->isNullPointerConstant(Context,
6324                                         Expr::NPC_ValueDependentIsNotNull);
6325   }
6326 
6327   if (NullKind == Expr::NPCK_NotNull)
6328     return false;
6329 
6330   if (NullKind == Expr::NPCK_ZeroExpression)
6331     return false;
6332 
6333   if (NullKind == Expr::NPCK_ZeroLiteral) {
6334     // In this case, check to make sure that we got here from a "NULL"
6335     // string in the source code.
6336     NullExpr = NullExpr->IgnoreParenImpCasts();
6337     SourceLocation loc = NullExpr->getExprLoc();
6338     if (!findMacroSpelling(loc, "NULL"))
6339       return false;
6340   }
6341 
6342   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6343   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6344       << NonPointerExpr->getType() << DiagType
6345       << NonPointerExpr->getSourceRange();
6346   return true;
6347 }
6348 
6349 /// Return false if the condition expression is valid, true otherwise.
6350 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6351   QualType CondTy = Cond->getType();
6352 
6353   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6354   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6355     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6356       << CondTy << Cond->getSourceRange();
6357     return true;
6358   }
6359 
6360   // C99 6.5.15p2
6361   if (CondTy->isScalarType()) return false;
6362 
6363   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6364     << CondTy << Cond->getSourceRange();
6365   return true;
6366 }
6367 
6368 /// Handle when one or both operands are void type.
6369 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6370                                          ExprResult &RHS) {
6371     Expr *LHSExpr = LHS.get();
6372     Expr *RHSExpr = RHS.get();
6373 
6374     if (!LHSExpr->getType()->isVoidType())
6375       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6376         << RHSExpr->getSourceRange();
6377     if (!RHSExpr->getType()->isVoidType())
6378       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6379         << LHSExpr->getSourceRange();
6380     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6381     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6382     return S.Context.VoidTy;
6383 }
6384 
6385 /// Return false if the NullExpr can be promoted to PointerTy,
6386 /// true otherwise.
6387 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6388                                         QualType PointerTy) {
6389   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6390       !NullExpr.get()->isNullPointerConstant(S.Context,
6391                                             Expr::NPC_ValueDependentIsNull))
6392     return true;
6393 
6394   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6395   return false;
6396 }
6397 
6398 /// Checks compatibility between two pointers and return the resulting
6399 /// type.
6400 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6401                                                      ExprResult &RHS,
6402                                                      SourceLocation Loc) {
6403   QualType LHSTy = LHS.get()->getType();
6404   QualType RHSTy = RHS.get()->getType();
6405 
6406   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6407     // Two identical pointers types are always compatible.
6408     return LHSTy;
6409   }
6410 
6411   QualType lhptee, rhptee;
6412 
6413   // Get the pointee types.
6414   bool IsBlockPointer = false;
6415   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6416     lhptee = LHSBTy->getPointeeType();
6417     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6418     IsBlockPointer = true;
6419   } else {
6420     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6421     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6422   }
6423 
6424   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6425   // differently qualified versions of compatible types, the result type is
6426   // a pointer to an appropriately qualified version of the composite
6427   // type.
6428 
6429   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6430   // clause doesn't make sense for our extensions. E.g. address space 2 should
6431   // be incompatible with address space 3: they may live on different devices or
6432   // anything.
6433   Qualifiers lhQual = lhptee.getQualifiers();
6434   Qualifiers rhQual = rhptee.getQualifiers();
6435 
6436   LangAS ResultAddrSpace = LangAS::Default;
6437   LangAS LAddrSpace = lhQual.getAddressSpace();
6438   LangAS RAddrSpace = rhQual.getAddressSpace();
6439   if (S.getLangOpts().OpenCL) {
6440     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6441     // spaces is disallowed.
6442     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6443       ResultAddrSpace = LAddrSpace;
6444     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6445       ResultAddrSpace = RAddrSpace;
6446     else {
6447       S.Diag(Loc,
6448              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6449           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6450           << RHS.get()->getSourceRange();
6451       return QualType();
6452     }
6453   }
6454 
6455   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6456   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6457   lhQual.removeCVRQualifiers();
6458   rhQual.removeCVRQualifiers();
6459 
6460   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6461   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6462   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6463   // qual types are compatible iff
6464   //  * corresponded types are compatible
6465   //  * CVR qualifiers are equal
6466   //  * address spaces are equal
6467   // Thus for conditional operator we merge CVR and address space unqualified
6468   // pointees and if there is a composite type we return a pointer to it with
6469   // merged qualifiers.
6470   if (S.getLangOpts().OpenCL) {
6471     LHSCastKind = LAddrSpace == ResultAddrSpace
6472                       ? CK_BitCast
6473                       : CK_AddressSpaceConversion;
6474     RHSCastKind = RAddrSpace == ResultAddrSpace
6475                       ? CK_BitCast
6476                       : CK_AddressSpaceConversion;
6477     lhQual.removeAddressSpace();
6478     rhQual.removeAddressSpace();
6479   }
6480 
6481   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6482   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6483 
6484   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6485 
6486   if (CompositeTy.isNull()) {
6487     // In this situation, we assume void* type. No especially good
6488     // reason, but this is what gcc does, and we do have to pick
6489     // to get a consistent AST.
6490     QualType incompatTy;
6491     incompatTy = S.Context.getPointerType(
6492         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6493     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6494     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6495     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6496     // for casts between types with incompatible address space qualifiers.
6497     // For the following code the compiler produces casts between global and
6498     // local address spaces of the corresponded innermost pointees:
6499     // local int *global *a;
6500     // global int *global *b;
6501     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6502     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6503         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6504         << RHS.get()->getSourceRange();
6505     return incompatTy;
6506   }
6507 
6508   // The pointer types are compatible.
6509   // In case of OpenCL ResultTy should have the address space qualifier
6510   // which is a superset of address spaces of both the 2nd and the 3rd
6511   // operands of the conditional operator.
6512   QualType ResultTy = [&, ResultAddrSpace]() {
6513     if (S.getLangOpts().OpenCL) {
6514       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6515       CompositeQuals.setAddressSpace(ResultAddrSpace);
6516       return S.Context
6517           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6518           .withCVRQualifiers(MergedCVRQual);
6519     }
6520     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6521   }();
6522   if (IsBlockPointer)
6523     ResultTy = S.Context.getBlockPointerType(ResultTy);
6524   else
6525     ResultTy = S.Context.getPointerType(ResultTy);
6526 
6527   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6528   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6529   return ResultTy;
6530 }
6531 
6532 /// Return the resulting type when the operands are both block pointers.
6533 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6534                                                           ExprResult &LHS,
6535                                                           ExprResult &RHS,
6536                                                           SourceLocation Loc) {
6537   QualType LHSTy = LHS.get()->getType();
6538   QualType RHSTy = RHS.get()->getType();
6539 
6540   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6541     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6542       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6543       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6544       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6545       return destType;
6546     }
6547     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6548       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6549       << RHS.get()->getSourceRange();
6550     return QualType();
6551   }
6552 
6553   // We have 2 block pointer types.
6554   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6555 }
6556 
6557 /// Return the resulting type when the operands are both pointers.
6558 static QualType
6559 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6560                                             ExprResult &RHS,
6561                                             SourceLocation Loc) {
6562   // get the pointer types
6563   QualType LHSTy = LHS.get()->getType();
6564   QualType RHSTy = RHS.get()->getType();
6565 
6566   // get the "pointed to" types
6567   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6568   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6569 
6570   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6571   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6572     // Figure out necessary qualifiers (C99 6.5.15p6)
6573     QualType destPointee
6574       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6575     QualType destType = S.Context.getPointerType(destPointee);
6576     // Add qualifiers if necessary.
6577     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6578     // Promote to void*.
6579     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6580     return destType;
6581   }
6582   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6583     QualType destPointee
6584       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6585     QualType destType = S.Context.getPointerType(destPointee);
6586     // Add qualifiers if necessary.
6587     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6588     // Promote to void*.
6589     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6590     return destType;
6591   }
6592 
6593   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6594 }
6595 
6596 /// Return false if the first expression is not an integer and the second
6597 /// expression is not a pointer, true otherwise.
6598 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6599                                         Expr* PointerExpr, SourceLocation Loc,
6600                                         bool IsIntFirstExpr) {
6601   if (!PointerExpr->getType()->isPointerType() ||
6602       !Int.get()->getType()->isIntegerType())
6603     return false;
6604 
6605   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6606   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6607 
6608   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6609     << Expr1->getType() << Expr2->getType()
6610     << Expr1->getSourceRange() << Expr2->getSourceRange();
6611   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6612                             CK_IntegralToPointer);
6613   return true;
6614 }
6615 
6616 /// Simple conversion between integer and floating point types.
6617 ///
6618 /// Used when handling the OpenCL conditional operator where the
6619 /// condition is a vector while the other operands are scalar.
6620 ///
6621 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6622 /// types are either integer or floating type. Between the two
6623 /// operands, the type with the higher rank is defined as the "result
6624 /// type". The other operand needs to be promoted to the same type. No
6625 /// other type promotion is allowed. We cannot use
6626 /// UsualArithmeticConversions() for this purpose, since it always
6627 /// promotes promotable types.
6628 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6629                                             ExprResult &RHS,
6630                                             SourceLocation QuestionLoc) {
6631   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6632   if (LHS.isInvalid())
6633     return QualType();
6634   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6635   if (RHS.isInvalid())
6636     return QualType();
6637 
6638   // For conversion purposes, we ignore any qualifiers.
6639   // For example, "const float" and "float" are equivalent.
6640   QualType LHSType =
6641     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6642   QualType RHSType =
6643     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6644 
6645   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6646     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6647       << LHSType << LHS.get()->getSourceRange();
6648     return QualType();
6649   }
6650 
6651   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6652     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6653       << RHSType << RHS.get()->getSourceRange();
6654     return QualType();
6655   }
6656 
6657   // If both types are identical, no conversion is needed.
6658   if (LHSType == RHSType)
6659     return LHSType;
6660 
6661   // Now handle "real" floating types (i.e. float, double, long double).
6662   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6663     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6664                                  /*IsCompAssign = */ false);
6665 
6666   // Finally, we have two differing integer types.
6667   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6668   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6669 }
6670 
6671 /// Convert scalar operands to a vector that matches the
6672 ///        condition in length.
6673 ///
6674 /// Used when handling the OpenCL conditional operator where the
6675 /// condition is a vector while the other operands are scalar.
6676 ///
6677 /// We first compute the "result type" for the scalar operands
6678 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6679 /// into a vector of that type where the length matches the condition
6680 /// vector type. s6.11.6 requires that the element types of the result
6681 /// and the condition must have the same number of bits.
6682 static QualType
6683 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6684                               QualType CondTy, SourceLocation QuestionLoc) {
6685   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6686   if (ResTy.isNull()) return QualType();
6687 
6688   const VectorType *CV = CondTy->getAs<VectorType>();
6689   assert(CV);
6690 
6691   // Determine the vector result type
6692   unsigned NumElements = CV->getNumElements();
6693   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6694 
6695   // Ensure that all types have the same number of bits
6696   if (S.Context.getTypeSize(CV->getElementType())
6697       != S.Context.getTypeSize(ResTy)) {
6698     // Since VectorTy is created internally, it does not pretty print
6699     // with an OpenCL name. Instead, we just print a description.
6700     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6701     SmallString<64> Str;
6702     llvm::raw_svector_ostream OS(Str);
6703     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6704     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6705       << CondTy << OS.str();
6706     return QualType();
6707   }
6708 
6709   // Convert operands to the vector result type
6710   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6711   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6712 
6713   return VectorTy;
6714 }
6715 
6716 /// Return false if this is a valid OpenCL condition vector
6717 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6718                                        SourceLocation QuestionLoc) {
6719   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6720   // integral type.
6721   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6722   assert(CondTy);
6723   QualType EleTy = CondTy->getElementType();
6724   if (EleTy->isIntegerType()) return false;
6725 
6726   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6727     << Cond->getType() << Cond->getSourceRange();
6728   return true;
6729 }
6730 
6731 /// Return false if the vector condition type and the vector
6732 ///        result type are compatible.
6733 ///
6734 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6735 /// number of elements, and their element types have the same number
6736 /// of bits.
6737 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6738                               SourceLocation QuestionLoc) {
6739   const VectorType *CV = CondTy->getAs<VectorType>();
6740   const VectorType *RV = VecResTy->getAs<VectorType>();
6741   assert(CV && RV);
6742 
6743   if (CV->getNumElements() != RV->getNumElements()) {
6744     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6745       << CondTy << VecResTy;
6746     return true;
6747   }
6748 
6749   QualType CVE = CV->getElementType();
6750   QualType RVE = RV->getElementType();
6751 
6752   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6753     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6754       << CondTy << VecResTy;
6755     return true;
6756   }
6757 
6758   return false;
6759 }
6760 
6761 /// Return the resulting type for the conditional operator in
6762 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6763 ///        s6.3.i) when the condition is a vector type.
6764 static QualType
6765 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6766                              ExprResult &LHS, ExprResult &RHS,
6767                              SourceLocation QuestionLoc) {
6768   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6769   if (Cond.isInvalid())
6770     return QualType();
6771   QualType CondTy = Cond.get()->getType();
6772 
6773   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6774     return QualType();
6775 
6776   // If either operand is a vector then find the vector type of the
6777   // result as specified in OpenCL v1.1 s6.3.i.
6778   if (LHS.get()->getType()->isVectorType() ||
6779       RHS.get()->getType()->isVectorType()) {
6780     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6781                                               /*isCompAssign*/false,
6782                                               /*AllowBothBool*/true,
6783                                               /*AllowBoolConversions*/false);
6784     if (VecResTy.isNull()) return QualType();
6785     // The result type must match the condition type as specified in
6786     // OpenCL v1.1 s6.11.6.
6787     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6788       return QualType();
6789     return VecResTy;
6790   }
6791 
6792   // Both operands are scalar.
6793   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6794 }
6795 
6796 /// Return true if the Expr is block type
6797 static bool checkBlockType(Sema &S, const Expr *E) {
6798   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6799     QualType Ty = CE->getCallee()->getType();
6800     if (Ty->isBlockPointerType()) {
6801       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6802       return true;
6803     }
6804   }
6805   return false;
6806 }
6807 
6808 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6809 /// In that case, LHS = cond.
6810 /// C99 6.5.15
6811 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6812                                         ExprResult &RHS, ExprValueKind &VK,
6813                                         ExprObjectKind &OK,
6814                                         SourceLocation QuestionLoc) {
6815 
6816   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6817   if (!LHSResult.isUsable()) return QualType();
6818   LHS = LHSResult;
6819 
6820   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6821   if (!RHSResult.isUsable()) return QualType();
6822   RHS = RHSResult;
6823 
6824   // C++ is sufficiently different to merit its own checker.
6825   if (getLangOpts().CPlusPlus)
6826     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6827 
6828   VK = VK_RValue;
6829   OK = OK_Ordinary;
6830 
6831   // The OpenCL operator with a vector condition is sufficiently
6832   // different to merit its own checker.
6833   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6834     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6835 
6836   // First, check the condition.
6837   Cond = UsualUnaryConversions(Cond.get());
6838   if (Cond.isInvalid())
6839     return QualType();
6840   if (checkCondition(*this, Cond.get(), QuestionLoc))
6841     return QualType();
6842 
6843   // Now check the two expressions.
6844   if (LHS.get()->getType()->isVectorType() ||
6845       RHS.get()->getType()->isVectorType())
6846     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6847                                /*AllowBothBool*/true,
6848                                /*AllowBoolConversions*/false);
6849 
6850   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6851   if (LHS.isInvalid() || RHS.isInvalid())
6852     return QualType();
6853 
6854   QualType LHSTy = LHS.get()->getType();
6855   QualType RHSTy = RHS.get()->getType();
6856 
6857   // Diagnose attempts to convert between __float128 and long double where
6858   // such conversions currently can't be handled.
6859   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6860     Diag(QuestionLoc,
6861          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6862       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6863     return QualType();
6864   }
6865 
6866   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6867   // selection operator (?:).
6868   if (getLangOpts().OpenCL &&
6869       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6870     return QualType();
6871   }
6872 
6873   // If both operands have arithmetic type, do the usual arithmetic conversions
6874   // to find a common type: C99 6.5.15p3,5.
6875   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6876     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6877     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6878 
6879     return ResTy;
6880   }
6881 
6882   // If both operands are the same structure or union type, the result is that
6883   // type.
6884   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6885     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6886       if (LHSRT->getDecl() == RHSRT->getDecl())
6887         // "If both the operands have structure or union type, the result has
6888         // that type."  This implies that CV qualifiers are dropped.
6889         return LHSTy.getUnqualifiedType();
6890     // FIXME: Type of conditional expression must be complete in C mode.
6891   }
6892 
6893   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6894   // The following || allows only one side to be void (a GCC-ism).
6895   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6896     return checkConditionalVoidType(*this, LHS, RHS);
6897   }
6898 
6899   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6900   // the type of the other operand."
6901   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6902   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6903 
6904   // All objective-c pointer type analysis is done here.
6905   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6906                                                         QuestionLoc);
6907   if (LHS.isInvalid() || RHS.isInvalid())
6908     return QualType();
6909   if (!compositeType.isNull())
6910     return compositeType;
6911 
6912 
6913   // Handle block pointer types.
6914   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6915     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6916                                                      QuestionLoc);
6917 
6918   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6919   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6920     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6921                                                        QuestionLoc);
6922 
6923   // GCC compatibility: soften pointer/integer mismatch.  Note that
6924   // null pointers have been filtered out by this point.
6925   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6926       /*isIntFirstExpr=*/true))
6927     return RHSTy;
6928   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6929       /*isIntFirstExpr=*/false))
6930     return LHSTy;
6931 
6932   // Emit a better diagnostic if one of the expressions is a null pointer
6933   // constant and the other is not a pointer type. In this case, the user most
6934   // likely forgot to take the address of the other expression.
6935   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6936     return QualType();
6937 
6938   // Otherwise, the operands are not compatible.
6939   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6940     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6941     << RHS.get()->getSourceRange();
6942   return QualType();
6943 }
6944 
6945 /// FindCompositeObjCPointerType - Helper method to find composite type of
6946 /// two objective-c pointer types of the two input expressions.
6947 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6948                                             SourceLocation QuestionLoc) {
6949   QualType LHSTy = LHS.get()->getType();
6950   QualType RHSTy = RHS.get()->getType();
6951 
6952   // Handle things like Class and struct objc_class*.  Here we case the result
6953   // to the pseudo-builtin, because that will be implicitly cast back to the
6954   // redefinition type if an attempt is made to access its fields.
6955   if (LHSTy->isObjCClassType() &&
6956       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6957     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6958     return LHSTy;
6959   }
6960   if (RHSTy->isObjCClassType() &&
6961       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6962     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6963     return RHSTy;
6964   }
6965   // And the same for struct objc_object* / id
6966   if (LHSTy->isObjCIdType() &&
6967       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6968     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6969     return LHSTy;
6970   }
6971   if (RHSTy->isObjCIdType() &&
6972       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6973     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6974     return RHSTy;
6975   }
6976   // And the same for struct objc_selector* / SEL
6977   if (Context.isObjCSelType(LHSTy) &&
6978       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6979     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6980     return LHSTy;
6981   }
6982   if (Context.isObjCSelType(RHSTy) &&
6983       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6984     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6985     return RHSTy;
6986   }
6987   // Check constraints for Objective-C object pointers types.
6988   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6989 
6990     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6991       // Two identical object pointer types are always compatible.
6992       return LHSTy;
6993     }
6994     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6995     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6996     QualType compositeType = LHSTy;
6997 
6998     // If both operands are interfaces and either operand can be
6999     // assigned to the other, use that type as the composite
7000     // type. This allows
7001     //   xxx ? (A*) a : (B*) b
7002     // where B is a subclass of A.
7003     //
7004     // Additionally, as for assignment, if either type is 'id'
7005     // allow silent coercion. Finally, if the types are
7006     // incompatible then make sure to use 'id' as the composite
7007     // type so the result is acceptable for sending messages to.
7008 
7009     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7010     // It could return the composite type.
7011     if (!(compositeType =
7012           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7013       // Nothing more to do.
7014     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7015       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7016     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7017       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7018     } else if ((LHSTy->isObjCQualifiedIdType() ||
7019                 RHSTy->isObjCQualifiedIdType()) &&
7020                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7021       // Need to handle "id<xx>" explicitly.
7022       // GCC allows qualified id and any Objective-C type to devolve to
7023       // id. Currently localizing to here until clear this should be
7024       // part of ObjCQualifiedIdTypesAreCompatible.
7025       compositeType = Context.getObjCIdType();
7026     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7027       compositeType = Context.getObjCIdType();
7028     } else {
7029       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7030       << LHSTy << RHSTy
7031       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7032       QualType incompatTy = Context.getObjCIdType();
7033       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7034       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7035       return incompatTy;
7036     }
7037     // The object pointer types are compatible.
7038     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7039     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7040     return compositeType;
7041   }
7042   // Check Objective-C object pointer types and 'void *'
7043   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7044     if (getLangOpts().ObjCAutoRefCount) {
7045       // ARC forbids the implicit conversion of object pointers to 'void *',
7046       // so these types are not compatible.
7047       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7048           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7049       LHS = RHS = true;
7050       return QualType();
7051     }
7052     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7053     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7054     QualType destPointee
7055     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7056     QualType destType = Context.getPointerType(destPointee);
7057     // Add qualifiers if necessary.
7058     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7059     // Promote to void*.
7060     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7061     return destType;
7062   }
7063   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
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<ObjCObjectPointerType>()->getPointeeType();
7073     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7074     QualType destPointee
7075     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7076     QualType destType = Context.getPointerType(destPointee);
7077     // Add qualifiers if necessary.
7078     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7079     // Promote to void*.
7080     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7081     return destType;
7082   }
7083   return QualType();
7084 }
7085 
7086 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7087 /// ParenRange in parentheses.
7088 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7089                                const PartialDiagnostic &Note,
7090                                SourceRange ParenRange) {
7091   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7092   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7093       EndLoc.isValid()) {
7094     Self.Diag(Loc, Note)
7095       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7096       << FixItHint::CreateInsertion(EndLoc, ")");
7097   } else {
7098     // We can't display the parentheses, so just show the bare note.
7099     Self.Diag(Loc, Note) << ParenRange;
7100   }
7101 }
7102 
7103 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7104   return BinaryOperator::isAdditiveOp(Opc) ||
7105          BinaryOperator::isMultiplicativeOp(Opc) ||
7106          BinaryOperator::isShiftOp(Opc);
7107 }
7108 
7109 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7110 /// expression, either using a built-in or overloaded operator,
7111 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7112 /// expression.
7113 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7114                                    Expr **RHSExprs) {
7115   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7116   E = E->IgnoreImpCasts();
7117   E = E->IgnoreConversionOperator();
7118   E = E->IgnoreImpCasts();
7119 
7120   // Built-in binary operator.
7121   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7122     if (IsArithmeticOp(OP->getOpcode())) {
7123       *Opcode = OP->getOpcode();
7124       *RHSExprs = OP->getRHS();
7125       return true;
7126     }
7127   }
7128 
7129   // Overloaded operator.
7130   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7131     if (Call->getNumArgs() != 2)
7132       return false;
7133 
7134     // Make sure this is really a binary operator that is safe to pass into
7135     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7136     OverloadedOperatorKind OO = Call->getOperator();
7137     if (OO < OO_Plus || OO > OO_Arrow ||
7138         OO == OO_PlusPlus || OO == OO_MinusMinus)
7139       return false;
7140 
7141     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7142     if (IsArithmeticOp(OpKind)) {
7143       *Opcode = OpKind;
7144       *RHSExprs = Call->getArg(1);
7145       return true;
7146     }
7147   }
7148 
7149   return false;
7150 }
7151 
7152 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7153 /// or is a logical expression such as (x==y) which has int type, but is
7154 /// commonly interpreted as boolean.
7155 static bool ExprLooksBoolean(Expr *E) {
7156   E = E->IgnoreParenImpCasts();
7157 
7158   if (E->getType()->isBooleanType())
7159     return true;
7160   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7161     return OP->isComparisonOp() || OP->isLogicalOp();
7162   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7163     return OP->getOpcode() == UO_LNot;
7164   if (E->getType()->isPointerType())
7165     return true;
7166 
7167   return false;
7168 }
7169 
7170 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7171 /// and binary operator are mixed in a way that suggests the programmer assumed
7172 /// the conditional operator has higher precedence, for example:
7173 /// "int x = a + someBinaryCondition ? 1 : 2".
7174 static void DiagnoseConditionalPrecedence(Sema &Self,
7175                                           SourceLocation OpLoc,
7176                                           Expr *Condition,
7177                                           Expr *LHSExpr,
7178                                           Expr *RHSExpr) {
7179   BinaryOperatorKind CondOpcode;
7180   Expr *CondRHS;
7181 
7182   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7183     return;
7184   if (!ExprLooksBoolean(CondRHS))
7185     return;
7186 
7187   // The condition is an arithmetic binary expression, with a right-
7188   // hand side that looks boolean, so warn.
7189 
7190   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7191       << Condition->getSourceRange()
7192       << BinaryOperator::getOpcodeStr(CondOpcode);
7193 
7194   SuggestParentheses(Self, OpLoc,
7195     Self.PDiag(diag::note_precedence_silence)
7196       << BinaryOperator::getOpcodeStr(CondOpcode),
7197     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7198 
7199   SuggestParentheses(Self, OpLoc,
7200     Self.PDiag(diag::note_precedence_conditional_first),
7201     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7202 }
7203 
7204 /// Compute the nullability of a conditional expression.
7205 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7206                                               QualType LHSTy, QualType RHSTy,
7207                                               ASTContext &Ctx) {
7208   if (!ResTy->isAnyPointerType())
7209     return ResTy;
7210 
7211   auto GetNullability = [&Ctx](QualType Ty) {
7212     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7213     if (Kind)
7214       return *Kind;
7215     return NullabilityKind::Unspecified;
7216   };
7217 
7218   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7219   NullabilityKind MergedKind;
7220 
7221   // Compute nullability of a binary conditional expression.
7222   if (IsBin) {
7223     if (LHSKind == NullabilityKind::NonNull)
7224       MergedKind = NullabilityKind::NonNull;
7225     else
7226       MergedKind = RHSKind;
7227   // Compute nullability of a normal conditional expression.
7228   } else {
7229     if (LHSKind == NullabilityKind::Nullable ||
7230         RHSKind == NullabilityKind::Nullable)
7231       MergedKind = NullabilityKind::Nullable;
7232     else if (LHSKind == NullabilityKind::NonNull)
7233       MergedKind = RHSKind;
7234     else if (RHSKind == NullabilityKind::NonNull)
7235       MergedKind = LHSKind;
7236     else
7237       MergedKind = NullabilityKind::Unspecified;
7238   }
7239 
7240   // Return if ResTy already has the correct nullability.
7241   if (GetNullability(ResTy) == MergedKind)
7242     return ResTy;
7243 
7244   // Strip all nullability from ResTy.
7245   while (ResTy->getNullability(Ctx))
7246     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7247 
7248   // Create a new AttributedType with the new nullability kind.
7249   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7250   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7251 }
7252 
7253 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7254 /// in the case of a the GNU conditional expr extension.
7255 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7256                                     SourceLocation ColonLoc,
7257                                     Expr *CondExpr, Expr *LHSExpr,
7258                                     Expr *RHSExpr) {
7259   if (!getLangOpts().CPlusPlus) {
7260     // C cannot handle TypoExpr nodes in the condition because it
7261     // doesn't handle dependent types properly, so make sure any TypoExprs have
7262     // been dealt with before checking the operands.
7263     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7264     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7265     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7266 
7267     if (!CondResult.isUsable())
7268       return ExprError();
7269 
7270     if (LHSExpr) {
7271       if (!LHSResult.isUsable())
7272         return ExprError();
7273     }
7274 
7275     if (!RHSResult.isUsable())
7276       return ExprError();
7277 
7278     CondExpr = CondResult.get();
7279     LHSExpr = LHSResult.get();
7280     RHSExpr = RHSResult.get();
7281   }
7282 
7283   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7284   // was the condition.
7285   OpaqueValueExpr *opaqueValue = nullptr;
7286   Expr *commonExpr = nullptr;
7287   if (!LHSExpr) {
7288     commonExpr = CondExpr;
7289     // Lower out placeholder types first.  This is important so that we don't
7290     // try to capture a placeholder. This happens in few cases in C++; such
7291     // as Objective-C++'s dictionary subscripting syntax.
7292     if (commonExpr->hasPlaceholderType()) {
7293       ExprResult result = CheckPlaceholderExpr(commonExpr);
7294       if (!result.isUsable()) return ExprError();
7295       commonExpr = result.get();
7296     }
7297     // We usually want to apply unary conversions *before* saving, except
7298     // in the special case of a C++ l-value conditional.
7299     if (!(getLangOpts().CPlusPlus
7300           && !commonExpr->isTypeDependent()
7301           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7302           && commonExpr->isGLValue()
7303           && commonExpr->isOrdinaryOrBitFieldObject()
7304           && RHSExpr->isOrdinaryOrBitFieldObject()
7305           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7306       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7307       if (commonRes.isInvalid())
7308         return ExprError();
7309       commonExpr = commonRes.get();
7310     }
7311 
7312     // If the common expression is a class or array prvalue, materialize it
7313     // so that we can safely refer to it multiple times.
7314     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7315                                    commonExpr->getType()->isArrayType())) {
7316       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7317       if (MatExpr.isInvalid())
7318         return ExprError();
7319       commonExpr = MatExpr.get();
7320     }
7321 
7322     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7323                                                 commonExpr->getType(),
7324                                                 commonExpr->getValueKind(),
7325                                                 commonExpr->getObjectKind(),
7326                                                 commonExpr);
7327     LHSExpr = CondExpr = opaqueValue;
7328   }
7329 
7330   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7331   ExprValueKind VK = VK_RValue;
7332   ExprObjectKind OK = OK_Ordinary;
7333   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7334   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7335                                              VK, OK, QuestionLoc);
7336   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7337       RHS.isInvalid())
7338     return ExprError();
7339 
7340   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7341                                 RHS.get());
7342 
7343   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7344 
7345   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7346                                          Context);
7347 
7348   if (!commonExpr)
7349     return new (Context)
7350         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7351                             RHS.get(), result, VK, OK);
7352 
7353   return new (Context) BinaryConditionalOperator(
7354       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7355       ColonLoc, result, VK, OK);
7356 }
7357 
7358 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7359 // being closely modeled after the C99 spec:-). The odd characteristic of this
7360 // routine is it effectively iqnores the qualifiers on the top level pointee.
7361 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7362 // FIXME: add a couple examples in this comment.
7363 static Sema::AssignConvertType
7364 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7365   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7366   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7367 
7368   // get the "pointed to" type (ignoring qualifiers at the top level)
7369   const Type *lhptee, *rhptee;
7370   Qualifiers lhq, rhq;
7371   std::tie(lhptee, lhq) =
7372       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7373   std::tie(rhptee, rhq) =
7374       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7375 
7376   Sema::AssignConvertType ConvTy = Sema::Compatible;
7377 
7378   // C99 6.5.16.1p1: This following citation is common to constraints
7379   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7380   // qualifiers of the type *pointed to* by the right;
7381 
7382   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7383   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7384       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7385     // Ignore lifetime for further calculation.
7386     lhq.removeObjCLifetime();
7387     rhq.removeObjCLifetime();
7388   }
7389 
7390   if (!lhq.compatiblyIncludes(rhq)) {
7391     // Treat address-space mismatches as fatal.  TODO: address subspaces
7392     if (!lhq.isAddressSpaceSupersetOf(rhq))
7393       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7394 
7395     // It's okay to add or remove GC or lifetime qualifiers when converting to
7396     // and from void*.
7397     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7398                         .compatiblyIncludes(
7399                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7400              && (lhptee->isVoidType() || rhptee->isVoidType()))
7401       ; // keep old
7402 
7403     // Treat lifetime mismatches as fatal.
7404     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7405       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7406 
7407     // For GCC/MS compatibility, other qualifier mismatches are treated
7408     // as still compatible in C.
7409     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7410   }
7411 
7412   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7413   // incomplete type and the other is a pointer to a qualified or unqualified
7414   // version of void...
7415   if (lhptee->isVoidType()) {
7416     if (rhptee->isIncompleteOrObjectType())
7417       return ConvTy;
7418 
7419     // As an extension, we allow cast to/from void* to function pointer.
7420     assert(rhptee->isFunctionType());
7421     return Sema::FunctionVoidPointer;
7422   }
7423 
7424   if (rhptee->isVoidType()) {
7425     if (lhptee->isIncompleteOrObjectType())
7426       return ConvTy;
7427 
7428     // As an extension, we allow cast to/from void* to function pointer.
7429     assert(lhptee->isFunctionType());
7430     return Sema::FunctionVoidPointer;
7431   }
7432 
7433   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7434   // unqualified versions of compatible types, ...
7435   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7436   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7437     // Check if the pointee types are compatible ignoring the sign.
7438     // We explicitly check for char so that we catch "char" vs
7439     // "unsigned char" on systems where "char" is unsigned.
7440     if (lhptee->isCharType())
7441       ltrans = S.Context.UnsignedCharTy;
7442     else if (lhptee->hasSignedIntegerRepresentation())
7443       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7444 
7445     if (rhptee->isCharType())
7446       rtrans = S.Context.UnsignedCharTy;
7447     else if (rhptee->hasSignedIntegerRepresentation())
7448       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7449 
7450     if (ltrans == rtrans) {
7451       // Types are compatible ignoring the sign. Qualifier incompatibility
7452       // takes priority over sign incompatibility because the sign
7453       // warning can be disabled.
7454       if (ConvTy != Sema::Compatible)
7455         return ConvTy;
7456 
7457       return Sema::IncompatiblePointerSign;
7458     }
7459 
7460     // If we are a multi-level pointer, it's possible that our issue is simply
7461     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7462     // the eventual target type is the same and the pointers have the same
7463     // level of indirection, this must be the issue.
7464     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7465       do {
7466         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7467         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7468       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7469 
7470       if (lhptee == rhptee)
7471         return Sema::IncompatibleNestedPointerQualifiers;
7472     }
7473 
7474     // General pointer incompatibility takes priority over qualifiers.
7475     return Sema::IncompatiblePointer;
7476   }
7477   if (!S.getLangOpts().CPlusPlus &&
7478       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7479     return Sema::IncompatiblePointer;
7480   return ConvTy;
7481 }
7482 
7483 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7484 /// block pointer types are compatible or whether a block and normal pointer
7485 /// are compatible. It is more restrict than comparing two function pointer
7486 // types.
7487 static Sema::AssignConvertType
7488 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7489                                     QualType RHSType) {
7490   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7491   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7492 
7493   QualType lhptee, rhptee;
7494 
7495   // get the "pointed to" type (ignoring qualifiers at the top level)
7496   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7497   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7498 
7499   // In C++, the types have to match exactly.
7500   if (S.getLangOpts().CPlusPlus)
7501     return Sema::IncompatibleBlockPointer;
7502 
7503   Sema::AssignConvertType ConvTy = Sema::Compatible;
7504 
7505   // For blocks we enforce that qualifiers are identical.
7506   Qualifiers LQuals = lhptee.getLocalQualifiers();
7507   Qualifiers RQuals = rhptee.getLocalQualifiers();
7508   if (S.getLangOpts().OpenCL) {
7509     LQuals.removeAddressSpace();
7510     RQuals.removeAddressSpace();
7511   }
7512   if (LQuals != RQuals)
7513     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7514 
7515   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7516   // assignment.
7517   // The current behavior is similar to C++ lambdas. A block might be
7518   // assigned to a variable iff its return type and parameters are compatible
7519   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7520   // an assignment. Presumably it should behave in way that a function pointer
7521   // assignment does in C, so for each parameter and return type:
7522   //  * CVR and address space of LHS should be a superset of CVR and address
7523   //  space of RHS.
7524   //  * unqualified types should be compatible.
7525   if (S.getLangOpts().OpenCL) {
7526     if (!S.Context.typesAreBlockPointerCompatible(
7527             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7528             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7529       return Sema::IncompatibleBlockPointer;
7530   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7531     return Sema::IncompatibleBlockPointer;
7532 
7533   return ConvTy;
7534 }
7535 
7536 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7537 /// for assignment compatibility.
7538 static Sema::AssignConvertType
7539 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7540                                    QualType RHSType) {
7541   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7542   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7543 
7544   if (LHSType->isObjCBuiltinType()) {
7545     // Class is not compatible with ObjC object pointers.
7546     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7547         !RHSType->isObjCQualifiedClassType())
7548       return Sema::IncompatiblePointer;
7549     return Sema::Compatible;
7550   }
7551   if (RHSType->isObjCBuiltinType()) {
7552     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7553         !LHSType->isObjCQualifiedClassType())
7554       return Sema::IncompatiblePointer;
7555     return Sema::Compatible;
7556   }
7557   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7558   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7559 
7560   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7561       // make an exception for id<P>
7562       !LHSType->isObjCQualifiedIdType())
7563     return Sema::CompatiblePointerDiscardsQualifiers;
7564 
7565   if (S.Context.typesAreCompatible(LHSType, RHSType))
7566     return Sema::Compatible;
7567   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7568     return Sema::IncompatibleObjCQualifiedId;
7569   return Sema::IncompatiblePointer;
7570 }
7571 
7572 Sema::AssignConvertType
7573 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7574                                  QualType LHSType, QualType RHSType) {
7575   // Fake up an opaque expression.  We don't actually care about what
7576   // cast operations are required, so if CheckAssignmentConstraints
7577   // adds casts to this they'll be wasted, but fortunately that doesn't
7578   // usually happen on valid code.
7579   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7580   ExprResult RHSPtr = &RHSExpr;
7581   CastKind K;
7582 
7583   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7584 }
7585 
7586 /// This helper function returns true if QT is a vector type that has element
7587 /// type ElementType.
7588 static bool isVector(QualType QT, QualType ElementType) {
7589   if (const VectorType *VT = QT->getAs<VectorType>())
7590     return VT->getElementType() == ElementType;
7591   return false;
7592 }
7593 
7594 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7595 /// has code to accommodate several GCC extensions when type checking
7596 /// pointers. Here are some objectionable examples that GCC considers warnings:
7597 ///
7598 ///  int a, *pint;
7599 ///  short *pshort;
7600 ///  struct foo *pfoo;
7601 ///
7602 ///  pint = pshort; // warning: assignment from incompatible pointer type
7603 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7604 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7605 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7606 ///
7607 /// As a result, the code for dealing with pointers is more complex than the
7608 /// C99 spec dictates.
7609 ///
7610 /// Sets 'Kind' for any result kind except Incompatible.
7611 Sema::AssignConvertType
7612 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7613                                  CastKind &Kind, bool ConvertRHS) {
7614   QualType RHSType = RHS.get()->getType();
7615   QualType OrigLHSType = LHSType;
7616 
7617   // Get canonical types.  We're not formatting these types, just comparing
7618   // them.
7619   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7620   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7621 
7622   // Common case: no conversion required.
7623   if (LHSType == RHSType) {
7624     Kind = CK_NoOp;
7625     return Compatible;
7626   }
7627 
7628   // If we have an atomic type, try a non-atomic assignment, then just add an
7629   // atomic qualification step.
7630   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7631     Sema::AssignConvertType result =
7632       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7633     if (result != Compatible)
7634       return result;
7635     if (Kind != CK_NoOp && ConvertRHS)
7636       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7637     Kind = CK_NonAtomicToAtomic;
7638     return Compatible;
7639   }
7640 
7641   // If the left-hand side is a reference type, then we are in a
7642   // (rare!) case where we've allowed the use of references in C,
7643   // e.g., as a parameter type in a built-in function. In this case,
7644   // just make sure that the type referenced is compatible with the
7645   // right-hand side type. The caller is responsible for adjusting
7646   // LHSType so that the resulting expression does not have reference
7647   // type.
7648   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7649     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7650       Kind = CK_LValueBitCast;
7651       return Compatible;
7652     }
7653     return Incompatible;
7654   }
7655 
7656   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7657   // to the same ExtVector type.
7658   if (LHSType->isExtVectorType()) {
7659     if (RHSType->isExtVectorType())
7660       return Incompatible;
7661     if (RHSType->isArithmeticType()) {
7662       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7663       if (ConvertRHS)
7664         RHS = prepareVectorSplat(LHSType, RHS.get());
7665       Kind = CK_VectorSplat;
7666       return Compatible;
7667     }
7668   }
7669 
7670   // Conversions to or from vector type.
7671   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7672     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7673       // Allow assignments of an AltiVec vector type to an equivalent GCC
7674       // vector type and vice versa
7675       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7676         Kind = CK_BitCast;
7677         return Compatible;
7678       }
7679 
7680       // If we are allowing lax vector conversions, and LHS and RHS are both
7681       // vectors, the total size only needs to be the same. This is a bitcast;
7682       // no bits are changed but the result type is different.
7683       if (isLaxVectorConversion(RHSType, LHSType)) {
7684         Kind = CK_BitCast;
7685         return IncompatibleVectors;
7686       }
7687     }
7688 
7689     // When the RHS comes from another lax conversion (e.g. binops between
7690     // scalars and vectors) the result is canonicalized as a vector. When the
7691     // LHS is also a vector, the lax is allowed by the condition above. Handle
7692     // the case where LHS is a scalar.
7693     if (LHSType->isScalarType()) {
7694       const VectorType *VecType = RHSType->getAs<VectorType>();
7695       if (VecType && VecType->getNumElements() == 1 &&
7696           isLaxVectorConversion(RHSType, LHSType)) {
7697         ExprResult *VecExpr = &RHS;
7698         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7699         Kind = CK_BitCast;
7700         return Compatible;
7701       }
7702     }
7703 
7704     return Incompatible;
7705   }
7706 
7707   // Diagnose attempts to convert between __float128 and long double where
7708   // such conversions currently can't be handled.
7709   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7710     return Incompatible;
7711 
7712   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7713   // discards the imaginary part.
7714   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7715       !LHSType->getAs<ComplexType>())
7716     return Incompatible;
7717 
7718   // Arithmetic conversions.
7719   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7720       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7721     if (ConvertRHS)
7722       Kind = PrepareScalarCast(RHS, LHSType);
7723     return Compatible;
7724   }
7725 
7726   // Conversions to normal pointers.
7727   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7728     // U* -> T*
7729     if (isa<PointerType>(RHSType)) {
7730       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7731       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7732       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7733       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7734     }
7735 
7736     // int -> T*
7737     if (RHSType->isIntegerType()) {
7738       Kind = CK_IntegralToPointer; // FIXME: null?
7739       return IntToPointer;
7740     }
7741 
7742     // C pointers are not compatible with ObjC object pointers,
7743     // with two exceptions:
7744     if (isa<ObjCObjectPointerType>(RHSType)) {
7745       //  - conversions to void*
7746       if (LHSPointer->getPointeeType()->isVoidType()) {
7747         Kind = CK_BitCast;
7748         return Compatible;
7749       }
7750 
7751       //  - conversions from 'Class' to the redefinition type
7752       if (RHSType->isObjCClassType() &&
7753           Context.hasSameType(LHSType,
7754                               Context.getObjCClassRedefinitionType())) {
7755         Kind = CK_BitCast;
7756         return Compatible;
7757       }
7758 
7759       Kind = CK_BitCast;
7760       return IncompatiblePointer;
7761     }
7762 
7763     // U^ -> void*
7764     if (RHSType->getAs<BlockPointerType>()) {
7765       if (LHSPointer->getPointeeType()->isVoidType()) {
7766         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7767         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7768                                 ->getPointeeType()
7769                                 .getAddressSpace();
7770         Kind =
7771             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7772         return Compatible;
7773       }
7774     }
7775 
7776     return Incompatible;
7777   }
7778 
7779   // Conversions to block pointers.
7780   if (isa<BlockPointerType>(LHSType)) {
7781     // U^ -> T^
7782     if (RHSType->isBlockPointerType()) {
7783       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7784                               ->getPointeeType()
7785                               .getAddressSpace();
7786       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7787                               ->getPointeeType()
7788                               .getAddressSpace();
7789       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7790       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7791     }
7792 
7793     // int or null -> T^
7794     if (RHSType->isIntegerType()) {
7795       Kind = CK_IntegralToPointer; // FIXME: null
7796       return IntToBlockPointer;
7797     }
7798 
7799     // id -> T^
7800     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7801       Kind = CK_AnyPointerToBlockPointerCast;
7802       return Compatible;
7803     }
7804 
7805     // void* -> T^
7806     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7807       if (RHSPT->getPointeeType()->isVoidType()) {
7808         Kind = CK_AnyPointerToBlockPointerCast;
7809         return Compatible;
7810       }
7811 
7812     return Incompatible;
7813   }
7814 
7815   // Conversions to Objective-C pointers.
7816   if (isa<ObjCObjectPointerType>(LHSType)) {
7817     // A* -> B*
7818     if (RHSType->isObjCObjectPointerType()) {
7819       Kind = CK_BitCast;
7820       Sema::AssignConvertType result =
7821         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7822       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7823           result == Compatible &&
7824           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7825         result = IncompatibleObjCWeakRef;
7826       return result;
7827     }
7828 
7829     // int or null -> A*
7830     if (RHSType->isIntegerType()) {
7831       Kind = CK_IntegralToPointer; // FIXME: null
7832       return IntToPointer;
7833     }
7834 
7835     // In general, C pointers are not compatible with ObjC object pointers,
7836     // with two exceptions:
7837     if (isa<PointerType>(RHSType)) {
7838       Kind = CK_CPointerToObjCPointerCast;
7839 
7840       //  - conversions from 'void*'
7841       if (RHSType->isVoidPointerType()) {
7842         return Compatible;
7843       }
7844 
7845       //  - conversions to 'Class' from its redefinition type
7846       if (LHSType->isObjCClassType() &&
7847           Context.hasSameType(RHSType,
7848                               Context.getObjCClassRedefinitionType())) {
7849         return Compatible;
7850       }
7851 
7852       return IncompatiblePointer;
7853     }
7854 
7855     // Only under strict condition T^ is compatible with an Objective-C pointer.
7856     if (RHSType->isBlockPointerType() &&
7857         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7858       if (ConvertRHS)
7859         maybeExtendBlockObject(RHS);
7860       Kind = CK_BlockPointerToObjCPointerCast;
7861       return Compatible;
7862     }
7863 
7864     return Incompatible;
7865   }
7866 
7867   // Conversions from pointers that are not covered by the above.
7868   if (isa<PointerType>(RHSType)) {
7869     // T* -> _Bool
7870     if (LHSType == Context.BoolTy) {
7871       Kind = CK_PointerToBoolean;
7872       return Compatible;
7873     }
7874 
7875     // T* -> int
7876     if (LHSType->isIntegerType()) {
7877       Kind = CK_PointerToIntegral;
7878       return PointerToInt;
7879     }
7880 
7881     return Incompatible;
7882   }
7883 
7884   // Conversions from Objective-C pointers that are not covered by the above.
7885   if (isa<ObjCObjectPointerType>(RHSType)) {
7886     // T* -> _Bool
7887     if (LHSType == Context.BoolTy) {
7888       Kind = CK_PointerToBoolean;
7889       return Compatible;
7890     }
7891 
7892     // T* -> int
7893     if (LHSType->isIntegerType()) {
7894       Kind = CK_PointerToIntegral;
7895       return PointerToInt;
7896     }
7897 
7898     return Incompatible;
7899   }
7900 
7901   // struct A -> struct B
7902   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7903     if (Context.typesAreCompatible(LHSType, RHSType)) {
7904       Kind = CK_NoOp;
7905       return Compatible;
7906     }
7907   }
7908 
7909   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7910     Kind = CK_IntToOCLSampler;
7911     return Compatible;
7912   }
7913 
7914   return Incompatible;
7915 }
7916 
7917 /// Constructs a transparent union from an expression that is
7918 /// used to initialize the transparent union.
7919 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7920                                       ExprResult &EResult, QualType UnionType,
7921                                       FieldDecl *Field) {
7922   // Build an initializer list that designates the appropriate member
7923   // of the transparent union.
7924   Expr *E = EResult.get();
7925   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7926                                                    E, SourceLocation());
7927   Initializer->setType(UnionType);
7928   Initializer->setInitializedFieldInUnion(Field);
7929 
7930   // Build a compound literal constructing a value of the transparent
7931   // union type from this initializer list.
7932   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7933   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7934                                         VK_RValue, Initializer, false);
7935 }
7936 
7937 Sema::AssignConvertType
7938 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7939                                                ExprResult &RHS) {
7940   QualType RHSType = RHS.get()->getType();
7941 
7942   // If the ArgType is a Union type, we want to handle a potential
7943   // transparent_union GCC extension.
7944   const RecordType *UT = ArgType->getAsUnionType();
7945   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7946     return Incompatible;
7947 
7948   // The field to initialize within the transparent union.
7949   RecordDecl *UD = UT->getDecl();
7950   FieldDecl *InitField = nullptr;
7951   // It's compatible if the expression matches any of the fields.
7952   for (auto *it : UD->fields()) {
7953     if (it->getType()->isPointerType()) {
7954       // If the transparent union contains a pointer type, we allow:
7955       // 1) void pointer
7956       // 2) null pointer constant
7957       if (RHSType->isPointerType())
7958         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7959           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7960           InitField = it;
7961           break;
7962         }
7963 
7964       if (RHS.get()->isNullPointerConstant(Context,
7965                                            Expr::NPC_ValueDependentIsNull)) {
7966         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7967                                 CK_NullToPointer);
7968         InitField = it;
7969         break;
7970       }
7971     }
7972 
7973     CastKind Kind;
7974     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7975           == Compatible) {
7976       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7977       InitField = it;
7978       break;
7979     }
7980   }
7981 
7982   if (!InitField)
7983     return Incompatible;
7984 
7985   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7986   return Compatible;
7987 }
7988 
7989 Sema::AssignConvertType
7990 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7991                                        bool Diagnose,
7992                                        bool DiagnoseCFAudited,
7993                                        bool ConvertRHS) {
7994   // We need to be able to tell the caller whether we diagnosed a problem, if
7995   // they ask us to issue diagnostics.
7996   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7997 
7998   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7999   // we can't avoid *all* modifications at the moment, so we need some somewhere
8000   // to put the updated value.
8001   ExprResult LocalRHS = CallerRHS;
8002   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8003 
8004   if (getLangOpts().CPlusPlus) {
8005     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8006       // C++ 5.17p3: If the left operand is not of class type, the
8007       // expression is implicitly converted (C++ 4) to the
8008       // cv-unqualified type of the left operand.
8009       QualType RHSType = RHS.get()->getType();
8010       if (Diagnose) {
8011         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8012                                         AA_Assigning);
8013       } else {
8014         ImplicitConversionSequence ICS =
8015             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8016                                   /*SuppressUserConversions=*/false,
8017                                   /*AllowExplicit=*/false,
8018                                   /*InOverloadResolution=*/false,
8019                                   /*CStyle=*/false,
8020                                   /*AllowObjCWritebackConversion=*/false);
8021         if (ICS.isFailure())
8022           return Incompatible;
8023         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8024                                         ICS, AA_Assigning);
8025       }
8026       if (RHS.isInvalid())
8027         return Incompatible;
8028       Sema::AssignConvertType result = Compatible;
8029       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8030           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8031         result = IncompatibleObjCWeakRef;
8032       return result;
8033     }
8034 
8035     // FIXME: Currently, we fall through and treat C++ classes like C
8036     // structures.
8037     // FIXME: We also fall through for atomics; not sure what should
8038     // happen there, though.
8039   } else if (RHS.get()->getType() == Context.OverloadTy) {
8040     // As a set of extensions to C, we support overloading on functions. These
8041     // functions need to be resolved here.
8042     DeclAccessPair DAP;
8043     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8044             RHS.get(), LHSType, /*Complain=*/false, DAP))
8045       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8046     else
8047       return Incompatible;
8048   }
8049 
8050   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8051   // a null pointer constant.
8052   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8053        LHSType->isBlockPointerType()) &&
8054       RHS.get()->isNullPointerConstant(Context,
8055                                        Expr::NPC_ValueDependentIsNull)) {
8056     if (Diagnose || ConvertRHS) {
8057       CastKind Kind;
8058       CXXCastPath Path;
8059       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8060                              /*IgnoreBaseAccess=*/false, Diagnose);
8061       if (ConvertRHS)
8062         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8063     }
8064     return Compatible;
8065   }
8066 
8067   // This check seems unnatural, however it is necessary to ensure the proper
8068   // conversion of functions/arrays. If the conversion were done for all
8069   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8070   // expressions that suppress this implicit conversion (&, sizeof).
8071   //
8072   // Suppress this for references: C++ 8.5.3p5.
8073   if (!LHSType->isReferenceType()) {
8074     // FIXME: We potentially allocate here even if ConvertRHS is false.
8075     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8076     if (RHS.isInvalid())
8077       return Incompatible;
8078   }
8079 
8080   Expr *PRE = RHS.get()->IgnoreParenCasts();
8081   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8082     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8083     if (PDecl && !PDecl->hasDefinition()) {
8084       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8085       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8086     }
8087   }
8088 
8089   CastKind Kind;
8090   Sema::AssignConvertType result =
8091     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8092 
8093   // C99 6.5.16.1p2: The value of the right operand is converted to the
8094   // type of the assignment expression.
8095   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8096   // so that we can use references in built-in functions even in C.
8097   // The getNonReferenceType() call makes sure that the resulting expression
8098   // does not have reference type.
8099   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8100     QualType Ty = LHSType.getNonLValueExprType(Context);
8101     Expr *E = RHS.get();
8102 
8103     // Check for various Objective-C errors. If we are not reporting
8104     // diagnostics and just checking for errors, e.g., during overload
8105     // resolution, return Incompatible to indicate the failure.
8106     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8107         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8108                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8109       if (!Diagnose)
8110         return Incompatible;
8111     }
8112     if (getLangOpts().ObjC1 &&
8113         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8114                                            E->getType(), E, Diagnose) ||
8115          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8116       if (!Diagnose)
8117         return Incompatible;
8118       // Replace the expression with a corrected version and continue so we
8119       // can find further errors.
8120       RHS = E;
8121       return Compatible;
8122     }
8123 
8124     if (ConvertRHS)
8125       RHS = ImpCastExprToType(E, Ty, Kind);
8126   }
8127   return result;
8128 }
8129 
8130 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8131                                ExprResult &RHS) {
8132   Diag(Loc, diag::err_typecheck_invalid_operands)
8133     << LHS.get()->getType() << RHS.get()->getType()
8134     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8135   return QualType();
8136 }
8137 
8138 // Diagnose cases where a scalar was implicitly converted to a vector and
8139 // diagnose the underlying types. Otherwise, diagnose the error
8140 // as invalid vector logical operands for non-C++ cases.
8141 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8142                                             ExprResult &RHS) {
8143   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8144   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8145 
8146   bool LHSNatVec = LHSType->isVectorType();
8147   bool RHSNatVec = RHSType->isVectorType();
8148 
8149   if (!(LHSNatVec && RHSNatVec)) {
8150     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8151     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8152     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8153         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8154         << Vector->getSourceRange();
8155     return QualType();
8156   }
8157 
8158   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8159       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8160       << RHS.get()->getSourceRange();
8161 
8162   return QualType();
8163 }
8164 
8165 /// Try to convert a value of non-vector type to a vector type by converting
8166 /// the type to the element type of the vector and then performing a splat.
8167 /// If the language is OpenCL, we only use conversions that promote scalar
8168 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8169 /// for float->int.
8170 ///
8171 /// OpenCL V2.0 6.2.6.p2:
8172 /// An error shall occur if any scalar operand type has greater rank
8173 /// than the type of the vector element.
8174 ///
8175 /// \param scalar - if non-null, actually perform the conversions
8176 /// \return true if the operation fails (but without diagnosing the failure)
8177 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8178                                      QualType scalarTy,
8179                                      QualType vectorEltTy,
8180                                      QualType vectorTy,
8181                                      unsigned &DiagID) {
8182   // The conversion to apply to the scalar before splatting it,
8183   // if necessary.
8184   CastKind scalarCast = CK_NoOp;
8185 
8186   if (vectorEltTy->isIntegralType(S.Context)) {
8187     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8188         (scalarTy->isIntegerType() &&
8189          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8190       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8191       return true;
8192     }
8193     if (!scalarTy->isIntegralType(S.Context))
8194       return true;
8195     scalarCast = CK_IntegralCast;
8196   } else if (vectorEltTy->isRealFloatingType()) {
8197     if (scalarTy->isRealFloatingType()) {
8198       if (S.getLangOpts().OpenCL &&
8199           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8200         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8201         return true;
8202       }
8203       scalarCast = CK_FloatingCast;
8204     }
8205     else if (scalarTy->isIntegralType(S.Context))
8206       scalarCast = CK_IntegralToFloating;
8207     else
8208       return true;
8209   } else {
8210     return true;
8211   }
8212 
8213   // Adjust scalar if desired.
8214   if (scalar) {
8215     if (scalarCast != CK_NoOp)
8216       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8217     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8218   }
8219   return false;
8220 }
8221 
8222 /// Convert vector E to a vector with the same number of elements but different
8223 /// element type.
8224 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8225   const auto *VecTy = E->getType()->getAs<VectorType>();
8226   assert(VecTy && "Expression E must be a vector");
8227   QualType NewVecTy = S.Context.getVectorType(ElementType,
8228                                               VecTy->getNumElements(),
8229                                               VecTy->getVectorKind());
8230 
8231   // Look through the implicit cast. Return the subexpression if its type is
8232   // NewVecTy.
8233   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8234     if (ICE->getSubExpr()->getType() == NewVecTy)
8235       return ICE->getSubExpr();
8236 
8237   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8238   return S.ImpCastExprToType(E, NewVecTy, Cast);
8239 }
8240 
8241 /// Test if a (constant) integer Int can be casted to another integer type
8242 /// IntTy without losing precision.
8243 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8244                                       QualType OtherIntTy) {
8245   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8246 
8247   // Reject cases where the value of the Int is unknown as that would
8248   // possibly cause truncation, but accept cases where the scalar can be
8249   // demoted without loss of precision.
8250   llvm::APSInt Result;
8251   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8252   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8253   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8254   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8255 
8256   if (CstInt) {
8257     // If the scalar is constant and is of a higher order and has more active
8258     // bits that the vector element type, reject it.
8259     unsigned NumBits = IntSigned
8260                            ? (Result.isNegative() ? Result.getMinSignedBits()
8261                                                   : Result.getActiveBits())
8262                            : Result.getActiveBits();
8263     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8264       return true;
8265 
8266     // If the signedness of the scalar type and the vector element type
8267     // differs and the number of bits is greater than that of the vector
8268     // element reject it.
8269     return (IntSigned != OtherIntSigned &&
8270             NumBits > S.Context.getIntWidth(OtherIntTy));
8271   }
8272 
8273   // Reject cases where the value of the scalar is not constant and it's
8274   // order is greater than that of the vector element type.
8275   return (Order < 0);
8276 }
8277 
8278 /// Test if a (constant) integer Int can be casted to floating point type
8279 /// FloatTy without losing precision.
8280 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8281                                      QualType FloatTy) {
8282   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8283 
8284   // Determine if the integer constant can be expressed as a floating point
8285   // number of the appropriate type.
8286   llvm::APSInt Result;
8287   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8288   uint64_t Bits = 0;
8289   if (CstInt) {
8290     // Reject constants that would be truncated if they were converted to
8291     // the floating point type. Test by simple to/from conversion.
8292     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8293     //        could be avoided if there was a convertFromAPInt method
8294     //        which could signal back if implicit truncation occurred.
8295     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8296     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8297                            llvm::APFloat::rmTowardZero);
8298     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8299                              !IntTy->hasSignedIntegerRepresentation());
8300     bool Ignored = false;
8301     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8302                            &Ignored);
8303     if (Result != ConvertBack)
8304       return true;
8305   } else {
8306     // Reject types that cannot be fully encoded into the mantissa of
8307     // the float.
8308     Bits = S.Context.getTypeSize(IntTy);
8309     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8310         S.Context.getFloatTypeSemantics(FloatTy));
8311     if (Bits > FloatPrec)
8312       return true;
8313   }
8314 
8315   return false;
8316 }
8317 
8318 /// Attempt to convert and splat Scalar into a vector whose types matches
8319 /// Vector following GCC conversion rules. The rule is that implicit
8320 /// conversion can occur when Scalar can be casted to match Vector's element
8321 /// type without causing truncation of Scalar.
8322 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8323                                         ExprResult *Vector) {
8324   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8325   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8326   const VectorType *VT = VectorTy->getAs<VectorType>();
8327 
8328   assert(!isa<ExtVectorType>(VT) &&
8329          "ExtVectorTypes should not be handled here!");
8330 
8331   QualType VectorEltTy = VT->getElementType();
8332 
8333   // Reject cases where the vector element type or the scalar element type are
8334   // not integral or floating point types.
8335   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8336     return true;
8337 
8338   // The conversion to apply to the scalar before splatting it,
8339   // if necessary.
8340   CastKind ScalarCast = CK_NoOp;
8341 
8342   // Accept cases where the vector elements are integers and the scalar is
8343   // an integer.
8344   // FIXME: Notionally if the scalar was a floating point value with a precise
8345   //        integral representation, we could cast it to an appropriate integer
8346   //        type and then perform the rest of the checks here. GCC will perform
8347   //        this conversion in some cases as determined by the input language.
8348   //        We should accept it on a language independent basis.
8349   if (VectorEltTy->isIntegralType(S.Context) &&
8350       ScalarTy->isIntegralType(S.Context) &&
8351       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8352 
8353     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8354       return true;
8355 
8356     ScalarCast = CK_IntegralCast;
8357   } else if (VectorEltTy->isRealFloatingType()) {
8358     if (ScalarTy->isRealFloatingType()) {
8359 
8360       // Reject cases where the scalar type is not a constant and has a higher
8361       // Order than the vector element type.
8362       llvm::APFloat Result(0.0);
8363       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8364       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8365       if (!CstScalar && Order < 0)
8366         return true;
8367 
8368       // If the scalar cannot be safely casted to the vector element type,
8369       // reject it.
8370       if (CstScalar) {
8371         bool Truncated = false;
8372         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8373                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8374         if (Truncated)
8375           return true;
8376       }
8377 
8378       ScalarCast = CK_FloatingCast;
8379     } else if (ScalarTy->isIntegralType(S.Context)) {
8380       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8381         return true;
8382 
8383       ScalarCast = CK_IntegralToFloating;
8384     } else
8385       return true;
8386   }
8387 
8388   // Adjust scalar if desired.
8389   if (Scalar) {
8390     if (ScalarCast != CK_NoOp)
8391       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8392     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8393   }
8394   return false;
8395 }
8396 
8397 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8398                                    SourceLocation Loc, bool IsCompAssign,
8399                                    bool AllowBothBool,
8400                                    bool AllowBoolConversions) {
8401   if (!IsCompAssign) {
8402     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8403     if (LHS.isInvalid())
8404       return QualType();
8405   }
8406   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8407   if (RHS.isInvalid())
8408     return QualType();
8409 
8410   // For conversion purposes, we ignore any qualifiers.
8411   // For example, "const float" and "float" are equivalent.
8412   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8413   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8414 
8415   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8416   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8417   assert(LHSVecType || RHSVecType);
8418 
8419   // AltiVec-style "vector bool op vector bool" combinations are allowed
8420   // for some operators but not others.
8421   if (!AllowBothBool &&
8422       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8423       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8424     return InvalidOperands(Loc, LHS, RHS);
8425 
8426   // If the vector types are identical, return.
8427   if (Context.hasSameType(LHSType, RHSType))
8428     return LHSType;
8429 
8430   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8431   if (LHSVecType && RHSVecType &&
8432       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8433     if (isa<ExtVectorType>(LHSVecType)) {
8434       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8435       return LHSType;
8436     }
8437 
8438     if (!IsCompAssign)
8439       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8440     return RHSType;
8441   }
8442 
8443   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8444   // can be mixed, with the result being the non-bool type.  The non-bool
8445   // operand must have integer element type.
8446   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8447       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8448       (Context.getTypeSize(LHSVecType->getElementType()) ==
8449        Context.getTypeSize(RHSVecType->getElementType()))) {
8450     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8451         LHSVecType->getElementType()->isIntegerType() &&
8452         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8453       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8454       return LHSType;
8455     }
8456     if (!IsCompAssign &&
8457         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8458         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8459         RHSVecType->getElementType()->isIntegerType()) {
8460       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8461       return RHSType;
8462     }
8463   }
8464 
8465   // If there's a vector type and a scalar, try to convert the scalar to
8466   // the vector element type and splat.
8467   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8468   if (!RHSVecType) {
8469     if (isa<ExtVectorType>(LHSVecType)) {
8470       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8471                                     LHSVecType->getElementType(), LHSType,
8472                                     DiagID))
8473         return LHSType;
8474     } else {
8475       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8476         return LHSType;
8477     }
8478   }
8479   if (!LHSVecType) {
8480     if (isa<ExtVectorType>(RHSVecType)) {
8481       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8482                                     LHSType, RHSVecType->getElementType(),
8483                                     RHSType, DiagID))
8484         return RHSType;
8485     } else {
8486       if (LHS.get()->getValueKind() == VK_LValue ||
8487           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8488         return RHSType;
8489     }
8490   }
8491 
8492   // FIXME: The code below also handles conversion between vectors and
8493   // non-scalars, we should break this down into fine grained specific checks
8494   // and emit proper diagnostics.
8495   QualType VecType = LHSVecType ? LHSType : RHSType;
8496   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8497   QualType OtherType = LHSVecType ? RHSType : LHSType;
8498   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8499   if (isLaxVectorConversion(OtherType, VecType)) {
8500     // If we're allowing lax vector conversions, only the total (data) size
8501     // needs to be the same. For non compound assignment, if one of the types is
8502     // scalar, the result is always the vector type.
8503     if (!IsCompAssign) {
8504       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8505       return VecType;
8506     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8507     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8508     // type. Note that this is already done by non-compound assignments in
8509     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8510     // <1 x T> -> T. The result is also a vector type.
8511     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8512                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8513       ExprResult *RHSExpr = &RHS;
8514       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8515       return VecType;
8516     }
8517   }
8518 
8519   // Okay, the expression is invalid.
8520 
8521   // If there's a non-vector, non-real operand, diagnose that.
8522   if ((!RHSVecType && !RHSType->isRealType()) ||
8523       (!LHSVecType && !LHSType->isRealType())) {
8524     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8525       << LHSType << RHSType
8526       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8527     return QualType();
8528   }
8529 
8530   // OpenCL V1.1 6.2.6.p1:
8531   // If the operands are of more than one vector type, then an error shall
8532   // occur. Implicit conversions between vector types are not permitted, per
8533   // section 6.2.1.
8534   if (getLangOpts().OpenCL &&
8535       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8536       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8537     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8538                                                            << RHSType;
8539     return QualType();
8540   }
8541 
8542 
8543   // If there is a vector type that is not a ExtVector and a scalar, we reach
8544   // this point if scalar could not be converted to the vector's element type
8545   // without truncation.
8546   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8547       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8548     QualType Scalar = LHSVecType ? RHSType : LHSType;
8549     QualType Vector = LHSVecType ? LHSType : RHSType;
8550     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8551     Diag(Loc,
8552          diag::err_typecheck_vector_not_convertable_implict_truncation)
8553         << ScalarOrVector << Scalar << Vector;
8554 
8555     return QualType();
8556   }
8557 
8558   // Otherwise, use the generic diagnostic.
8559   Diag(Loc, DiagID)
8560     << LHSType << RHSType
8561     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8562   return QualType();
8563 }
8564 
8565 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8566 // expression.  These are mainly cases where the null pointer is used as an
8567 // integer instead of a pointer.
8568 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8569                                 SourceLocation Loc, bool IsCompare) {
8570   // The canonical way to check for a GNU null is with isNullPointerConstant,
8571   // but we use a bit of a hack here for speed; this is a relatively
8572   // hot path, and isNullPointerConstant is slow.
8573   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8574   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8575 
8576   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8577 
8578   // Avoid analyzing cases where the result will either be invalid (and
8579   // diagnosed as such) or entirely valid and not something to warn about.
8580   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8581       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8582     return;
8583 
8584   // Comparison operations would not make sense with a null pointer no matter
8585   // what the other expression is.
8586   if (!IsCompare) {
8587     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8588         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8589         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8590     return;
8591   }
8592 
8593   // The rest of the operations only make sense with a null pointer
8594   // if the other expression is a pointer.
8595   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8596       NonNullType->canDecayToPointerType())
8597     return;
8598 
8599   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8600       << LHSNull /* LHS is NULL */ << NonNullType
8601       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8602 }
8603 
8604 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8605                                                ExprResult &RHS,
8606                                                SourceLocation Loc, bool IsDiv) {
8607   // Check for division/remainder by zero.
8608   llvm::APSInt RHSValue;
8609   if (!RHS.get()->isValueDependent() &&
8610       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8611     S.DiagRuntimeBehavior(Loc, RHS.get(),
8612                           S.PDiag(diag::warn_remainder_division_by_zero)
8613                             << IsDiv << RHS.get()->getSourceRange());
8614 }
8615 
8616 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8617                                            SourceLocation Loc,
8618                                            bool IsCompAssign, bool IsDiv) {
8619   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8620 
8621   if (LHS.get()->getType()->isVectorType() ||
8622       RHS.get()->getType()->isVectorType())
8623     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8624                                /*AllowBothBool*/getLangOpts().AltiVec,
8625                                /*AllowBoolConversions*/false);
8626 
8627   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8628   if (LHS.isInvalid() || RHS.isInvalid())
8629     return QualType();
8630 
8631 
8632   if (compType.isNull() || !compType->isArithmeticType())
8633     return InvalidOperands(Loc, LHS, RHS);
8634   if (IsDiv)
8635     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8636   return compType;
8637 }
8638 
8639 QualType Sema::CheckRemainderOperands(
8640   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8641   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8642 
8643   if (LHS.get()->getType()->isVectorType() ||
8644       RHS.get()->getType()->isVectorType()) {
8645     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8646         RHS.get()->getType()->hasIntegerRepresentation())
8647       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8648                                  /*AllowBothBool*/getLangOpts().AltiVec,
8649                                  /*AllowBoolConversions*/false);
8650     return InvalidOperands(Loc, LHS, RHS);
8651   }
8652 
8653   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8654   if (LHS.isInvalid() || RHS.isInvalid())
8655     return QualType();
8656 
8657   if (compType.isNull() || !compType->isIntegerType())
8658     return InvalidOperands(Loc, LHS, RHS);
8659   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8660   return compType;
8661 }
8662 
8663 /// Diagnose invalid arithmetic on two void pointers.
8664 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8665                                                 Expr *LHSExpr, Expr *RHSExpr) {
8666   S.Diag(Loc, S.getLangOpts().CPlusPlus
8667                 ? diag::err_typecheck_pointer_arith_void_type
8668                 : diag::ext_gnu_void_ptr)
8669     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8670                             << RHSExpr->getSourceRange();
8671 }
8672 
8673 /// Diagnose invalid arithmetic on a void pointer.
8674 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8675                                             Expr *Pointer) {
8676   S.Diag(Loc, S.getLangOpts().CPlusPlus
8677                 ? diag::err_typecheck_pointer_arith_void_type
8678                 : diag::ext_gnu_void_ptr)
8679     << 0 /* one pointer */ << Pointer->getSourceRange();
8680 }
8681 
8682 /// Diagnose invalid arithmetic on a null pointer.
8683 ///
8684 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8685 /// idiom, which we recognize as a GNU extension.
8686 ///
8687 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8688                                             Expr *Pointer, bool IsGNUIdiom) {
8689   if (IsGNUIdiom)
8690     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8691       << Pointer->getSourceRange();
8692   else
8693     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8694       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8695 }
8696 
8697 /// Diagnose invalid arithmetic on two function pointers.
8698 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8699                                                     Expr *LHS, Expr *RHS) {
8700   assert(LHS->getType()->isAnyPointerType());
8701   assert(RHS->getType()->isAnyPointerType());
8702   S.Diag(Loc, S.getLangOpts().CPlusPlus
8703                 ? diag::err_typecheck_pointer_arith_function_type
8704                 : diag::ext_gnu_ptr_func_arith)
8705     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8706     // We only show the second type if it differs from the first.
8707     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8708                                                    RHS->getType())
8709     << RHS->getType()->getPointeeType()
8710     << LHS->getSourceRange() << RHS->getSourceRange();
8711 }
8712 
8713 /// Diagnose invalid arithmetic on a function pointer.
8714 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8715                                                 Expr *Pointer) {
8716   assert(Pointer->getType()->isAnyPointerType());
8717   S.Diag(Loc, S.getLangOpts().CPlusPlus
8718                 ? diag::err_typecheck_pointer_arith_function_type
8719                 : diag::ext_gnu_ptr_func_arith)
8720     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8721     << 0 /* one pointer, so only one type */
8722     << Pointer->getSourceRange();
8723 }
8724 
8725 /// Emit error if Operand is incomplete pointer type
8726 ///
8727 /// \returns True if pointer has incomplete type
8728 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8729                                                  Expr *Operand) {
8730   QualType ResType = Operand->getType();
8731   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8732     ResType = ResAtomicType->getValueType();
8733 
8734   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8735   QualType PointeeTy = ResType->getPointeeType();
8736   return S.RequireCompleteType(Loc, PointeeTy,
8737                                diag::err_typecheck_arithmetic_incomplete_type,
8738                                PointeeTy, Operand->getSourceRange());
8739 }
8740 
8741 /// Check the validity of an arithmetic pointer operand.
8742 ///
8743 /// If the operand has pointer type, this code will check for pointer types
8744 /// which are invalid in arithmetic operations. These will be diagnosed
8745 /// appropriately, including whether or not the use is supported as an
8746 /// extension.
8747 ///
8748 /// \returns True when the operand is valid to use (even if as an extension).
8749 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8750                                             Expr *Operand) {
8751   QualType ResType = Operand->getType();
8752   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8753     ResType = ResAtomicType->getValueType();
8754 
8755   if (!ResType->isAnyPointerType()) return true;
8756 
8757   QualType PointeeTy = ResType->getPointeeType();
8758   if (PointeeTy->isVoidType()) {
8759     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8760     return !S.getLangOpts().CPlusPlus;
8761   }
8762   if (PointeeTy->isFunctionType()) {
8763     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8764     return !S.getLangOpts().CPlusPlus;
8765   }
8766 
8767   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8768 
8769   return true;
8770 }
8771 
8772 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8773 /// operands.
8774 ///
8775 /// This routine will diagnose any invalid arithmetic on pointer operands much
8776 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8777 /// for emitting a single diagnostic even for operations where both LHS and RHS
8778 /// are (potentially problematic) pointers.
8779 ///
8780 /// \returns True when the operand is valid to use (even if as an extension).
8781 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8782                                                 Expr *LHSExpr, Expr *RHSExpr) {
8783   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8784   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8785   if (!isLHSPointer && !isRHSPointer) return true;
8786 
8787   QualType LHSPointeeTy, RHSPointeeTy;
8788   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8789   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8790 
8791   // if both are pointers check if operation is valid wrt address spaces
8792   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8793     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8794     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8795     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8796       S.Diag(Loc,
8797              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8798           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8799           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8800       return false;
8801     }
8802   }
8803 
8804   // Check for arithmetic on pointers to incomplete types.
8805   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8806   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8807   if (isLHSVoidPtr || isRHSVoidPtr) {
8808     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8809     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8810     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8811 
8812     return !S.getLangOpts().CPlusPlus;
8813   }
8814 
8815   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8816   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8817   if (isLHSFuncPtr || isRHSFuncPtr) {
8818     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8819     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8820                                                                 RHSExpr);
8821     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8822 
8823     return !S.getLangOpts().CPlusPlus;
8824   }
8825 
8826   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8827     return false;
8828   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8829     return false;
8830 
8831   return true;
8832 }
8833 
8834 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8835 /// literal.
8836 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8837                                   Expr *LHSExpr, Expr *RHSExpr) {
8838   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8839   Expr* IndexExpr = RHSExpr;
8840   if (!StrExpr) {
8841     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8842     IndexExpr = LHSExpr;
8843   }
8844 
8845   bool IsStringPlusInt = StrExpr &&
8846       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8847   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8848     return;
8849 
8850   llvm::APSInt index;
8851   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8852     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8853     if (index.isNonNegative() &&
8854         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8855                               index.isUnsigned()))
8856       return;
8857   }
8858 
8859   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8860   Self.Diag(OpLoc, diag::warn_string_plus_int)
8861       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8862 
8863   // Only print a fixit for "str" + int, not for int + "str".
8864   if (IndexExpr == RHSExpr) {
8865     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8866     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8867         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8868         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8869         << FixItHint::CreateInsertion(EndLoc, "]");
8870   } else
8871     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8872 }
8873 
8874 /// Emit a warning when adding a char literal to a string.
8875 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8876                                    Expr *LHSExpr, Expr *RHSExpr) {
8877   const Expr *StringRefExpr = LHSExpr;
8878   const CharacterLiteral *CharExpr =
8879       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8880 
8881   if (!CharExpr) {
8882     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8883     StringRefExpr = RHSExpr;
8884   }
8885 
8886   if (!CharExpr || !StringRefExpr)
8887     return;
8888 
8889   const QualType StringType = StringRefExpr->getType();
8890 
8891   // Return if not a PointerType.
8892   if (!StringType->isAnyPointerType())
8893     return;
8894 
8895   // Return if not a CharacterType.
8896   if (!StringType->getPointeeType()->isAnyCharacterType())
8897     return;
8898 
8899   ASTContext &Ctx = Self.getASTContext();
8900   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8901 
8902   const QualType CharType = CharExpr->getType();
8903   if (!CharType->isAnyCharacterType() &&
8904       CharType->isIntegerType() &&
8905       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8906     Self.Diag(OpLoc, diag::warn_string_plus_char)
8907         << DiagRange << Ctx.CharTy;
8908   } else {
8909     Self.Diag(OpLoc, diag::warn_string_plus_char)
8910         << DiagRange << CharExpr->getType();
8911   }
8912 
8913   // Only print a fixit for str + char, not for char + str.
8914   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8915     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8916     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8917         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8918         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8919         << FixItHint::CreateInsertion(EndLoc, "]");
8920   } else {
8921     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8922   }
8923 }
8924 
8925 /// Emit error when two pointers are incompatible.
8926 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8927                                            Expr *LHSExpr, Expr *RHSExpr) {
8928   assert(LHSExpr->getType()->isAnyPointerType());
8929   assert(RHSExpr->getType()->isAnyPointerType());
8930   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8931     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8932     << RHSExpr->getSourceRange();
8933 }
8934 
8935 // C99 6.5.6
8936 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8937                                      SourceLocation Loc, BinaryOperatorKind Opc,
8938                                      QualType* CompLHSTy) {
8939   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8940 
8941   if (LHS.get()->getType()->isVectorType() ||
8942       RHS.get()->getType()->isVectorType()) {
8943     QualType compType = CheckVectorOperands(
8944         LHS, RHS, Loc, CompLHSTy,
8945         /*AllowBothBool*/getLangOpts().AltiVec,
8946         /*AllowBoolConversions*/getLangOpts().ZVector);
8947     if (CompLHSTy) *CompLHSTy = compType;
8948     return compType;
8949   }
8950 
8951   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8952   if (LHS.isInvalid() || RHS.isInvalid())
8953     return QualType();
8954 
8955   // Diagnose "string literal" '+' int and string '+' "char literal".
8956   if (Opc == BO_Add) {
8957     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8958     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8959   }
8960 
8961   // handle the common case first (both operands are arithmetic).
8962   if (!compType.isNull() && compType->isArithmeticType()) {
8963     if (CompLHSTy) *CompLHSTy = compType;
8964     return compType;
8965   }
8966 
8967   // Type-checking.  Ultimately the pointer's going to be in PExp;
8968   // note that we bias towards the LHS being the pointer.
8969   Expr *PExp = LHS.get(), *IExp = RHS.get();
8970 
8971   bool isObjCPointer;
8972   if (PExp->getType()->isPointerType()) {
8973     isObjCPointer = false;
8974   } else if (PExp->getType()->isObjCObjectPointerType()) {
8975     isObjCPointer = true;
8976   } else {
8977     std::swap(PExp, IExp);
8978     if (PExp->getType()->isPointerType()) {
8979       isObjCPointer = false;
8980     } else if (PExp->getType()->isObjCObjectPointerType()) {
8981       isObjCPointer = true;
8982     } else {
8983       return InvalidOperands(Loc, LHS, RHS);
8984     }
8985   }
8986   assert(PExp->getType()->isAnyPointerType());
8987 
8988   if (!IExp->getType()->isIntegerType())
8989     return InvalidOperands(Loc, LHS, RHS);
8990 
8991   // Adding to a null pointer results in undefined behavior.
8992   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
8993           Context, Expr::NPC_ValueDependentIsNotNull)) {
8994     // In C++ adding zero to a null pointer is defined.
8995     llvm::APSInt KnownVal;
8996     if (!getLangOpts().CPlusPlus ||
8997         (!IExp->isValueDependent() &&
8998          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
8999       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9000       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9001           Context, BO_Add, PExp, IExp);
9002       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9003     }
9004   }
9005 
9006   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9007     return QualType();
9008 
9009   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9010     return QualType();
9011 
9012   // Check array bounds for pointer arithemtic
9013   CheckArrayAccess(PExp, IExp);
9014 
9015   if (CompLHSTy) {
9016     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9017     if (LHSTy.isNull()) {
9018       LHSTy = LHS.get()->getType();
9019       if (LHSTy->isPromotableIntegerType())
9020         LHSTy = Context.getPromotedIntegerType(LHSTy);
9021     }
9022     *CompLHSTy = LHSTy;
9023   }
9024 
9025   return PExp->getType();
9026 }
9027 
9028 // C99 6.5.6
9029 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9030                                         SourceLocation Loc,
9031                                         QualType* CompLHSTy) {
9032   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9033 
9034   if (LHS.get()->getType()->isVectorType() ||
9035       RHS.get()->getType()->isVectorType()) {
9036     QualType compType = CheckVectorOperands(
9037         LHS, RHS, Loc, CompLHSTy,
9038         /*AllowBothBool*/getLangOpts().AltiVec,
9039         /*AllowBoolConversions*/getLangOpts().ZVector);
9040     if (CompLHSTy) *CompLHSTy = compType;
9041     return compType;
9042   }
9043 
9044   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9045   if (LHS.isInvalid() || RHS.isInvalid())
9046     return QualType();
9047 
9048   // Enforce type constraints: C99 6.5.6p3.
9049 
9050   // Handle the common case first (both operands are arithmetic).
9051   if (!compType.isNull() && compType->isArithmeticType()) {
9052     if (CompLHSTy) *CompLHSTy = compType;
9053     return compType;
9054   }
9055 
9056   // Either ptr - int   or   ptr - ptr.
9057   if (LHS.get()->getType()->isAnyPointerType()) {
9058     QualType lpointee = LHS.get()->getType()->getPointeeType();
9059 
9060     // Diagnose bad cases where we step over interface counts.
9061     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9062         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9063       return QualType();
9064 
9065     // The result type of a pointer-int computation is the pointer type.
9066     if (RHS.get()->getType()->isIntegerType()) {
9067       // Subtracting from a null pointer should produce a warning.
9068       // The last argument to the diagnose call says this doesn't match the
9069       // GNU int-to-pointer idiom.
9070       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9071                                            Expr::NPC_ValueDependentIsNotNull)) {
9072         // In C++ adding zero to a null pointer is defined.
9073         llvm::APSInt KnownVal;
9074         if (!getLangOpts().CPlusPlus ||
9075             (!RHS.get()->isValueDependent() &&
9076              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9077           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9078         }
9079       }
9080 
9081       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9082         return QualType();
9083 
9084       // Check array bounds for pointer arithemtic
9085       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9086                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9087 
9088       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9089       return LHS.get()->getType();
9090     }
9091 
9092     // Handle pointer-pointer subtractions.
9093     if (const PointerType *RHSPTy
9094           = RHS.get()->getType()->getAs<PointerType>()) {
9095       QualType rpointee = RHSPTy->getPointeeType();
9096 
9097       if (getLangOpts().CPlusPlus) {
9098         // Pointee types must be the same: C++ [expr.add]
9099         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9100           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9101         }
9102       } else {
9103         // Pointee types must be compatible C99 6.5.6p3
9104         if (!Context.typesAreCompatible(
9105                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9106                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9107           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9108           return QualType();
9109         }
9110       }
9111 
9112       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9113                                                LHS.get(), RHS.get()))
9114         return QualType();
9115 
9116       // FIXME: Add warnings for nullptr - ptr.
9117 
9118       // The pointee type may have zero size.  As an extension, a structure or
9119       // union may have zero size or an array may have zero length.  In this
9120       // case subtraction does not make sense.
9121       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9122         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9123         if (ElementSize.isZero()) {
9124           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9125             << rpointee.getUnqualifiedType()
9126             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9127         }
9128       }
9129 
9130       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9131       return Context.getPointerDiffType();
9132     }
9133   }
9134 
9135   return InvalidOperands(Loc, LHS, RHS);
9136 }
9137 
9138 static bool isScopedEnumerationType(QualType T) {
9139   if (const EnumType *ET = T->getAs<EnumType>())
9140     return ET->getDecl()->isScoped();
9141   return false;
9142 }
9143 
9144 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9145                                    SourceLocation Loc, BinaryOperatorKind Opc,
9146                                    QualType LHSType) {
9147   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9148   // so skip remaining warnings as we don't want to modify values within Sema.
9149   if (S.getLangOpts().OpenCL)
9150     return;
9151 
9152   llvm::APSInt Right;
9153   // Check right/shifter operand
9154   if (RHS.get()->isValueDependent() ||
9155       !RHS.get()->EvaluateAsInt(Right, S.Context))
9156     return;
9157 
9158   if (Right.isNegative()) {
9159     S.DiagRuntimeBehavior(Loc, RHS.get(),
9160                           S.PDiag(diag::warn_shift_negative)
9161                             << RHS.get()->getSourceRange());
9162     return;
9163   }
9164   llvm::APInt LeftBits(Right.getBitWidth(),
9165                        S.Context.getTypeSize(LHS.get()->getType()));
9166   if (Right.uge(LeftBits)) {
9167     S.DiagRuntimeBehavior(Loc, RHS.get(),
9168                           S.PDiag(diag::warn_shift_gt_typewidth)
9169                             << RHS.get()->getSourceRange());
9170     return;
9171   }
9172   if (Opc != BO_Shl)
9173     return;
9174 
9175   // When left shifting an ICE which is signed, we can check for overflow which
9176   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9177   // integers have defined behavior modulo one more than the maximum value
9178   // representable in the result type, so never warn for those.
9179   llvm::APSInt Left;
9180   if (LHS.get()->isValueDependent() ||
9181       LHSType->hasUnsignedIntegerRepresentation() ||
9182       !LHS.get()->EvaluateAsInt(Left, S.Context))
9183     return;
9184 
9185   // If LHS does not have a signed type and non-negative value
9186   // then, the behavior is undefined. Warn about it.
9187   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9188     S.DiagRuntimeBehavior(Loc, LHS.get(),
9189                           S.PDiag(diag::warn_shift_lhs_negative)
9190                             << LHS.get()->getSourceRange());
9191     return;
9192   }
9193 
9194   llvm::APInt ResultBits =
9195       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9196   if (LeftBits.uge(ResultBits))
9197     return;
9198   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9199   Result = Result.shl(Right);
9200 
9201   // Print the bit representation of the signed integer as an unsigned
9202   // hexadecimal number.
9203   SmallString<40> HexResult;
9204   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9205 
9206   // If we are only missing a sign bit, this is less likely to result in actual
9207   // bugs -- if the result is cast back to an unsigned type, it will have the
9208   // expected value. Thus we place this behind a different warning that can be
9209   // turned off separately if needed.
9210   if (LeftBits == ResultBits - 1) {
9211     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9212         << HexResult << LHSType
9213         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9214     return;
9215   }
9216 
9217   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9218     << HexResult.str() << Result.getMinSignedBits() << LHSType
9219     << Left.getBitWidth() << LHS.get()->getSourceRange()
9220     << RHS.get()->getSourceRange();
9221 }
9222 
9223 /// Return the resulting type when a vector is shifted
9224 ///        by a scalar or vector shift amount.
9225 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9226                                  SourceLocation Loc, bool IsCompAssign) {
9227   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9228   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9229       !LHS.get()->getType()->isVectorType()) {
9230     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9231       << RHS.get()->getType() << LHS.get()->getType()
9232       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9233     return QualType();
9234   }
9235 
9236   if (!IsCompAssign) {
9237     LHS = S.UsualUnaryConversions(LHS.get());
9238     if (LHS.isInvalid()) return QualType();
9239   }
9240 
9241   RHS = S.UsualUnaryConversions(RHS.get());
9242   if (RHS.isInvalid()) return QualType();
9243 
9244   QualType LHSType = LHS.get()->getType();
9245   // Note that LHS might be a scalar because the routine calls not only in
9246   // OpenCL case.
9247   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9248   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9249 
9250   // Note that RHS might not be a vector.
9251   QualType RHSType = RHS.get()->getType();
9252   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9253   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9254 
9255   // The operands need to be integers.
9256   if (!LHSEleType->isIntegerType()) {
9257     S.Diag(Loc, diag::err_typecheck_expect_int)
9258       << LHS.get()->getType() << LHS.get()->getSourceRange();
9259     return QualType();
9260   }
9261 
9262   if (!RHSEleType->isIntegerType()) {
9263     S.Diag(Loc, diag::err_typecheck_expect_int)
9264       << RHS.get()->getType() << RHS.get()->getSourceRange();
9265     return QualType();
9266   }
9267 
9268   if (!LHSVecTy) {
9269     assert(RHSVecTy);
9270     if (IsCompAssign)
9271       return RHSType;
9272     if (LHSEleType != RHSEleType) {
9273       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9274       LHSEleType = RHSEleType;
9275     }
9276     QualType VecTy =
9277         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9278     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9279     LHSType = VecTy;
9280   } else if (RHSVecTy) {
9281     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9282     // are applied component-wise. So if RHS is a vector, then ensure
9283     // that the number of elements is the same as LHS...
9284     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9285       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9286         << LHS.get()->getType() << RHS.get()->getType()
9287         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9288       return QualType();
9289     }
9290     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9291       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9292       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9293       if (LHSBT != RHSBT &&
9294           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9295         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9296             << LHS.get()->getType() << RHS.get()->getType()
9297             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9298       }
9299     }
9300   } else {
9301     // ...else expand RHS to match the number of elements in LHS.
9302     QualType VecTy =
9303       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9304     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9305   }
9306 
9307   return LHSType;
9308 }
9309 
9310 // C99 6.5.7
9311 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9312                                   SourceLocation Loc, BinaryOperatorKind Opc,
9313                                   bool IsCompAssign) {
9314   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9315 
9316   // Vector shifts promote their scalar inputs to vector type.
9317   if (LHS.get()->getType()->isVectorType() ||
9318       RHS.get()->getType()->isVectorType()) {
9319     if (LangOpts.ZVector) {
9320       // The shift operators for the z vector extensions work basically
9321       // like general shifts, except that neither the LHS nor the RHS is
9322       // allowed to be a "vector bool".
9323       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9324         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9325           return InvalidOperands(Loc, LHS, RHS);
9326       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9327         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9328           return InvalidOperands(Loc, LHS, RHS);
9329     }
9330     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9331   }
9332 
9333   // Shifts don't perform usual arithmetic conversions, they just do integer
9334   // promotions on each operand. C99 6.5.7p3
9335 
9336   // For the LHS, do usual unary conversions, but then reset them away
9337   // if this is a compound assignment.
9338   ExprResult OldLHS = LHS;
9339   LHS = UsualUnaryConversions(LHS.get());
9340   if (LHS.isInvalid())
9341     return QualType();
9342   QualType LHSType = LHS.get()->getType();
9343   if (IsCompAssign) LHS = OldLHS;
9344 
9345   // The RHS is simpler.
9346   RHS = UsualUnaryConversions(RHS.get());
9347   if (RHS.isInvalid())
9348     return QualType();
9349   QualType RHSType = RHS.get()->getType();
9350 
9351   // C99 6.5.7p2: Each of the operands shall have integer type.
9352   if (!LHSType->hasIntegerRepresentation() ||
9353       !RHSType->hasIntegerRepresentation())
9354     return InvalidOperands(Loc, LHS, RHS);
9355 
9356   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9357   // hasIntegerRepresentation() above instead of this.
9358   if (isScopedEnumerationType(LHSType) ||
9359       isScopedEnumerationType(RHSType)) {
9360     return InvalidOperands(Loc, LHS, RHS);
9361   }
9362   // Sanity-check shift operands
9363   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9364 
9365   // "The type of the result is that of the promoted left operand."
9366   return LHSType;
9367 }
9368 
9369 /// If two different enums are compared, raise a warning.
9370 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9371                                 Expr *RHS) {
9372   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9373   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9374 
9375   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9376   if (!LHSEnumType)
9377     return;
9378   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9379   if (!RHSEnumType)
9380     return;
9381 
9382   // Ignore anonymous enums.
9383   if (!LHSEnumType->getDecl()->getIdentifier() &&
9384       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9385     return;
9386   if (!RHSEnumType->getDecl()->getIdentifier() &&
9387       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9388     return;
9389 
9390   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9391     return;
9392 
9393   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9394       << LHSStrippedType << RHSStrippedType
9395       << LHS->getSourceRange() << RHS->getSourceRange();
9396 }
9397 
9398 /// Diagnose bad pointer comparisons.
9399 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9400                                               ExprResult &LHS, ExprResult &RHS,
9401                                               bool IsError) {
9402   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9403                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9404     << LHS.get()->getType() << RHS.get()->getType()
9405     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9406 }
9407 
9408 /// Returns false if the pointers are converted to a composite type,
9409 /// true otherwise.
9410 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9411                                            ExprResult &LHS, ExprResult &RHS) {
9412   // C++ [expr.rel]p2:
9413   //   [...] Pointer conversions (4.10) and qualification
9414   //   conversions (4.4) are performed on pointer operands (or on
9415   //   a pointer operand and a null pointer constant) to bring
9416   //   them to their composite pointer type. [...]
9417   //
9418   // C++ [expr.eq]p1 uses the same notion for (in)equality
9419   // comparisons of pointers.
9420 
9421   QualType LHSType = LHS.get()->getType();
9422   QualType RHSType = RHS.get()->getType();
9423   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9424          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9425 
9426   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9427   if (T.isNull()) {
9428     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9429         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9430       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9431     else
9432       S.InvalidOperands(Loc, LHS, RHS);
9433     return true;
9434   }
9435 
9436   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9437   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9438   return false;
9439 }
9440 
9441 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9442                                                     ExprResult &LHS,
9443                                                     ExprResult &RHS,
9444                                                     bool IsError) {
9445   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9446                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9447     << LHS.get()->getType() << RHS.get()->getType()
9448     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9449 }
9450 
9451 static bool isObjCObjectLiteral(ExprResult &E) {
9452   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9453   case Stmt::ObjCArrayLiteralClass:
9454   case Stmt::ObjCDictionaryLiteralClass:
9455   case Stmt::ObjCStringLiteralClass:
9456   case Stmt::ObjCBoxedExprClass:
9457     return true;
9458   default:
9459     // Note that ObjCBoolLiteral is NOT an object literal!
9460     return false;
9461   }
9462 }
9463 
9464 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9465   const ObjCObjectPointerType *Type =
9466     LHS->getType()->getAs<ObjCObjectPointerType>();
9467 
9468   // If this is not actually an Objective-C object, bail out.
9469   if (!Type)
9470     return false;
9471 
9472   // Get the LHS object's interface type.
9473   QualType InterfaceType = Type->getPointeeType();
9474 
9475   // If the RHS isn't an Objective-C object, bail out.
9476   if (!RHS->getType()->isObjCObjectPointerType())
9477     return false;
9478 
9479   // Try to find the -isEqual: method.
9480   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9481   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9482                                                       InterfaceType,
9483                                                       /*instance=*/true);
9484   if (!Method) {
9485     if (Type->isObjCIdType()) {
9486       // For 'id', just check the global pool.
9487       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9488                                                   /*receiverId=*/true);
9489     } else {
9490       // Check protocols.
9491       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9492                                              /*instance=*/true);
9493     }
9494   }
9495 
9496   if (!Method)
9497     return false;
9498 
9499   QualType T = Method->parameters()[0]->getType();
9500   if (!T->isObjCObjectPointerType())
9501     return false;
9502 
9503   QualType R = Method->getReturnType();
9504   if (!R->isScalarType())
9505     return false;
9506 
9507   return true;
9508 }
9509 
9510 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9511   FromE = FromE->IgnoreParenImpCasts();
9512   switch (FromE->getStmtClass()) {
9513     default:
9514       break;
9515     case Stmt::ObjCStringLiteralClass:
9516       // "string literal"
9517       return LK_String;
9518     case Stmt::ObjCArrayLiteralClass:
9519       // "array literal"
9520       return LK_Array;
9521     case Stmt::ObjCDictionaryLiteralClass:
9522       // "dictionary literal"
9523       return LK_Dictionary;
9524     case Stmt::BlockExprClass:
9525       return LK_Block;
9526     case Stmt::ObjCBoxedExprClass: {
9527       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9528       switch (Inner->getStmtClass()) {
9529         case Stmt::IntegerLiteralClass:
9530         case Stmt::FloatingLiteralClass:
9531         case Stmt::CharacterLiteralClass:
9532         case Stmt::ObjCBoolLiteralExprClass:
9533         case Stmt::CXXBoolLiteralExprClass:
9534           // "numeric literal"
9535           return LK_Numeric;
9536         case Stmt::ImplicitCastExprClass: {
9537           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9538           // Boolean literals can be represented by implicit casts.
9539           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9540             return LK_Numeric;
9541           break;
9542         }
9543         default:
9544           break;
9545       }
9546       return LK_Boxed;
9547     }
9548   }
9549   return LK_None;
9550 }
9551 
9552 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9553                                           ExprResult &LHS, ExprResult &RHS,
9554                                           BinaryOperator::Opcode Opc){
9555   Expr *Literal;
9556   Expr *Other;
9557   if (isObjCObjectLiteral(LHS)) {
9558     Literal = LHS.get();
9559     Other = RHS.get();
9560   } else {
9561     Literal = RHS.get();
9562     Other = LHS.get();
9563   }
9564 
9565   // Don't warn on comparisons against nil.
9566   Other = Other->IgnoreParenCasts();
9567   if (Other->isNullPointerConstant(S.getASTContext(),
9568                                    Expr::NPC_ValueDependentIsNotNull))
9569     return;
9570 
9571   // This should be kept in sync with warn_objc_literal_comparison.
9572   // LK_String should always be after the other literals, since it has its own
9573   // warning flag.
9574   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9575   assert(LiteralKind != Sema::LK_Block);
9576   if (LiteralKind == Sema::LK_None) {
9577     llvm_unreachable("Unknown Objective-C object literal kind");
9578   }
9579 
9580   if (LiteralKind == Sema::LK_String)
9581     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9582       << Literal->getSourceRange();
9583   else
9584     S.Diag(Loc, diag::warn_objc_literal_comparison)
9585       << LiteralKind << Literal->getSourceRange();
9586 
9587   if (BinaryOperator::isEqualityOp(Opc) &&
9588       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9589     SourceLocation Start = LHS.get()->getLocStart();
9590     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9591     CharSourceRange OpRange =
9592       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9593 
9594     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9595       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9596       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9597       << FixItHint::CreateInsertion(End, "]");
9598   }
9599 }
9600 
9601 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9602 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9603                                            ExprResult &RHS, SourceLocation Loc,
9604                                            BinaryOperatorKind Opc) {
9605   // Check that left hand side is !something.
9606   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9607   if (!UO || UO->getOpcode() != UO_LNot) return;
9608 
9609   // Only check if the right hand side is non-bool arithmetic type.
9610   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9611 
9612   // Make sure that the something in !something is not bool.
9613   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9614   if (SubExpr->isKnownToHaveBooleanValue()) return;
9615 
9616   // Emit warning.
9617   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9618   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9619       << Loc << IsBitwiseOp;
9620 
9621   // First note suggest !(x < y)
9622   SourceLocation FirstOpen = SubExpr->getLocStart();
9623   SourceLocation FirstClose = RHS.get()->getLocEnd();
9624   FirstClose = S.getLocForEndOfToken(FirstClose);
9625   if (FirstClose.isInvalid())
9626     FirstOpen = SourceLocation();
9627   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9628       << IsBitwiseOp
9629       << FixItHint::CreateInsertion(FirstOpen, "(")
9630       << FixItHint::CreateInsertion(FirstClose, ")");
9631 
9632   // Second note suggests (!x) < y
9633   SourceLocation SecondOpen = LHS.get()->getLocStart();
9634   SourceLocation SecondClose = LHS.get()->getLocEnd();
9635   SecondClose = S.getLocForEndOfToken(SecondClose);
9636   if (SecondClose.isInvalid())
9637     SecondOpen = SourceLocation();
9638   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9639       << FixItHint::CreateInsertion(SecondOpen, "(")
9640       << FixItHint::CreateInsertion(SecondClose, ")");
9641 }
9642 
9643 // Get the decl for a simple expression: a reference to a variable,
9644 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9645 static ValueDecl *getCompareDecl(Expr *E) {
9646   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9647     return DR->getDecl();
9648   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9649     if (Ivar->isFreeIvar())
9650       return Ivar->getDecl();
9651   }
9652   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9653     if (Mem->isImplicitAccess())
9654       return Mem->getMemberDecl();
9655   }
9656   return nullptr;
9657 }
9658 
9659 /// Diagnose some forms of syntactically-obvious tautological comparison.
9660 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9661                                            Expr *LHS, Expr *RHS,
9662                                            BinaryOperatorKind Opc) {
9663   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9664   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9665 
9666   QualType LHSType = LHS->getType();
9667   QualType RHSType = RHS->getType();
9668   if (LHSType->hasFloatingRepresentation() ||
9669       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9670       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9671       S.inTemplateInstantiation())
9672     return;
9673 
9674   // Comparisons between two array types are ill-formed for operator<=>, so
9675   // we shouldn't emit any additional warnings about it.
9676   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9677     return;
9678 
9679   // For non-floating point types, check for self-comparisons of the form
9680   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9681   // often indicate logic errors in the program.
9682   //
9683   // NOTE: Don't warn about comparison expressions resulting from macro
9684   // expansion. Also don't warn about comparisons which are only self
9685   // comparisons within a template instantiation. The warnings should catch
9686   // obvious cases in the definition of the template anyways. The idea is to
9687   // warn when the typed comparison operator will always evaluate to the same
9688   // result.
9689   ValueDecl *DL = getCompareDecl(LHSStripped);
9690   ValueDecl *DR = getCompareDecl(RHSStripped);
9691   if (DL && DR && declaresSameEntity(DL, DR)) {
9692     StringRef Result;
9693     switch (Opc) {
9694     case BO_EQ: case BO_LE: case BO_GE:
9695       Result = "true";
9696       break;
9697     case BO_NE: case BO_LT: case BO_GT:
9698       Result = "false";
9699       break;
9700     case BO_Cmp:
9701       Result = "'std::strong_ordering::equal'";
9702       break;
9703     default:
9704       break;
9705     }
9706     S.DiagRuntimeBehavior(Loc, nullptr,
9707                           S.PDiag(diag::warn_comparison_always)
9708                               << 0 /*self-comparison*/ << !Result.empty()
9709                               << Result);
9710   } else if (DL && DR &&
9711              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9712              !DL->isWeak() && !DR->isWeak()) {
9713     // What is it always going to evaluate to?
9714     StringRef Result;
9715     switch(Opc) {
9716     case BO_EQ: // e.g. array1 == array2
9717       Result = "false";
9718       break;
9719     case BO_NE: // e.g. array1 != array2
9720       Result = "true";
9721       break;
9722     default: // e.g. array1 <= array2
9723       // The best we can say is 'a constant'
9724       break;
9725     }
9726     S.DiagRuntimeBehavior(Loc, nullptr,
9727                           S.PDiag(diag::warn_comparison_always)
9728                               << 1 /*array comparison*/
9729                               << !Result.empty() << Result);
9730   }
9731 
9732   if (isa<CastExpr>(LHSStripped))
9733     LHSStripped = LHSStripped->IgnoreParenCasts();
9734   if (isa<CastExpr>(RHSStripped))
9735     RHSStripped = RHSStripped->IgnoreParenCasts();
9736 
9737   // Warn about comparisons against a string constant (unless the other
9738   // operand is null); the user probably wants strcmp.
9739   Expr *LiteralString = nullptr;
9740   Expr *LiteralStringStripped = nullptr;
9741   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9742       !RHSStripped->isNullPointerConstant(S.Context,
9743                                           Expr::NPC_ValueDependentIsNull)) {
9744     LiteralString = LHS;
9745     LiteralStringStripped = LHSStripped;
9746   } else if ((isa<StringLiteral>(RHSStripped) ||
9747               isa<ObjCEncodeExpr>(RHSStripped)) &&
9748              !LHSStripped->isNullPointerConstant(S.Context,
9749                                           Expr::NPC_ValueDependentIsNull)) {
9750     LiteralString = RHS;
9751     LiteralStringStripped = RHSStripped;
9752   }
9753 
9754   if (LiteralString) {
9755     S.DiagRuntimeBehavior(Loc, nullptr,
9756                           S.PDiag(diag::warn_stringcompare)
9757                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9758                               << LiteralString->getSourceRange());
9759   }
9760 }
9761 
9762 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9763   switch (CK) {
9764   default: {
9765 #ifndef NDEBUG
9766     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9767                  << "\n";
9768 #endif
9769     llvm_unreachable("unhandled cast kind");
9770   }
9771   case CK_UserDefinedConversion:
9772     return ICK_Identity;
9773   case CK_LValueToRValue:
9774     return ICK_Lvalue_To_Rvalue;
9775   case CK_ArrayToPointerDecay:
9776     return ICK_Array_To_Pointer;
9777   case CK_FunctionToPointerDecay:
9778     return ICK_Function_To_Pointer;
9779   case CK_IntegralCast:
9780     return ICK_Integral_Conversion;
9781   case CK_FloatingCast:
9782     return ICK_Floating_Conversion;
9783   case CK_IntegralToFloating:
9784   case CK_FloatingToIntegral:
9785     return ICK_Floating_Integral;
9786   case CK_IntegralComplexCast:
9787   case CK_FloatingComplexCast:
9788   case CK_FloatingComplexToIntegralComplex:
9789   case CK_IntegralComplexToFloatingComplex:
9790     return ICK_Complex_Conversion;
9791   case CK_FloatingComplexToReal:
9792   case CK_FloatingRealToComplex:
9793   case CK_IntegralComplexToReal:
9794   case CK_IntegralRealToComplex:
9795     return ICK_Complex_Real;
9796   }
9797 }
9798 
9799 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9800                                              QualType FromType,
9801                                              SourceLocation Loc) {
9802   // Check for a narrowing implicit conversion.
9803   StandardConversionSequence SCS;
9804   SCS.setAsIdentityConversion();
9805   SCS.setToType(0, FromType);
9806   SCS.setToType(1, ToType);
9807   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9808     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9809 
9810   APValue PreNarrowingValue;
9811   QualType PreNarrowingType;
9812   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9813                                PreNarrowingType,
9814                                /*IgnoreFloatToIntegralConversion*/ true)) {
9815   case NK_Dependent_Narrowing:
9816     // Implicit conversion to a narrower type, but the expression is
9817     // value-dependent so we can't tell whether it's actually narrowing.
9818   case NK_Not_Narrowing:
9819     return false;
9820 
9821   case NK_Constant_Narrowing:
9822     // Implicit conversion to a narrower type, and the value is not a constant
9823     // expression.
9824     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9825         << /*Constant*/ 1
9826         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9827     return true;
9828 
9829   case NK_Variable_Narrowing:
9830     // Implicit conversion to a narrower type, and the value is not a constant
9831     // expression.
9832   case NK_Type_Narrowing:
9833     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9834         << /*Constant*/ 0 << FromType << ToType;
9835     // TODO: It's not a constant expression, but what if the user intended it
9836     // to be? Can we produce notes to help them figure out why it isn't?
9837     return true;
9838   }
9839   llvm_unreachable("unhandled case in switch");
9840 }
9841 
9842 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
9843                                                          ExprResult &LHS,
9844                                                          ExprResult &RHS,
9845                                                          SourceLocation Loc) {
9846   using CCT = ComparisonCategoryType;
9847 
9848   QualType LHSType = LHS.get()->getType();
9849   QualType RHSType = RHS.get()->getType();
9850   // Dig out the original argument type and expression before implicit casts
9851   // were applied. These are the types/expressions we need to check the
9852   // [expr.spaceship] requirements against.
9853   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9854   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9855   QualType LHSStrippedType = LHSStripped.get()->getType();
9856   QualType RHSStrippedType = RHSStripped.get()->getType();
9857 
9858   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9859   // other is not, the program is ill-formed.
9860   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9861     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9862     return QualType();
9863   }
9864 
9865   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9866                     RHSStrippedType->isEnumeralType();
9867   if (NumEnumArgs == 1) {
9868     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9869     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9870     if (OtherTy->hasFloatingRepresentation()) {
9871       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9872       return QualType();
9873     }
9874   }
9875   if (NumEnumArgs == 2) {
9876     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9877     // type E, the operator yields the result of converting the operands
9878     // to the underlying type of E and applying <=> to the converted operands.
9879     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
9880       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9881       return QualType();
9882     }
9883     QualType IntType =
9884         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
9885     assert(IntType->isArithmeticType());
9886 
9887     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
9888     // promote the boolean type, and all other promotable integer types, to
9889     // avoid this.
9890     if (IntType->isPromotableIntegerType())
9891       IntType = S.Context.getPromotedIntegerType(IntType);
9892 
9893     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
9894     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
9895     LHSType = RHSType = IntType;
9896   }
9897 
9898   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
9899   // usual arithmetic conversions are applied to the operands.
9900   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9901   if (LHS.isInvalid() || RHS.isInvalid())
9902     return QualType();
9903   if (Type.isNull())
9904     return S.InvalidOperands(Loc, LHS, RHS);
9905   assert(Type->isArithmeticType() || Type->isEnumeralType());
9906 
9907   bool HasNarrowing = checkThreeWayNarrowingConversion(
9908       S, Type, LHS.get(), LHSType, LHS.get()->getLocStart());
9909   HasNarrowing |= checkThreeWayNarrowingConversion(
9910       S, Type, RHS.get(), RHSType, RHS.get()->getLocStart());
9911   if (HasNarrowing)
9912     return QualType();
9913 
9914   assert(!Type.isNull() && "composite type for <=> has not been set");
9915 
9916   auto TypeKind = [&]() {
9917     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
9918       if (CT->getElementType()->hasFloatingRepresentation())
9919         return CCT::WeakEquality;
9920       return CCT::StrongEquality;
9921     }
9922     if (Type->isIntegralOrEnumerationType())
9923       return CCT::StrongOrdering;
9924     if (Type->hasFloatingRepresentation())
9925       return CCT::PartialOrdering;
9926     llvm_unreachable("other types are unimplemented");
9927   }();
9928 
9929   return S.CheckComparisonCategoryType(TypeKind, Loc);
9930 }
9931 
9932 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9933                                                  ExprResult &RHS,
9934                                                  SourceLocation Loc,
9935                                                  BinaryOperatorKind Opc) {
9936   if (Opc == BO_Cmp)
9937     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
9938 
9939   // C99 6.5.8p3 / C99 6.5.9p4
9940   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9941   if (LHS.isInvalid() || RHS.isInvalid())
9942     return QualType();
9943   if (Type.isNull())
9944     return S.InvalidOperands(Loc, LHS, RHS);
9945   assert(Type->isArithmeticType() || Type->isEnumeralType());
9946 
9947   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
9948 
9949   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
9950     return S.InvalidOperands(Loc, LHS, RHS);
9951 
9952   // Check for comparisons of floating point operands using != and ==.
9953   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
9954     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
9955 
9956   // The result of comparisons is 'bool' in C++, 'int' in C.
9957   return S.Context.getLogicalOperationType();
9958 }
9959 
9960 // C99 6.5.8, C++ [expr.rel]
9961 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9962                                     SourceLocation Loc,
9963                                     BinaryOperatorKind Opc) {
9964   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
9965   bool IsThreeWay = Opc == BO_Cmp;
9966   auto IsAnyPointerType = [](ExprResult E) {
9967     QualType Ty = E.get()->getType();
9968     return Ty->isPointerType() || Ty->isMemberPointerType();
9969   };
9970 
9971   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
9972   // type, array-to-pointer, ..., conversions are performed on both operands to
9973   // bring them to their composite type.
9974   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
9975   // any type-related checks.
9976   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
9977     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9978     if (LHS.isInvalid())
9979       return QualType();
9980     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9981     if (RHS.isInvalid())
9982       return QualType();
9983   } else {
9984     LHS = DefaultLvalueConversion(LHS.get());
9985     if (LHS.isInvalid())
9986       return QualType();
9987     RHS = DefaultLvalueConversion(RHS.get());
9988     if (RHS.isInvalid())
9989       return QualType();
9990   }
9991 
9992   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9993 
9994   // Handle vector comparisons separately.
9995   if (LHS.get()->getType()->isVectorType() ||
9996       RHS.get()->getType()->isVectorType())
9997     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
9998 
9999   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10000   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10001 
10002   QualType LHSType = LHS.get()->getType();
10003   QualType RHSType = RHS.get()->getType();
10004   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10005       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10006     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10007 
10008   const Expr::NullPointerConstantKind LHSNullKind =
10009       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10010   const Expr::NullPointerConstantKind RHSNullKind =
10011       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10012   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10013   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10014 
10015   auto computeResultTy = [&]() {
10016     if (Opc != BO_Cmp)
10017       return Context.getLogicalOperationType();
10018     assert(getLangOpts().CPlusPlus);
10019     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10020 
10021     QualType CompositeTy = LHS.get()->getType();
10022     assert(!CompositeTy->isReferenceType());
10023 
10024     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10025       return CheckComparisonCategoryType(Kind, Loc);
10026     };
10027 
10028     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10029     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10030     // result is of type std::strong_equality
10031     if (CompositeTy->isFunctionPointerType() ||
10032         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10033       // FIXME: consider making the function pointer case produce
10034       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10035       // and direction polls
10036       return buildResultTy(ComparisonCategoryType::StrongEquality);
10037 
10038     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10039     // pointer type, p <=> q is of type std::strong_ordering.
10040     if (CompositeTy->isPointerType()) {
10041       // P0946R0: Comparisons between a null pointer constant and an object
10042       // pointer result in std::strong_equality
10043       if (LHSIsNull != RHSIsNull)
10044         return buildResultTy(ComparisonCategoryType::StrongEquality);
10045       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10046     }
10047     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10048     // TODO: Extend support for operator<=> to ObjC types.
10049     return InvalidOperands(Loc, LHS, RHS);
10050   };
10051 
10052 
10053   if (!IsRelational && LHSIsNull != RHSIsNull) {
10054     bool IsEquality = Opc == BO_EQ;
10055     if (RHSIsNull)
10056       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10057                                    RHS.get()->getSourceRange());
10058     else
10059       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10060                                    LHS.get()->getSourceRange());
10061   }
10062 
10063   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10064       (RHSType->isIntegerType() && !RHSIsNull)) {
10065     // Skip normal pointer conversion checks in this case; we have better
10066     // diagnostics for this below.
10067   } else if (getLangOpts().CPlusPlus) {
10068     // Equality comparison of a function pointer to a void pointer is invalid,
10069     // but we allow it as an extension.
10070     // FIXME: If we really want to allow this, should it be part of composite
10071     // pointer type computation so it works in conditionals too?
10072     if (!IsRelational &&
10073         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10074          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10075       // This is a gcc extension compatibility comparison.
10076       // In a SFINAE context, we treat this as a hard error to maintain
10077       // conformance with the C++ standard.
10078       diagnoseFunctionPointerToVoidComparison(
10079           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10080 
10081       if (isSFINAEContext())
10082         return QualType();
10083 
10084       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10085       return computeResultTy();
10086     }
10087 
10088     // C++ [expr.eq]p2:
10089     //   If at least one operand is a pointer [...] bring them to their
10090     //   composite pointer type.
10091     // C++ [expr.spaceship]p6
10092     //  If at least one of the operands is of pointer type, [...] bring them
10093     //  to their composite pointer type.
10094     // C++ [expr.rel]p2:
10095     //   If both operands are pointers, [...] bring them to their composite
10096     //   pointer type.
10097     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10098             (IsRelational ? 2 : 1) &&
10099         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10100                                          RHSType->isObjCObjectPointerType()))) {
10101       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10102         return QualType();
10103       return computeResultTy();
10104     }
10105   } else if (LHSType->isPointerType() &&
10106              RHSType->isPointerType()) { // C99 6.5.8p2
10107     // All of the following pointer-related warnings are GCC extensions, except
10108     // when handling null pointer constants.
10109     QualType LCanPointeeTy =
10110       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10111     QualType RCanPointeeTy =
10112       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10113 
10114     // C99 6.5.9p2 and C99 6.5.8p2
10115     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10116                                    RCanPointeeTy.getUnqualifiedType())) {
10117       // Valid unless a relational comparison of function pointers
10118       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10119         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10120           << LHSType << RHSType << LHS.get()->getSourceRange()
10121           << RHS.get()->getSourceRange();
10122       }
10123     } else if (!IsRelational &&
10124                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10125       // Valid unless comparison between non-null pointer and function pointer
10126       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10127           && !LHSIsNull && !RHSIsNull)
10128         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10129                                                 /*isError*/false);
10130     } else {
10131       // Invalid
10132       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10133     }
10134     if (LCanPointeeTy != RCanPointeeTy) {
10135       // Treat NULL constant as a special case in OpenCL.
10136       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10137         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10138         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10139           Diag(Loc,
10140                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10141               << LHSType << RHSType << 0 /* comparison */
10142               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10143         }
10144       }
10145       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10146       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10147       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10148                                                : CK_BitCast;
10149       if (LHSIsNull && !RHSIsNull)
10150         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10151       else
10152         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10153     }
10154     return computeResultTy();
10155   }
10156 
10157   if (getLangOpts().CPlusPlus) {
10158     // C++ [expr.eq]p4:
10159     //   Two operands of type std::nullptr_t or one operand of type
10160     //   std::nullptr_t and the other a null pointer constant compare equal.
10161     if (!IsRelational && LHSIsNull && RHSIsNull) {
10162       if (LHSType->isNullPtrType()) {
10163         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10164         return computeResultTy();
10165       }
10166       if (RHSType->isNullPtrType()) {
10167         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10168         return computeResultTy();
10169       }
10170     }
10171 
10172     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10173     // These aren't covered by the composite pointer type rules.
10174     if (!IsRelational && RHSType->isNullPtrType() &&
10175         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10176       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10177       return computeResultTy();
10178     }
10179     if (!IsRelational && LHSType->isNullPtrType() &&
10180         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10181       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10182       return computeResultTy();
10183     }
10184 
10185     if (IsRelational &&
10186         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10187          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10188       // HACK: Relational comparison of nullptr_t against a pointer type is
10189       // invalid per DR583, but we allow it within std::less<> and friends,
10190       // since otherwise common uses of it break.
10191       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10192       // friends to have std::nullptr_t overload candidates.
10193       DeclContext *DC = CurContext;
10194       if (isa<FunctionDecl>(DC))
10195         DC = DC->getParent();
10196       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10197         if (CTSD->isInStdNamespace() &&
10198             llvm::StringSwitch<bool>(CTSD->getName())
10199                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10200                 .Default(false)) {
10201           if (RHSType->isNullPtrType())
10202             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10203           else
10204             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10205           return computeResultTy();
10206         }
10207       }
10208     }
10209 
10210     // C++ [expr.eq]p2:
10211     //   If at least one operand is a pointer to member, [...] bring them to
10212     //   their composite pointer type.
10213     if (!IsRelational &&
10214         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10215       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10216         return QualType();
10217       else
10218         return computeResultTy();
10219     }
10220   }
10221 
10222   // Handle block pointer types.
10223   if (!IsRelational && LHSType->isBlockPointerType() &&
10224       RHSType->isBlockPointerType()) {
10225     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10226     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10227 
10228     if (!LHSIsNull && !RHSIsNull &&
10229         !Context.typesAreCompatible(lpointee, rpointee)) {
10230       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10231         << LHSType << RHSType << LHS.get()->getSourceRange()
10232         << RHS.get()->getSourceRange();
10233     }
10234     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10235     return computeResultTy();
10236   }
10237 
10238   // Allow block pointers to be compared with null pointer constants.
10239   if (!IsRelational
10240       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10241           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10242     if (!LHSIsNull && !RHSIsNull) {
10243       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10244              ->getPointeeType()->isVoidType())
10245             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10246                 ->getPointeeType()->isVoidType())))
10247         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10248           << LHSType << RHSType << LHS.get()->getSourceRange()
10249           << RHS.get()->getSourceRange();
10250     }
10251     if (LHSIsNull && !RHSIsNull)
10252       LHS = ImpCastExprToType(LHS.get(), RHSType,
10253                               RHSType->isPointerType() ? CK_BitCast
10254                                 : CK_AnyPointerToBlockPointerCast);
10255     else
10256       RHS = ImpCastExprToType(RHS.get(), LHSType,
10257                               LHSType->isPointerType() ? CK_BitCast
10258                                 : CK_AnyPointerToBlockPointerCast);
10259     return computeResultTy();
10260   }
10261 
10262   if (LHSType->isObjCObjectPointerType() ||
10263       RHSType->isObjCObjectPointerType()) {
10264     const PointerType *LPT = LHSType->getAs<PointerType>();
10265     const PointerType *RPT = RHSType->getAs<PointerType>();
10266     if (LPT || RPT) {
10267       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10268       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10269 
10270       if (!LPtrToVoid && !RPtrToVoid &&
10271           !Context.typesAreCompatible(LHSType, RHSType)) {
10272         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10273                                           /*isError*/false);
10274       }
10275       if (LHSIsNull && !RHSIsNull) {
10276         Expr *E = LHS.get();
10277         if (getLangOpts().ObjCAutoRefCount)
10278           CheckObjCConversion(SourceRange(), RHSType, E,
10279                               CCK_ImplicitConversion);
10280         LHS = ImpCastExprToType(E, RHSType,
10281                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10282       }
10283       else {
10284         Expr *E = RHS.get();
10285         if (getLangOpts().ObjCAutoRefCount)
10286           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10287                               /*Diagnose=*/true,
10288                               /*DiagnoseCFAudited=*/false, Opc);
10289         RHS = ImpCastExprToType(E, LHSType,
10290                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10291       }
10292       return computeResultTy();
10293     }
10294     if (LHSType->isObjCObjectPointerType() &&
10295         RHSType->isObjCObjectPointerType()) {
10296       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10297         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10298                                           /*isError*/false);
10299       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10300         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10301 
10302       if (LHSIsNull && !RHSIsNull)
10303         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10304       else
10305         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10306       return computeResultTy();
10307     }
10308 
10309     if (!IsRelational && LHSType->isBlockPointerType() &&
10310         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10311       LHS = ImpCastExprToType(LHS.get(), RHSType,
10312                               CK_BlockPointerToObjCPointerCast);
10313       return computeResultTy();
10314     } else if (!IsRelational &&
10315                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10316                RHSType->isBlockPointerType()) {
10317       RHS = ImpCastExprToType(RHS.get(), LHSType,
10318                               CK_BlockPointerToObjCPointerCast);
10319       return computeResultTy();
10320     }
10321   }
10322   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10323       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10324     unsigned DiagID = 0;
10325     bool isError = false;
10326     if (LangOpts.DebuggerSupport) {
10327       // Under a debugger, allow the comparison of pointers to integers,
10328       // since users tend to want to compare addresses.
10329     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10330                (RHSIsNull && RHSType->isIntegerType())) {
10331       if (IsRelational) {
10332         isError = getLangOpts().CPlusPlus;
10333         DiagID =
10334           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10335                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10336       }
10337     } else if (getLangOpts().CPlusPlus) {
10338       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10339       isError = true;
10340     } else if (IsRelational)
10341       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10342     else
10343       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10344 
10345     if (DiagID) {
10346       Diag(Loc, DiagID)
10347         << LHSType << RHSType << LHS.get()->getSourceRange()
10348         << RHS.get()->getSourceRange();
10349       if (isError)
10350         return QualType();
10351     }
10352 
10353     if (LHSType->isIntegerType())
10354       LHS = ImpCastExprToType(LHS.get(), RHSType,
10355                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10356     else
10357       RHS = ImpCastExprToType(RHS.get(), LHSType,
10358                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10359     return computeResultTy();
10360   }
10361 
10362   // Handle block pointers.
10363   if (!IsRelational && RHSIsNull
10364       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10365     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10366     return computeResultTy();
10367   }
10368   if (!IsRelational && LHSIsNull
10369       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10370     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10371     return computeResultTy();
10372   }
10373 
10374   if (getLangOpts().OpenCLVersion >= 200) {
10375     if (LHSIsNull && RHSType->isQueueT()) {
10376       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10377       return computeResultTy();
10378     }
10379 
10380     if (LHSType->isQueueT() && RHSIsNull) {
10381       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10382       return computeResultTy();
10383     }
10384   }
10385 
10386   return InvalidOperands(Loc, LHS, RHS);
10387 }
10388 
10389 // Return a signed ext_vector_type that is of identical size and number of
10390 // elements. For floating point vectors, return an integer type of identical
10391 // size and number of elements. In the non ext_vector_type case, search from
10392 // the largest type to the smallest type to avoid cases where long long == long,
10393 // where long gets picked over long long.
10394 QualType Sema::GetSignedVectorType(QualType V) {
10395   const VectorType *VTy = V->getAs<VectorType>();
10396   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10397 
10398   if (isa<ExtVectorType>(VTy)) {
10399     if (TypeSize == Context.getTypeSize(Context.CharTy))
10400       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10401     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10402       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10403     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10404       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10405     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10406       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10407     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10408            "Unhandled vector element size in vector compare");
10409     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10410   }
10411 
10412   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10413     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10414                                  VectorType::GenericVector);
10415   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10416     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10417                                  VectorType::GenericVector);
10418   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10419     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10420                                  VectorType::GenericVector);
10421   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10422     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10423                                  VectorType::GenericVector);
10424   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10425          "Unhandled vector element size in vector compare");
10426   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10427                                VectorType::GenericVector);
10428 }
10429 
10430 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10431 /// operates on extended vector types.  Instead of producing an IntTy result,
10432 /// like a scalar comparison, a vector comparison produces a vector of integer
10433 /// types.
10434 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10435                                           SourceLocation Loc,
10436                                           BinaryOperatorKind Opc) {
10437   // Check to make sure we're operating on vectors of the same type and width,
10438   // Allowing one side to be a scalar of element type.
10439   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10440                               /*AllowBothBool*/true,
10441                               /*AllowBoolConversions*/getLangOpts().ZVector);
10442   if (vType.isNull())
10443     return vType;
10444 
10445   QualType LHSType = LHS.get()->getType();
10446 
10447   // If AltiVec, the comparison results in a numeric type, i.e.
10448   // bool for C++, int for C
10449   if (getLangOpts().AltiVec &&
10450       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10451     return Context.getLogicalOperationType();
10452 
10453   // For non-floating point types, check for self-comparisons of the form
10454   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10455   // often indicate logic errors in the program.
10456   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10457 
10458   // Check for comparisons of floating point operands using != and ==.
10459   if (BinaryOperator::isEqualityOp(Opc) &&
10460       LHSType->hasFloatingRepresentation()) {
10461     assert(RHS.get()->getType()->hasFloatingRepresentation());
10462     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10463   }
10464 
10465   // Return a signed type for the vector.
10466   return GetSignedVectorType(vType);
10467 }
10468 
10469 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10470                                           SourceLocation Loc) {
10471   // Ensure that either both operands are of the same vector type, or
10472   // one operand is of a vector type and the other is of its element type.
10473   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10474                                        /*AllowBothBool*/true,
10475                                        /*AllowBoolConversions*/false);
10476   if (vType.isNull())
10477     return InvalidOperands(Loc, LHS, RHS);
10478   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10479       vType->hasFloatingRepresentation())
10480     return InvalidOperands(Loc, LHS, RHS);
10481   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10482   //        usage of the logical operators && and || with vectors in C. This
10483   //        check could be notionally dropped.
10484   if (!getLangOpts().CPlusPlus &&
10485       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10486     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10487 
10488   return GetSignedVectorType(LHS.get()->getType());
10489 }
10490 
10491 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10492                                            SourceLocation Loc,
10493                                            BinaryOperatorKind Opc) {
10494   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10495 
10496   bool IsCompAssign =
10497       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10498 
10499   if (LHS.get()->getType()->isVectorType() ||
10500       RHS.get()->getType()->isVectorType()) {
10501     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10502         RHS.get()->getType()->hasIntegerRepresentation())
10503       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10504                         /*AllowBothBool*/true,
10505                         /*AllowBoolConversions*/getLangOpts().ZVector);
10506     return InvalidOperands(Loc, LHS, RHS);
10507   }
10508 
10509   if (Opc == BO_And)
10510     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10511 
10512   ExprResult LHSResult = LHS, RHSResult = RHS;
10513   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10514                                                  IsCompAssign);
10515   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10516     return QualType();
10517   LHS = LHSResult.get();
10518   RHS = RHSResult.get();
10519 
10520   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10521     return compType;
10522   return InvalidOperands(Loc, LHS, RHS);
10523 }
10524 
10525 // C99 6.5.[13,14]
10526 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10527                                            SourceLocation Loc,
10528                                            BinaryOperatorKind Opc) {
10529   // Check vector operands differently.
10530   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10531     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10532 
10533   // Diagnose cases where the user write a logical and/or but probably meant a
10534   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10535   // is a constant.
10536   if (LHS.get()->getType()->isIntegerType() &&
10537       !LHS.get()->getType()->isBooleanType() &&
10538       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10539       // Don't warn in macros or template instantiations.
10540       !Loc.isMacroID() && !inTemplateInstantiation()) {
10541     // If the RHS can be constant folded, and if it constant folds to something
10542     // that isn't 0 or 1 (which indicate a potential logical operation that
10543     // happened to fold to true/false) then warn.
10544     // Parens on the RHS are ignored.
10545     llvm::APSInt Result;
10546     if (RHS.get()->EvaluateAsInt(Result, Context))
10547       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10548            !RHS.get()->getExprLoc().isMacroID()) ||
10549           (Result != 0 && Result != 1)) {
10550         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10551           << RHS.get()->getSourceRange()
10552           << (Opc == BO_LAnd ? "&&" : "||");
10553         // Suggest replacing the logical operator with the bitwise version
10554         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10555             << (Opc == BO_LAnd ? "&" : "|")
10556             << FixItHint::CreateReplacement(SourceRange(
10557                                                  Loc, getLocForEndOfToken(Loc)),
10558                                             Opc == BO_LAnd ? "&" : "|");
10559         if (Opc == BO_LAnd)
10560           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10561           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10562               << FixItHint::CreateRemoval(
10563                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10564                               RHS.get()->getLocEnd()));
10565       }
10566   }
10567 
10568   if (!Context.getLangOpts().CPlusPlus) {
10569     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10570     // not operate on the built-in scalar and vector float types.
10571     if (Context.getLangOpts().OpenCL &&
10572         Context.getLangOpts().OpenCLVersion < 120) {
10573       if (LHS.get()->getType()->isFloatingType() ||
10574           RHS.get()->getType()->isFloatingType())
10575         return InvalidOperands(Loc, LHS, RHS);
10576     }
10577 
10578     LHS = UsualUnaryConversions(LHS.get());
10579     if (LHS.isInvalid())
10580       return QualType();
10581 
10582     RHS = UsualUnaryConversions(RHS.get());
10583     if (RHS.isInvalid())
10584       return QualType();
10585 
10586     if (!LHS.get()->getType()->isScalarType() ||
10587         !RHS.get()->getType()->isScalarType())
10588       return InvalidOperands(Loc, LHS, RHS);
10589 
10590     return Context.IntTy;
10591   }
10592 
10593   // The following is safe because we only use this method for
10594   // non-overloadable operands.
10595 
10596   // C++ [expr.log.and]p1
10597   // C++ [expr.log.or]p1
10598   // The operands are both contextually converted to type bool.
10599   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10600   if (LHSRes.isInvalid())
10601     return InvalidOperands(Loc, LHS, RHS);
10602   LHS = LHSRes;
10603 
10604   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10605   if (RHSRes.isInvalid())
10606     return InvalidOperands(Loc, LHS, RHS);
10607   RHS = RHSRes;
10608 
10609   // C++ [expr.log.and]p2
10610   // C++ [expr.log.or]p2
10611   // The result is a bool.
10612   return Context.BoolTy;
10613 }
10614 
10615 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10616   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10617   if (!ME) return false;
10618   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10619   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10620       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10621   if (!Base) return false;
10622   return Base->getMethodDecl() != nullptr;
10623 }
10624 
10625 /// Is the given expression (which must be 'const') a reference to a
10626 /// variable which was originally non-const, but which has become
10627 /// 'const' due to being captured within a block?
10628 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10629 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10630   assert(E->isLValue() && E->getType().isConstQualified());
10631   E = E->IgnoreParens();
10632 
10633   // Must be a reference to a declaration from an enclosing scope.
10634   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10635   if (!DRE) return NCCK_None;
10636   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10637 
10638   // The declaration must be a variable which is not declared 'const'.
10639   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10640   if (!var) return NCCK_None;
10641   if (var->getType().isConstQualified()) return NCCK_None;
10642   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10643 
10644   // Decide whether the first capture was for a block or a lambda.
10645   DeclContext *DC = S.CurContext, *Prev = nullptr;
10646   // Decide whether the first capture was for a block or a lambda.
10647   while (DC) {
10648     // For init-capture, it is possible that the variable belongs to the
10649     // template pattern of the current context.
10650     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10651       if (var->isInitCapture() &&
10652           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10653         break;
10654     if (DC == var->getDeclContext())
10655       break;
10656     Prev = DC;
10657     DC = DC->getParent();
10658   }
10659   // Unless we have an init-capture, we've gone one step too far.
10660   if (!var->isInitCapture())
10661     DC = Prev;
10662   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10663 }
10664 
10665 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10666   Ty = Ty.getNonReferenceType();
10667   if (IsDereference && Ty->isPointerType())
10668     Ty = Ty->getPointeeType();
10669   return !Ty.isConstQualified();
10670 }
10671 
10672 // Update err_typecheck_assign_const and note_typecheck_assign_const
10673 // when this enum is changed.
10674 enum {
10675   ConstFunction,
10676   ConstVariable,
10677   ConstMember,
10678   ConstMethod,
10679   NestedConstMember,
10680   ConstUnknown,  // Keep as last element
10681 };
10682 
10683 /// Emit the "read-only variable not assignable" error and print notes to give
10684 /// more information about why the variable is not assignable, such as pointing
10685 /// to the declaration of a const variable, showing that a method is const, or
10686 /// that the function is returning a const reference.
10687 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10688                                     SourceLocation Loc) {
10689   SourceRange ExprRange = E->getSourceRange();
10690 
10691   // Only emit one error on the first const found.  All other consts will emit
10692   // a note to the error.
10693   bool DiagnosticEmitted = false;
10694 
10695   // Track if the current expression is the result of a dereference, and if the
10696   // next checked expression is the result of a dereference.
10697   bool IsDereference = false;
10698   bool NextIsDereference = false;
10699 
10700   // Loop to process MemberExpr chains.
10701   while (true) {
10702     IsDereference = NextIsDereference;
10703 
10704     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10705     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10706       NextIsDereference = ME->isArrow();
10707       const ValueDecl *VD = ME->getMemberDecl();
10708       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10709         // Mutable fields can be modified even if the class is const.
10710         if (Field->isMutable()) {
10711           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10712           break;
10713         }
10714 
10715         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10716           if (!DiagnosticEmitted) {
10717             S.Diag(Loc, diag::err_typecheck_assign_const)
10718                 << ExprRange << ConstMember << false /*static*/ << Field
10719                 << Field->getType();
10720             DiagnosticEmitted = true;
10721           }
10722           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10723               << ConstMember << false /*static*/ << Field << Field->getType()
10724               << Field->getSourceRange();
10725         }
10726         E = ME->getBase();
10727         continue;
10728       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10729         if (VDecl->getType().isConstQualified()) {
10730           if (!DiagnosticEmitted) {
10731             S.Diag(Loc, diag::err_typecheck_assign_const)
10732                 << ExprRange << ConstMember << true /*static*/ << VDecl
10733                 << VDecl->getType();
10734             DiagnosticEmitted = true;
10735           }
10736           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10737               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10738               << VDecl->getSourceRange();
10739         }
10740         // Static fields do not inherit constness from parents.
10741         break;
10742       }
10743       break; // End MemberExpr
10744     } else if (const ArraySubscriptExpr *ASE =
10745                    dyn_cast<ArraySubscriptExpr>(E)) {
10746       E = ASE->getBase()->IgnoreParenImpCasts();
10747       continue;
10748     } else if (const ExtVectorElementExpr *EVE =
10749                    dyn_cast<ExtVectorElementExpr>(E)) {
10750       E = EVE->getBase()->IgnoreParenImpCasts();
10751       continue;
10752     }
10753     break;
10754   }
10755 
10756   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10757     // Function calls
10758     const FunctionDecl *FD = CE->getDirectCallee();
10759     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10760       if (!DiagnosticEmitted) {
10761         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10762                                                       << ConstFunction << FD;
10763         DiagnosticEmitted = true;
10764       }
10765       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10766              diag::note_typecheck_assign_const)
10767           << ConstFunction << FD << FD->getReturnType()
10768           << FD->getReturnTypeSourceRange();
10769     }
10770   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10771     // Point to variable declaration.
10772     if (const ValueDecl *VD = DRE->getDecl()) {
10773       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10774         if (!DiagnosticEmitted) {
10775           S.Diag(Loc, diag::err_typecheck_assign_const)
10776               << ExprRange << ConstVariable << VD << VD->getType();
10777           DiagnosticEmitted = true;
10778         }
10779         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10780             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10781       }
10782     }
10783   } else if (isa<CXXThisExpr>(E)) {
10784     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10785       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10786         if (MD->isConst()) {
10787           if (!DiagnosticEmitted) {
10788             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10789                                                           << ConstMethod << MD;
10790             DiagnosticEmitted = true;
10791           }
10792           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10793               << ConstMethod << MD << MD->getSourceRange();
10794         }
10795       }
10796     }
10797   }
10798 
10799   if (DiagnosticEmitted)
10800     return;
10801 
10802   // Can't determine a more specific message, so display the generic error.
10803   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10804 }
10805 
10806 enum OriginalExprKind {
10807   OEK_Variable,
10808   OEK_Member,
10809   OEK_LValue
10810 };
10811 
10812 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10813                                          const RecordType *Ty,
10814                                          SourceLocation Loc, SourceRange Range,
10815                                          OriginalExprKind OEK,
10816                                          bool &DiagnosticEmitted,
10817                                          bool IsNested = false) {
10818   // We walk the record hierarchy breadth-first to ensure that we print
10819   // diagnostics in field nesting order.
10820   // First, check every field for constness.
10821   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10822     if (Field->getType().isConstQualified()) {
10823       if (!DiagnosticEmitted) {
10824         S.Diag(Loc, diag::err_typecheck_assign_const)
10825             << Range << NestedConstMember << OEK << VD
10826             << IsNested << Field;
10827         DiagnosticEmitted = true;
10828       }
10829       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10830           << NestedConstMember << IsNested << Field
10831           << Field->getType() << Field->getSourceRange();
10832     }
10833   }
10834   // Then, recurse.
10835   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10836     QualType FTy = Field->getType();
10837     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10838       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10839                                    OEK, DiagnosticEmitted, true);
10840   }
10841 }
10842 
10843 /// Emit an error for the case where a record we are trying to assign to has a
10844 /// const-qualified field somewhere in its hierarchy.
10845 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10846                                          SourceLocation Loc) {
10847   QualType Ty = E->getType();
10848   assert(Ty->isRecordType() && "lvalue was not record?");
10849   SourceRange Range = E->getSourceRange();
10850   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10851   bool DiagEmitted = false;
10852 
10853   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10854     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10855             Range, OEK_Member, DiagEmitted);
10856   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10857     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10858             Range, OEK_Variable, DiagEmitted);
10859   else
10860     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10861             Range, OEK_LValue, DiagEmitted);
10862   if (!DiagEmitted)
10863     DiagnoseConstAssignment(S, E, Loc);
10864 }
10865 
10866 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10867 /// emit an error and return true.  If so, return false.
10868 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10869   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10870 
10871   S.CheckShadowingDeclModification(E, Loc);
10872 
10873   SourceLocation OrigLoc = Loc;
10874   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10875                                                               &Loc);
10876   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10877     IsLV = Expr::MLV_InvalidMessageExpression;
10878   if (IsLV == Expr::MLV_Valid)
10879     return false;
10880 
10881   unsigned DiagID = 0;
10882   bool NeedType = false;
10883   switch (IsLV) { // C99 6.5.16p2
10884   case Expr::MLV_ConstQualified:
10885     // Use a specialized diagnostic when we're assigning to an object
10886     // from an enclosing function or block.
10887     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10888       if (NCCK == NCCK_Block)
10889         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10890       else
10891         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10892       break;
10893     }
10894 
10895     // In ARC, use some specialized diagnostics for occasions where we
10896     // infer 'const'.  These are always pseudo-strong variables.
10897     if (S.getLangOpts().ObjCAutoRefCount) {
10898       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10899       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10900         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10901 
10902         // Use the normal diagnostic if it's pseudo-__strong but the
10903         // user actually wrote 'const'.
10904         if (var->isARCPseudoStrong() &&
10905             (!var->getTypeSourceInfo() ||
10906              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10907           // There are two pseudo-strong cases:
10908           //  - self
10909           ObjCMethodDecl *method = S.getCurMethodDecl();
10910           if (method && var == method->getSelfDecl())
10911             DiagID = method->isClassMethod()
10912               ? diag::err_typecheck_arc_assign_self_class_method
10913               : diag::err_typecheck_arc_assign_self;
10914 
10915           //  - fast enumeration variables
10916           else
10917             DiagID = diag::err_typecheck_arr_assign_enumeration;
10918 
10919           SourceRange Assign;
10920           if (Loc != OrigLoc)
10921             Assign = SourceRange(OrigLoc, OrigLoc);
10922           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10923           // We need to preserve the AST regardless, so migration tool
10924           // can do its job.
10925           return false;
10926         }
10927       }
10928     }
10929 
10930     // If none of the special cases above are triggered, then this is a
10931     // simple const assignment.
10932     if (DiagID == 0) {
10933       DiagnoseConstAssignment(S, E, Loc);
10934       return true;
10935     }
10936 
10937     break;
10938   case Expr::MLV_ConstAddrSpace:
10939     DiagnoseConstAssignment(S, E, Loc);
10940     return true;
10941   case Expr::MLV_ConstQualifiedField:
10942     DiagnoseRecursiveConstFields(S, E, Loc);
10943     return true;
10944   case Expr::MLV_ArrayType:
10945   case Expr::MLV_ArrayTemporary:
10946     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10947     NeedType = true;
10948     break;
10949   case Expr::MLV_NotObjectType:
10950     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10951     NeedType = true;
10952     break;
10953   case Expr::MLV_LValueCast:
10954     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10955     break;
10956   case Expr::MLV_Valid:
10957     llvm_unreachable("did not take early return for MLV_Valid");
10958   case Expr::MLV_InvalidExpression:
10959   case Expr::MLV_MemberFunction:
10960   case Expr::MLV_ClassTemporary:
10961     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10962     break;
10963   case Expr::MLV_IncompleteType:
10964   case Expr::MLV_IncompleteVoidType:
10965     return S.RequireCompleteType(Loc, E->getType(),
10966              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10967   case Expr::MLV_DuplicateVectorComponents:
10968     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10969     break;
10970   case Expr::MLV_NoSetterProperty:
10971     llvm_unreachable("readonly properties should be processed differently");
10972   case Expr::MLV_InvalidMessageExpression:
10973     DiagID = diag::err_readonly_message_assignment;
10974     break;
10975   case Expr::MLV_SubObjCPropertySetting:
10976     DiagID = diag::err_no_subobject_property_setting;
10977     break;
10978   }
10979 
10980   SourceRange Assign;
10981   if (Loc != OrigLoc)
10982     Assign = SourceRange(OrigLoc, OrigLoc);
10983   if (NeedType)
10984     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10985   else
10986     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10987   return true;
10988 }
10989 
10990 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10991                                          SourceLocation Loc,
10992                                          Sema &Sema) {
10993   if (Sema.inTemplateInstantiation())
10994     return;
10995   if (Sema.isUnevaluatedContext())
10996     return;
10997   if (Loc.isInvalid() || Loc.isMacroID())
10998     return;
10999   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11000     return;
11001 
11002   // C / C++ fields
11003   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11004   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11005   if (ML && MR) {
11006     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11007       return;
11008     const ValueDecl *LHSDecl =
11009         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11010     const ValueDecl *RHSDecl =
11011         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11012     if (LHSDecl != RHSDecl)
11013       return;
11014     if (LHSDecl->getType().isVolatileQualified())
11015       return;
11016     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11017       if (RefTy->getPointeeType().isVolatileQualified())
11018         return;
11019 
11020     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11021   }
11022 
11023   // Objective-C instance variables
11024   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11025   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11026   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11027     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11028     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11029     if (RL && RR && RL->getDecl() == RR->getDecl())
11030       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11031   }
11032 }
11033 
11034 // C99 6.5.16.1
11035 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11036                                        SourceLocation Loc,
11037                                        QualType CompoundType) {
11038   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11039 
11040   // Verify that LHS is a modifiable lvalue, and emit error if not.
11041   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11042     return QualType();
11043 
11044   QualType LHSType = LHSExpr->getType();
11045   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11046                                              CompoundType;
11047   // OpenCL v1.2 s6.1.1.1 p2:
11048   // The half data type can only be used to declare a pointer to a buffer that
11049   // contains half values
11050   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11051     LHSType->isHalfType()) {
11052     Diag(Loc, diag::err_opencl_half_load_store) << 1
11053         << LHSType.getUnqualifiedType();
11054     return QualType();
11055   }
11056 
11057   AssignConvertType ConvTy;
11058   if (CompoundType.isNull()) {
11059     Expr *RHSCheck = RHS.get();
11060 
11061     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11062 
11063     QualType LHSTy(LHSType);
11064     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11065     if (RHS.isInvalid())
11066       return QualType();
11067     // Special case of NSObject attributes on c-style pointer types.
11068     if (ConvTy == IncompatiblePointer &&
11069         ((Context.isObjCNSObjectType(LHSType) &&
11070           RHSType->isObjCObjectPointerType()) ||
11071          (Context.isObjCNSObjectType(RHSType) &&
11072           LHSType->isObjCObjectPointerType())))
11073       ConvTy = Compatible;
11074 
11075     if (ConvTy == Compatible &&
11076         LHSType->isObjCObjectType())
11077         Diag(Loc, diag::err_objc_object_assignment)
11078           << LHSType;
11079 
11080     // If the RHS is a unary plus or minus, check to see if they = and + are
11081     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11082     // instead of "x += 4".
11083     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11084       RHSCheck = ICE->getSubExpr();
11085     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11086       if ((UO->getOpcode() == UO_Plus ||
11087            UO->getOpcode() == UO_Minus) &&
11088           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11089           // Only if the two operators are exactly adjacent.
11090           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11091           // And there is a space or other character before the subexpr of the
11092           // unary +/-.  We don't want to warn on "x=-1".
11093           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
11094           UO->getSubExpr()->getLocStart().isFileID()) {
11095         Diag(Loc, diag::warn_not_compound_assign)
11096           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11097           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11098       }
11099     }
11100 
11101     if (ConvTy == Compatible) {
11102       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11103         // Warn about retain cycles where a block captures the LHS, but
11104         // not if the LHS is a simple variable into which the block is
11105         // being stored...unless that variable can be captured by reference!
11106         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11107         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11108         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11109           checkRetainCycles(LHSExpr, RHS.get());
11110       }
11111 
11112       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11113           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11114         // It is safe to assign a weak reference into a strong variable.
11115         // Although this code can still have problems:
11116         //   id x = self.weakProp;
11117         //   id y = self.weakProp;
11118         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11119         // paths through the function. This should be revisited if
11120         // -Wrepeated-use-of-weak is made flow-sensitive.
11121         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11122         // variable, which will be valid for the current autorelease scope.
11123         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11124                              RHS.get()->getLocStart()))
11125           getCurFunction()->markSafeWeakUse(RHS.get());
11126 
11127       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11128         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11129       }
11130     }
11131   } else {
11132     // Compound assignment "x += y"
11133     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11134   }
11135 
11136   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11137                                RHS.get(), AA_Assigning))
11138     return QualType();
11139 
11140   CheckForNullPointerDereference(*this, LHSExpr);
11141 
11142   // C99 6.5.16p3: The type of an assignment expression is the type of the
11143   // left operand unless the left operand has qualified type, in which case
11144   // it is the unqualified version of the type of the left operand.
11145   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11146   // is converted to the type of the assignment expression (above).
11147   // C++ 5.17p1: the type of the assignment expression is that of its left
11148   // operand.
11149   return (getLangOpts().CPlusPlus
11150           ? LHSType : LHSType.getUnqualifiedType());
11151 }
11152 
11153 // Only ignore explicit casts to void.
11154 static bool IgnoreCommaOperand(const Expr *E) {
11155   E = E->IgnoreParens();
11156 
11157   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11158     if (CE->getCastKind() == CK_ToVoid) {
11159       return true;
11160     }
11161   }
11162 
11163   return false;
11164 }
11165 
11166 // Look for instances where it is likely the comma operator is confused with
11167 // another operator.  There is a whitelist of acceptable expressions for the
11168 // left hand side of the comma operator, otherwise emit a warning.
11169 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11170   // No warnings in macros
11171   if (Loc.isMacroID())
11172     return;
11173 
11174   // Don't warn in template instantiations.
11175   if (inTemplateInstantiation())
11176     return;
11177 
11178   // Scope isn't fine-grained enough to whitelist the specific cases, so
11179   // instead, skip more than needed, then call back into here with the
11180   // CommaVisitor in SemaStmt.cpp.
11181   // The whitelisted locations are the initialization and increment portions
11182   // of a for loop.  The additional checks are on the condition of
11183   // if statements, do/while loops, and for loops.
11184   const unsigned ForIncrementFlags =
11185       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
11186   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11187   const unsigned ScopeFlags = getCurScope()->getFlags();
11188   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11189       (ScopeFlags & ForInitFlags) == ForInitFlags)
11190     return;
11191 
11192   // If there are multiple comma operators used together, get the RHS of the
11193   // of the comma operator as the LHS.
11194   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11195     if (BO->getOpcode() != BO_Comma)
11196       break;
11197     LHS = BO->getRHS();
11198   }
11199 
11200   // Only allow some expressions on LHS to not warn.
11201   if (IgnoreCommaOperand(LHS))
11202     return;
11203 
11204   Diag(Loc, diag::warn_comma_operator);
11205   Diag(LHS->getLocStart(), diag::note_cast_to_void)
11206       << LHS->getSourceRange()
11207       << FixItHint::CreateInsertion(LHS->getLocStart(),
11208                                     LangOpts.CPlusPlus ? "static_cast<void>("
11209                                                        : "(void)(")
11210       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
11211                                     ")");
11212 }
11213 
11214 // C99 6.5.17
11215 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11216                                    SourceLocation Loc) {
11217   LHS = S.CheckPlaceholderExpr(LHS.get());
11218   RHS = S.CheckPlaceholderExpr(RHS.get());
11219   if (LHS.isInvalid() || RHS.isInvalid())
11220     return QualType();
11221 
11222   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11223   // operands, but not unary promotions.
11224   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11225 
11226   // So we treat the LHS as a ignored value, and in C++ we allow the
11227   // containing site to determine what should be done with the RHS.
11228   LHS = S.IgnoredValueConversions(LHS.get());
11229   if (LHS.isInvalid())
11230     return QualType();
11231 
11232   S.DiagnoseUnusedExprResult(LHS.get());
11233 
11234   if (!S.getLangOpts().CPlusPlus) {
11235     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11236     if (RHS.isInvalid())
11237       return QualType();
11238     if (!RHS.get()->getType()->isVoidType())
11239       S.RequireCompleteType(Loc, RHS.get()->getType(),
11240                             diag::err_incomplete_type);
11241   }
11242 
11243   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11244     S.DiagnoseCommaOperator(LHS.get(), Loc);
11245 
11246   return RHS.get()->getType();
11247 }
11248 
11249 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11250 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11251 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11252                                                ExprValueKind &VK,
11253                                                ExprObjectKind &OK,
11254                                                SourceLocation OpLoc,
11255                                                bool IsInc, bool IsPrefix) {
11256   if (Op->isTypeDependent())
11257     return S.Context.DependentTy;
11258 
11259   QualType ResType = Op->getType();
11260   // Atomic types can be used for increment / decrement where the non-atomic
11261   // versions can, so ignore the _Atomic() specifier for the purpose of
11262   // checking.
11263   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11264     ResType = ResAtomicType->getValueType();
11265 
11266   assert(!ResType.isNull() && "no type for increment/decrement expression");
11267 
11268   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11269     // Decrement of bool is not allowed.
11270     if (!IsInc) {
11271       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11272       return QualType();
11273     }
11274     // Increment of bool sets it to true, but is deprecated.
11275     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11276                                               : diag::warn_increment_bool)
11277       << Op->getSourceRange();
11278   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11279     // Error on enum increments and decrements in C++ mode
11280     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11281     return QualType();
11282   } else if (ResType->isRealType()) {
11283     // OK!
11284   } else if (ResType->isPointerType()) {
11285     // C99 6.5.2.4p2, 6.5.6p2
11286     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11287       return QualType();
11288   } else if (ResType->isObjCObjectPointerType()) {
11289     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11290     // Otherwise, we just need a complete type.
11291     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11292         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11293       return QualType();
11294   } else if (ResType->isAnyComplexType()) {
11295     // C99 does not support ++/-- on complex types, we allow as an extension.
11296     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11297       << ResType << Op->getSourceRange();
11298   } else if (ResType->isPlaceholderType()) {
11299     ExprResult PR = S.CheckPlaceholderExpr(Op);
11300     if (PR.isInvalid()) return QualType();
11301     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11302                                           IsInc, IsPrefix);
11303   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11304     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11305   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11306              (ResType->getAs<VectorType>()->getVectorKind() !=
11307               VectorType::AltiVecBool)) {
11308     // The z vector extensions allow ++ and -- for non-bool vectors.
11309   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11310             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11311     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11312   } else {
11313     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11314       << ResType << int(IsInc) << Op->getSourceRange();
11315     return QualType();
11316   }
11317   // At this point, we know we have a real, complex or pointer type.
11318   // Now make sure the operand is a modifiable lvalue.
11319   if (CheckForModifiableLvalue(Op, OpLoc, S))
11320     return QualType();
11321   // In C++, a prefix increment is the same type as the operand. Otherwise
11322   // (in C or with postfix), the increment is the unqualified type of the
11323   // operand.
11324   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11325     VK = VK_LValue;
11326     OK = Op->getObjectKind();
11327     return ResType;
11328   } else {
11329     VK = VK_RValue;
11330     return ResType.getUnqualifiedType();
11331   }
11332 }
11333 
11334 
11335 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11336 /// This routine allows us to typecheck complex/recursive expressions
11337 /// where the declaration is needed for type checking. We only need to
11338 /// handle cases when the expression references a function designator
11339 /// or is an lvalue. Here are some examples:
11340 ///  - &(x) => x
11341 ///  - &*****f => f for f a function designator.
11342 ///  - &s.xx => s
11343 ///  - &s.zz[1].yy -> s, if zz is an array
11344 ///  - *(x + 1) -> x, if x is an array
11345 ///  - &"123"[2] -> 0
11346 ///  - & __real__ x -> x
11347 static ValueDecl *getPrimaryDecl(Expr *E) {
11348   switch (E->getStmtClass()) {
11349   case Stmt::DeclRefExprClass:
11350     return cast<DeclRefExpr>(E)->getDecl();
11351   case Stmt::MemberExprClass:
11352     // If this is an arrow operator, the address is an offset from
11353     // the base's value, so the object the base refers to is
11354     // irrelevant.
11355     if (cast<MemberExpr>(E)->isArrow())
11356       return nullptr;
11357     // Otherwise, the expression refers to a part of the base
11358     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11359   case Stmt::ArraySubscriptExprClass: {
11360     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11361     // promotion of register arrays earlier.
11362     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11363     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11364       if (ICE->getSubExpr()->getType()->isArrayType())
11365         return getPrimaryDecl(ICE->getSubExpr());
11366     }
11367     return nullptr;
11368   }
11369   case Stmt::UnaryOperatorClass: {
11370     UnaryOperator *UO = cast<UnaryOperator>(E);
11371 
11372     switch(UO->getOpcode()) {
11373     case UO_Real:
11374     case UO_Imag:
11375     case UO_Extension:
11376       return getPrimaryDecl(UO->getSubExpr());
11377     default:
11378       return nullptr;
11379     }
11380   }
11381   case Stmt::ParenExprClass:
11382     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11383   case Stmt::ImplicitCastExprClass:
11384     // If the result of an implicit cast is an l-value, we care about
11385     // the sub-expression; otherwise, the result here doesn't matter.
11386     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11387   default:
11388     return nullptr;
11389   }
11390 }
11391 
11392 namespace {
11393   enum {
11394     AO_Bit_Field = 0,
11395     AO_Vector_Element = 1,
11396     AO_Property_Expansion = 2,
11397     AO_Register_Variable = 3,
11398     AO_No_Error = 4
11399   };
11400 }
11401 /// Diagnose invalid operand for address of operations.
11402 ///
11403 /// \param Type The type of operand which cannot have its address taken.
11404 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11405                                          Expr *E, unsigned Type) {
11406   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11407 }
11408 
11409 /// CheckAddressOfOperand - The operand of & must be either a function
11410 /// designator or an lvalue designating an object. If it is an lvalue, the
11411 /// object cannot be declared with storage class register or be a bit field.
11412 /// Note: The usual conversions are *not* applied to the operand of the &
11413 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11414 /// In C++, the operand might be an overloaded function name, in which case
11415 /// we allow the '&' but retain the overloaded-function type.
11416 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11417   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11418     if (PTy->getKind() == BuiltinType::Overload) {
11419       Expr *E = OrigOp.get()->IgnoreParens();
11420       if (!isa<OverloadExpr>(E)) {
11421         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11422         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11423           << OrigOp.get()->getSourceRange();
11424         return QualType();
11425       }
11426 
11427       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11428       if (isa<UnresolvedMemberExpr>(Ovl))
11429         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11430           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11431             << OrigOp.get()->getSourceRange();
11432           return QualType();
11433         }
11434 
11435       return Context.OverloadTy;
11436     }
11437 
11438     if (PTy->getKind() == BuiltinType::UnknownAny)
11439       return Context.UnknownAnyTy;
11440 
11441     if (PTy->getKind() == BuiltinType::BoundMember) {
11442       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11443         << OrigOp.get()->getSourceRange();
11444       return QualType();
11445     }
11446 
11447     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11448     if (OrigOp.isInvalid()) return QualType();
11449   }
11450 
11451   if (OrigOp.get()->isTypeDependent())
11452     return Context.DependentTy;
11453 
11454   assert(!OrigOp.get()->getType()->isPlaceholderType());
11455 
11456   // Make sure to ignore parentheses in subsequent checks
11457   Expr *op = OrigOp.get()->IgnoreParens();
11458 
11459   // In OpenCL captures for blocks called as lambda functions
11460   // are located in the private address space. Blocks used in
11461   // enqueue_kernel can be located in a different address space
11462   // depending on a vendor implementation. Thus preventing
11463   // taking an address of the capture to avoid invalid AS casts.
11464   if (LangOpts.OpenCL) {
11465     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11466     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11467       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11468       return QualType();
11469     }
11470   }
11471 
11472   if (getLangOpts().C99) {
11473     // Implement C99-only parts of addressof rules.
11474     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11475       if (uOp->getOpcode() == UO_Deref)
11476         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11477         // (assuming the deref expression is valid).
11478         return uOp->getSubExpr()->getType();
11479     }
11480     // Technically, there should be a check for array subscript
11481     // expressions here, but the result of one is always an lvalue anyway.
11482   }
11483   ValueDecl *dcl = getPrimaryDecl(op);
11484 
11485   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11486     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11487                                            op->getLocStart()))
11488       return QualType();
11489 
11490   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11491   unsigned AddressOfError = AO_No_Error;
11492 
11493   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11494     bool sfinae = (bool)isSFINAEContext();
11495     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11496                                   : diag::ext_typecheck_addrof_temporary)
11497       << op->getType() << op->getSourceRange();
11498     if (sfinae)
11499       return QualType();
11500     // Materialize the temporary as an lvalue so that we can take its address.
11501     OrigOp = op =
11502         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11503   } else if (isa<ObjCSelectorExpr>(op)) {
11504     return Context.getPointerType(op->getType());
11505   } else if (lval == Expr::LV_MemberFunction) {
11506     // If it's an instance method, make a member pointer.
11507     // The expression must have exactly the form &A::foo.
11508 
11509     // If the underlying expression isn't a decl ref, give up.
11510     if (!isa<DeclRefExpr>(op)) {
11511       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11512         << OrigOp.get()->getSourceRange();
11513       return QualType();
11514     }
11515     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11516     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11517 
11518     // The id-expression was parenthesized.
11519     if (OrigOp.get() != DRE) {
11520       Diag(OpLoc, diag::err_parens_pointer_member_function)
11521         << OrigOp.get()->getSourceRange();
11522 
11523     // The method was named without a qualifier.
11524     } else if (!DRE->getQualifier()) {
11525       if (MD->getParent()->getName().empty())
11526         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11527           << op->getSourceRange();
11528       else {
11529         SmallString<32> Str;
11530         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11531         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11532           << op->getSourceRange()
11533           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11534       }
11535     }
11536 
11537     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11538     if (isa<CXXDestructorDecl>(MD))
11539       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11540 
11541     QualType MPTy = Context.getMemberPointerType(
11542         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11543     // Under the MS ABI, lock down the inheritance model now.
11544     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11545       (void)isCompleteType(OpLoc, MPTy);
11546     return MPTy;
11547   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11548     // C99 6.5.3.2p1
11549     // The operand must be either an l-value or a function designator
11550     if (!op->getType()->isFunctionType()) {
11551       // Use a special diagnostic for loads from property references.
11552       if (isa<PseudoObjectExpr>(op)) {
11553         AddressOfError = AO_Property_Expansion;
11554       } else {
11555         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11556           << op->getType() << op->getSourceRange();
11557         return QualType();
11558       }
11559     }
11560   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11561     // The operand cannot be a bit-field
11562     AddressOfError = AO_Bit_Field;
11563   } else if (op->getObjectKind() == OK_VectorComponent) {
11564     // The operand cannot be an element of a vector
11565     AddressOfError = AO_Vector_Element;
11566   } else if (dcl) { // C99 6.5.3.2p1
11567     // We have an lvalue with a decl. Make sure the decl is not declared
11568     // with the register storage-class specifier.
11569     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11570       // in C++ it is not error to take address of a register
11571       // variable (c++03 7.1.1P3)
11572       if (vd->getStorageClass() == SC_Register &&
11573           !getLangOpts().CPlusPlus) {
11574         AddressOfError = AO_Register_Variable;
11575       }
11576     } else if (isa<MSPropertyDecl>(dcl)) {
11577       AddressOfError = AO_Property_Expansion;
11578     } else if (isa<FunctionTemplateDecl>(dcl)) {
11579       return Context.OverloadTy;
11580     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11581       // Okay: we can take the address of a field.
11582       // Could be a pointer to member, though, if there is an explicit
11583       // scope qualifier for the class.
11584       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11585         DeclContext *Ctx = dcl->getDeclContext();
11586         if (Ctx && Ctx->isRecord()) {
11587           if (dcl->getType()->isReferenceType()) {
11588             Diag(OpLoc,
11589                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11590               << dcl->getDeclName() << dcl->getType();
11591             return QualType();
11592           }
11593 
11594           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11595             Ctx = Ctx->getParent();
11596 
11597           QualType MPTy = Context.getMemberPointerType(
11598               op->getType(),
11599               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11600           // Under the MS ABI, lock down the inheritance model now.
11601           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11602             (void)isCompleteType(OpLoc, MPTy);
11603           return MPTy;
11604         }
11605       }
11606     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11607                !isa<BindingDecl>(dcl))
11608       llvm_unreachable("Unknown/unexpected decl type");
11609   }
11610 
11611   if (AddressOfError != AO_No_Error) {
11612     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11613     return QualType();
11614   }
11615 
11616   if (lval == Expr::LV_IncompleteVoidType) {
11617     // Taking the address of a void variable is technically illegal, but we
11618     // allow it in cases which are otherwise valid.
11619     // Example: "extern void x; void* y = &x;".
11620     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11621   }
11622 
11623   // If the operand has type "type", the result has type "pointer to type".
11624   if (op->getType()->isObjCObjectType())
11625     return Context.getObjCObjectPointerType(op->getType());
11626 
11627   CheckAddressOfPackedMember(op);
11628 
11629   return Context.getPointerType(op->getType());
11630 }
11631 
11632 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11633   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11634   if (!DRE)
11635     return;
11636   const Decl *D = DRE->getDecl();
11637   if (!D)
11638     return;
11639   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11640   if (!Param)
11641     return;
11642   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11643     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11644       return;
11645   if (FunctionScopeInfo *FD = S.getCurFunction())
11646     if (!FD->ModifiedNonNullParams.count(Param))
11647       FD->ModifiedNonNullParams.insert(Param);
11648 }
11649 
11650 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11651 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11652                                         SourceLocation OpLoc) {
11653   if (Op->isTypeDependent())
11654     return S.Context.DependentTy;
11655 
11656   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11657   if (ConvResult.isInvalid())
11658     return QualType();
11659   Op = ConvResult.get();
11660   QualType OpTy = Op->getType();
11661   QualType Result;
11662 
11663   if (isa<CXXReinterpretCastExpr>(Op)) {
11664     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11665     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11666                                      Op->getSourceRange());
11667   }
11668 
11669   if (const PointerType *PT = OpTy->getAs<PointerType>())
11670   {
11671     Result = PT->getPointeeType();
11672   }
11673   else if (const ObjCObjectPointerType *OPT =
11674              OpTy->getAs<ObjCObjectPointerType>())
11675     Result = OPT->getPointeeType();
11676   else {
11677     ExprResult PR = S.CheckPlaceholderExpr(Op);
11678     if (PR.isInvalid()) return QualType();
11679     if (PR.get() != Op)
11680       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11681   }
11682 
11683   if (Result.isNull()) {
11684     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11685       << OpTy << Op->getSourceRange();
11686     return QualType();
11687   }
11688 
11689   // Note that per both C89 and C99, indirection is always legal, even if Result
11690   // is an incomplete type or void.  It would be possible to warn about
11691   // dereferencing a void pointer, but it's completely well-defined, and such a
11692   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11693   // for pointers to 'void' but is fine for any other pointer type:
11694   //
11695   // C++ [expr.unary.op]p1:
11696   //   [...] the expression to which [the unary * operator] is applied shall
11697   //   be a pointer to an object type, or a pointer to a function type
11698   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11699     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11700       << OpTy << Op->getSourceRange();
11701 
11702   // Dereferences are usually l-values...
11703   VK = VK_LValue;
11704 
11705   // ...except that certain expressions are never l-values in C.
11706   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11707     VK = VK_RValue;
11708 
11709   return Result;
11710 }
11711 
11712 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11713   BinaryOperatorKind Opc;
11714   switch (Kind) {
11715   default: llvm_unreachable("Unknown binop!");
11716   case tok::periodstar:           Opc = BO_PtrMemD; break;
11717   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11718   case tok::star:                 Opc = BO_Mul; break;
11719   case tok::slash:                Opc = BO_Div; break;
11720   case tok::percent:              Opc = BO_Rem; break;
11721   case tok::plus:                 Opc = BO_Add; break;
11722   case tok::minus:                Opc = BO_Sub; break;
11723   case tok::lessless:             Opc = BO_Shl; break;
11724   case tok::greatergreater:       Opc = BO_Shr; break;
11725   case tok::lessequal:            Opc = BO_LE; break;
11726   case tok::less:                 Opc = BO_LT; break;
11727   case tok::greaterequal:         Opc = BO_GE; break;
11728   case tok::greater:              Opc = BO_GT; break;
11729   case tok::exclaimequal:         Opc = BO_NE; break;
11730   case tok::equalequal:           Opc = BO_EQ; break;
11731   case tok::spaceship:            Opc = BO_Cmp; break;
11732   case tok::amp:                  Opc = BO_And; break;
11733   case tok::caret:                Opc = BO_Xor; break;
11734   case tok::pipe:                 Opc = BO_Or; break;
11735   case tok::ampamp:               Opc = BO_LAnd; break;
11736   case tok::pipepipe:             Opc = BO_LOr; break;
11737   case tok::equal:                Opc = BO_Assign; break;
11738   case tok::starequal:            Opc = BO_MulAssign; break;
11739   case tok::slashequal:           Opc = BO_DivAssign; break;
11740   case tok::percentequal:         Opc = BO_RemAssign; break;
11741   case tok::plusequal:            Opc = BO_AddAssign; break;
11742   case tok::minusequal:           Opc = BO_SubAssign; break;
11743   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11744   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11745   case tok::ampequal:             Opc = BO_AndAssign; break;
11746   case tok::caretequal:           Opc = BO_XorAssign; break;
11747   case tok::pipeequal:            Opc = BO_OrAssign; break;
11748   case tok::comma:                Opc = BO_Comma; break;
11749   }
11750   return Opc;
11751 }
11752 
11753 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11754   tok::TokenKind Kind) {
11755   UnaryOperatorKind Opc;
11756   switch (Kind) {
11757   default: llvm_unreachable("Unknown unary op!");
11758   case tok::plusplus:     Opc = UO_PreInc; break;
11759   case tok::minusminus:   Opc = UO_PreDec; break;
11760   case tok::amp:          Opc = UO_AddrOf; break;
11761   case tok::star:         Opc = UO_Deref; break;
11762   case tok::plus:         Opc = UO_Plus; break;
11763   case tok::minus:        Opc = UO_Minus; break;
11764   case tok::tilde:        Opc = UO_Not; break;
11765   case tok::exclaim:      Opc = UO_LNot; break;
11766   case tok::kw___real:    Opc = UO_Real; break;
11767   case tok::kw___imag:    Opc = UO_Imag; break;
11768   case tok::kw___extension__: Opc = UO_Extension; break;
11769   }
11770   return Opc;
11771 }
11772 
11773 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11774 /// This warning suppressed in the event of macro expansions.
11775 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11776                                    SourceLocation OpLoc, bool IsBuiltin) {
11777   if (S.inTemplateInstantiation())
11778     return;
11779   if (S.isUnevaluatedContext())
11780     return;
11781   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11782     return;
11783   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11784   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11785   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11786   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11787   if (!LHSDeclRef || !RHSDeclRef ||
11788       LHSDeclRef->getLocation().isMacroID() ||
11789       RHSDeclRef->getLocation().isMacroID())
11790     return;
11791   const ValueDecl *LHSDecl =
11792     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11793   const ValueDecl *RHSDecl =
11794     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11795   if (LHSDecl != RHSDecl)
11796     return;
11797   if (LHSDecl->getType().isVolatileQualified())
11798     return;
11799   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11800     if (RefTy->getPointeeType().isVolatileQualified())
11801       return;
11802 
11803   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11804                           : diag::warn_self_assignment_overloaded)
11805       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11806       << RHSExpr->getSourceRange();
11807 }
11808 
11809 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11810 /// is usually indicative of introspection within the Objective-C pointer.
11811 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11812                                           SourceLocation OpLoc) {
11813   if (!S.getLangOpts().ObjC1)
11814     return;
11815 
11816   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11817   const Expr *LHS = L.get();
11818   const Expr *RHS = R.get();
11819 
11820   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11821     ObjCPointerExpr = LHS;
11822     OtherExpr = RHS;
11823   }
11824   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11825     ObjCPointerExpr = RHS;
11826     OtherExpr = LHS;
11827   }
11828 
11829   // This warning is deliberately made very specific to reduce false
11830   // positives with logic that uses '&' for hashing.  This logic mainly
11831   // looks for code trying to introspect into tagged pointers, which
11832   // code should generally never do.
11833   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11834     unsigned Diag = diag::warn_objc_pointer_masking;
11835     // Determine if we are introspecting the result of performSelectorXXX.
11836     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11837     // Special case messages to -performSelector and friends, which
11838     // can return non-pointer values boxed in a pointer value.
11839     // Some clients may wish to silence warnings in this subcase.
11840     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11841       Selector S = ME->getSelector();
11842       StringRef SelArg0 = S.getNameForSlot(0);
11843       if (SelArg0.startswith("performSelector"))
11844         Diag = diag::warn_objc_pointer_masking_performSelector;
11845     }
11846 
11847     S.Diag(OpLoc, Diag)
11848       << ObjCPointerExpr->getSourceRange();
11849   }
11850 }
11851 
11852 static NamedDecl *getDeclFromExpr(Expr *E) {
11853   if (!E)
11854     return nullptr;
11855   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11856     return DRE->getDecl();
11857   if (auto *ME = dyn_cast<MemberExpr>(E))
11858     return ME->getMemberDecl();
11859   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11860     return IRE->getDecl();
11861   return nullptr;
11862 }
11863 
11864 // This helper function promotes a binary operator's operands (which are of a
11865 // half vector type) to a vector of floats and then truncates the result to
11866 // a vector of either half or short.
11867 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11868                                       BinaryOperatorKind Opc, QualType ResultTy,
11869                                       ExprValueKind VK, ExprObjectKind OK,
11870                                       bool IsCompAssign, SourceLocation OpLoc,
11871                                       FPOptions FPFeatures) {
11872   auto &Context = S.getASTContext();
11873   assert((isVector(ResultTy, Context.HalfTy) ||
11874           isVector(ResultTy, Context.ShortTy)) &&
11875          "Result must be a vector of half or short");
11876   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11877          isVector(RHS.get()->getType(), Context.HalfTy) &&
11878          "both operands expected to be a half vector");
11879 
11880   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11881   QualType BinOpResTy = RHS.get()->getType();
11882 
11883   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11884   // change BinOpResTy to a vector of ints.
11885   if (isVector(ResultTy, Context.ShortTy))
11886     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11887 
11888   if (IsCompAssign)
11889     return new (Context) CompoundAssignOperator(
11890         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11891         OpLoc, FPFeatures);
11892 
11893   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11894   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11895                                           VK, OK, OpLoc, FPFeatures);
11896   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11897 }
11898 
11899 static std::pair<ExprResult, ExprResult>
11900 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11901                            Expr *RHSExpr) {
11902   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11903   if (!S.getLangOpts().CPlusPlus) {
11904     // C cannot handle TypoExpr nodes on either side of a binop because it
11905     // doesn't handle dependent types properly, so make sure any TypoExprs have
11906     // been dealt with before checking the operands.
11907     LHS = S.CorrectDelayedTyposInExpr(LHS);
11908     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11909       if (Opc != BO_Assign)
11910         return ExprResult(E);
11911       // Avoid correcting the RHS to the same Expr as the LHS.
11912       Decl *D = getDeclFromExpr(E);
11913       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11914     });
11915   }
11916   return std::make_pair(LHS, RHS);
11917 }
11918 
11919 /// Returns true if conversion between vectors of halfs and vectors of floats
11920 /// is needed.
11921 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11922                                      QualType SrcType) {
11923   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11924          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11925          isVector(SrcType, Ctx.HalfTy);
11926 }
11927 
11928 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11929 /// operator @p Opc at location @c TokLoc. This routine only supports
11930 /// built-in operations; ActOnBinOp handles overloaded operators.
11931 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11932                                     BinaryOperatorKind Opc,
11933                                     Expr *LHSExpr, Expr *RHSExpr) {
11934   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11935     // The syntax only allows initializer lists on the RHS of assignment,
11936     // so we don't need to worry about accepting invalid code for
11937     // non-assignment operators.
11938     // C++11 5.17p9:
11939     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11940     //   of x = {} is x = T().
11941     InitializationKind Kind = InitializationKind::CreateDirectList(
11942         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
11943     InitializedEntity Entity =
11944         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11945     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11946     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11947     if (Init.isInvalid())
11948       return Init;
11949     RHSExpr = Init.get();
11950   }
11951 
11952   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11953   QualType ResultTy;     // Result type of the binary operator.
11954   // The following two variables are used for compound assignment operators
11955   QualType CompLHSTy;    // Type of LHS after promotions for computation
11956   QualType CompResultTy; // Type of computation result
11957   ExprValueKind VK = VK_RValue;
11958   ExprObjectKind OK = OK_Ordinary;
11959   bool ConvertHalfVec = false;
11960 
11961   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11962   if (!LHS.isUsable() || !RHS.isUsable())
11963     return ExprError();
11964 
11965   if (getLangOpts().OpenCL) {
11966     QualType LHSTy = LHSExpr->getType();
11967     QualType RHSTy = RHSExpr->getType();
11968     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11969     // the ATOMIC_VAR_INIT macro.
11970     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11971       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11972       if (BO_Assign == Opc)
11973         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11974       else
11975         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11976       return ExprError();
11977     }
11978 
11979     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11980     // only with a builtin functions and therefore should be disallowed here.
11981     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11982         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11983         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11984         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11985       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11986       return ExprError();
11987     }
11988   }
11989 
11990   switch (Opc) {
11991   case BO_Assign:
11992     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11993     if (getLangOpts().CPlusPlus &&
11994         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11995       VK = LHS.get()->getValueKind();
11996       OK = LHS.get()->getObjectKind();
11997     }
11998     if (!ResultTy.isNull()) {
11999       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12000       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12001     }
12002     RecordModifiableNonNullParam(*this, LHS.get());
12003     break;
12004   case BO_PtrMemD:
12005   case BO_PtrMemI:
12006     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12007                                             Opc == BO_PtrMemI);
12008     break;
12009   case BO_Mul:
12010   case BO_Div:
12011     ConvertHalfVec = true;
12012     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12013                                            Opc == BO_Div);
12014     break;
12015   case BO_Rem:
12016     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12017     break;
12018   case BO_Add:
12019     ConvertHalfVec = true;
12020     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12021     break;
12022   case BO_Sub:
12023     ConvertHalfVec = true;
12024     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12025     break;
12026   case BO_Shl:
12027   case BO_Shr:
12028     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12029     break;
12030   case BO_LE:
12031   case BO_LT:
12032   case BO_GE:
12033   case BO_GT:
12034     ConvertHalfVec = true;
12035     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12036     break;
12037   case BO_EQ:
12038   case BO_NE:
12039     ConvertHalfVec = true;
12040     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12041     break;
12042   case BO_Cmp:
12043     ConvertHalfVec = true;
12044     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12045     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12046     break;
12047   case BO_And:
12048     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12049     LLVM_FALLTHROUGH;
12050   case BO_Xor:
12051   case BO_Or:
12052     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12053     break;
12054   case BO_LAnd:
12055   case BO_LOr:
12056     ConvertHalfVec = true;
12057     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12058     break;
12059   case BO_MulAssign:
12060   case BO_DivAssign:
12061     ConvertHalfVec = true;
12062     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12063                                                Opc == BO_DivAssign);
12064     CompLHSTy = CompResultTy;
12065     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12066       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12067     break;
12068   case BO_RemAssign:
12069     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12070     CompLHSTy = CompResultTy;
12071     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12072       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12073     break;
12074   case BO_AddAssign:
12075     ConvertHalfVec = true;
12076     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12077     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12078       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12079     break;
12080   case BO_SubAssign:
12081     ConvertHalfVec = true;
12082     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12083     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12084       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12085     break;
12086   case BO_ShlAssign:
12087   case BO_ShrAssign:
12088     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12089     CompLHSTy = CompResultTy;
12090     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12091       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12092     break;
12093   case BO_AndAssign:
12094   case BO_OrAssign: // fallthrough
12095     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12096     LLVM_FALLTHROUGH;
12097   case BO_XorAssign:
12098     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12099     CompLHSTy = CompResultTy;
12100     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12101       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12102     break;
12103   case BO_Comma:
12104     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12105     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12106       VK = RHS.get()->getValueKind();
12107       OK = RHS.get()->getObjectKind();
12108     }
12109     break;
12110   }
12111   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12112     return ExprError();
12113 
12114   // Some of the binary operations require promoting operands of half vector to
12115   // float vectors and truncating the result back to half vector. For now, we do
12116   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12117   // arm64).
12118   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12119          isVector(LHS.get()->getType(), Context.HalfTy) &&
12120          "both sides are half vectors or neither sides are");
12121   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12122                                             LHS.get()->getType());
12123 
12124   // Check for array bounds violations for both sides of the BinaryOperator
12125   CheckArrayAccess(LHS.get());
12126   CheckArrayAccess(RHS.get());
12127 
12128   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12129     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12130                                                  &Context.Idents.get("object_setClass"),
12131                                                  SourceLocation(), LookupOrdinaryName);
12132     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12133       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
12134       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
12135       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
12136       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
12137       FixItHint::CreateInsertion(RHSLocEnd, ")");
12138     }
12139     else
12140       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12141   }
12142   else if (const ObjCIvarRefExpr *OIRE =
12143            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12144     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12145 
12146   // Opc is not a compound assignment if CompResultTy is null.
12147   if (CompResultTy.isNull()) {
12148     if (ConvertHalfVec)
12149       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12150                                  OpLoc, FPFeatures);
12151     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12152                                         OK, OpLoc, FPFeatures);
12153   }
12154 
12155   // Handle compound assignments.
12156   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12157       OK_ObjCProperty) {
12158     VK = VK_LValue;
12159     OK = LHS.get()->getObjectKind();
12160   }
12161 
12162   if (ConvertHalfVec)
12163     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12164                                OpLoc, FPFeatures);
12165 
12166   return new (Context) CompoundAssignOperator(
12167       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12168       OpLoc, FPFeatures);
12169 }
12170 
12171 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12172 /// operators are mixed in a way that suggests that the programmer forgot that
12173 /// comparison operators have higher precedence. The most typical example of
12174 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12175 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12176                                       SourceLocation OpLoc, Expr *LHSExpr,
12177                                       Expr *RHSExpr) {
12178   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12179   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12180 
12181   // Check that one of the sides is a comparison operator and the other isn't.
12182   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12183   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12184   if (isLeftComp == isRightComp)
12185     return;
12186 
12187   // Bitwise operations are sometimes used as eager logical ops.
12188   // Don't diagnose this.
12189   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12190   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12191   if (isLeftBitwise || isRightBitwise)
12192     return;
12193 
12194   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
12195                                                    OpLoc)
12196                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
12197   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12198   SourceRange ParensRange = isLeftComp ?
12199       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
12200     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
12201 
12202   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12203     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12204   SuggestParentheses(Self, OpLoc,
12205     Self.PDiag(diag::note_precedence_silence) << OpStr,
12206     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12207   SuggestParentheses(Self, OpLoc,
12208     Self.PDiag(diag::note_precedence_bitwise_first)
12209       << BinaryOperator::getOpcodeStr(Opc),
12210     ParensRange);
12211 }
12212 
12213 /// It accepts a '&&' expr that is inside a '||' one.
12214 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12215 /// in parentheses.
12216 static void
12217 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12218                                        BinaryOperator *Bop) {
12219   assert(Bop->getOpcode() == BO_LAnd);
12220   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12221       << Bop->getSourceRange() << OpLoc;
12222   SuggestParentheses(Self, Bop->getOperatorLoc(),
12223     Self.PDiag(diag::note_precedence_silence)
12224       << Bop->getOpcodeStr(),
12225     Bop->getSourceRange());
12226 }
12227 
12228 /// Returns true if the given expression can be evaluated as a constant
12229 /// 'true'.
12230 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12231   bool Res;
12232   return !E->isValueDependent() &&
12233          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12234 }
12235 
12236 /// Returns true if the given expression can be evaluated as a constant
12237 /// 'false'.
12238 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12239   bool Res;
12240   return !E->isValueDependent() &&
12241          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12242 }
12243 
12244 /// Look for '&&' in the left hand of a '||' expr.
12245 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12246                                              Expr *LHSExpr, Expr *RHSExpr) {
12247   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12248     if (Bop->getOpcode() == BO_LAnd) {
12249       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12250       if (EvaluatesAsFalse(S, RHSExpr))
12251         return;
12252       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12253       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12254         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12255     } else if (Bop->getOpcode() == BO_LOr) {
12256       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12257         // If it's "a || b && 1 || c" we didn't warn earlier for
12258         // "a || b && 1", but warn now.
12259         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12260           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12261       }
12262     }
12263   }
12264 }
12265 
12266 /// Look for '&&' in the right hand of a '||' expr.
12267 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12268                                              Expr *LHSExpr, Expr *RHSExpr) {
12269   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12270     if (Bop->getOpcode() == BO_LAnd) {
12271       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12272       if (EvaluatesAsFalse(S, LHSExpr))
12273         return;
12274       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12275       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12276         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12277     }
12278   }
12279 }
12280 
12281 /// Look for bitwise op in the left or right hand of a bitwise op with
12282 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12283 /// the '&' expression in parentheses.
12284 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12285                                          SourceLocation OpLoc, Expr *SubExpr) {
12286   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12287     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12288       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12289         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12290         << Bop->getSourceRange() << OpLoc;
12291       SuggestParentheses(S, Bop->getOperatorLoc(),
12292         S.PDiag(diag::note_precedence_silence)
12293           << Bop->getOpcodeStr(),
12294         Bop->getSourceRange());
12295     }
12296   }
12297 }
12298 
12299 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12300                                     Expr *SubExpr, StringRef Shift) {
12301   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12302     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12303       StringRef Op = Bop->getOpcodeStr();
12304       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12305           << Bop->getSourceRange() << OpLoc << Shift << Op;
12306       SuggestParentheses(S, Bop->getOperatorLoc(),
12307           S.PDiag(diag::note_precedence_silence) << Op,
12308           Bop->getSourceRange());
12309     }
12310   }
12311 }
12312 
12313 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12314                                  Expr *LHSExpr, Expr *RHSExpr) {
12315   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12316   if (!OCE)
12317     return;
12318 
12319   FunctionDecl *FD = OCE->getDirectCallee();
12320   if (!FD || !FD->isOverloadedOperator())
12321     return;
12322 
12323   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12324   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12325     return;
12326 
12327   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12328       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12329       << (Kind == OO_LessLess);
12330   SuggestParentheses(S, OCE->getOperatorLoc(),
12331                      S.PDiag(diag::note_precedence_silence)
12332                          << (Kind == OO_LessLess ? "<<" : ">>"),
12333                      OCE->getSourceRange());
12334   SuggestParentheses(S, OpLoc,
12335                      S.PDiag(diag::note_evaluate_comparison_first),
12336                      SourceRange(OCE->getArg(1)->getLocStart(),
12337                                  RHSExpr->getLocEnd()));
12338 }
12339 
12340 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12341 /// precedence.
12342 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12343                                     SourceLocation OpLoc, Expr *LHSExpr,
12344                                     Expr *RHSExpr){
12345   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12346   if (BinaryOperator::isBitwiseOp(Opc))
12347     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12348 
12349   // Diagnose "arg1 & arg2 | arg3"
12350   if ((Opc == BO_Or || Opc == BO_Xor) &&
12351       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12352     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12353     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12354   }
12355 
12356   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12357   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12358   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12359     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12360     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12361   }
12362 
12363   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12364       || Opc == BO_Shr) {
12365     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12366     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12367     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12368   }
12369 
12370   // Warn on overloaded shift operators and comparisons, such as:
12371   // cout << 5 == 4;
12372   if (BinaryOperator::isComparisonOp(Opc))
12373     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12374 }
12375 
12376 // Binary Operators.  'Tok' is the token for the operator.
12377 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12378                             tok::TokenKind Kind,
12379                             Expr *LHSExpr, Expr *RHSExpr) {
12380   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12381   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12382   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12383 
12384   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12385   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12386 
12387   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12388 }
12389 
12390 /// Build an overloaded binary operator expression in the given scope.
12391 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12392                                        BinaryOperatorKind Opc,
12393                                        Expr *LHS, Expr *RHS) {
12394   switch (Opc) {
12395   case BO_Assign:
12396   case BO_DivAssign:
12397   case BO_RemAssign:
12398   case BO_SubAssign:
12399   case BO_AndAssign:
12400   case BO_OrAssign:
12401   case BO_XorAssign:
12402     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12403     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12404     break;
12405   default:
12406     break;
12407   }
12408 
12409   // Find all of the overloaded operators visible from this
12410   // point. We perform both an operator-name lookup from the local
12411   // scope and an argument-dependent lookup based on the types of
12412   // the arguments.
12413   UnresolvedSet<16> Functions;
12414   OverloadedOperatorKind OverOp
12415     = BinaryOperator::getOverloadedOperator(Opc);
12416   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12417     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12418                                    RHS->getType(), Functions);
12419 
12420   // Build the (potentially-overloaded, potentially-dependent)
12421   // binary operation.
12422   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12423 }
12424 
12425 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12426                             BinaryOperatorKind Opc,
12427                             Expr *LHSExpr, Expr *RHSExpr) {
12428   ExprResult LHS, RHS;
12429   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12430   if (!LHS.isUsable() || !RHS.isUsable())
12431     return ExprError();
12432   LHSExpr = LHS.get();
12433   RHSExpr = RHS.get();
12434 
12435   // We want to end up calling one of checkPseudoObjectAssignment
12436   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12437   // both expressions are overloadable or either is type-dependent),
12438   // or CreateBuiltinBinOp (in any other case).  We also want to get
12439   // any placeholder types out of the way.
12440 
12441   // Handle pseudo-objects in the LHS.
12442   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12443     // Assignments with a pseudo-object l-value need special analysis.
12444     if (pty->getKind() == BuiltinType::PseudoObject &&
12445         BinaryOperator::isAssignmentOp(Opc))
12446       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12447 
12448     // Don't resolve overloads if the other type is overloadable.
12449     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12450       // We can't actually test that if we still have a placeholder,
12451       // though.  Fortunately, none of the exceptions we see in that
12452       // code below are valid when the LHS is an overload set.  Note
12453       // that an overload set can be dependently-typed, but it never
12454       // instantiates to having an overloadable type.
12455       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12456       if (resolvedRHS.isInvalid()) return ExprError();
12457       RHSExpr = resolvedRHS.get();
12458 
12459       if (RHSExpr->isTypeDependent() ||
12460           RHSExpr->getType()->isOverloadableType())
12461         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12462     }
12463 
12464     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12465     // template, diagnose the missing 'template' keyword instead of diagnosing
12466     // an invalid use of a bound member function.
12467     //
12468     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12469     // to C++1z [over.over]/1.4, but we already checked for that case above.
12470     if (Opc == BO_LT && inTemplateInstantiation() &&
12471         (pty->getKind() == BuiltinType::BoundMember ||
12472          pty->getKind() == BuiltinType::Overload)) {
12473       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12474       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12475           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12476             return isa<FunctionTemplateDecl>(ND);
12477           })) {
12478         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12479                                 : OE->getNameLoc(),
12480              diag::err_template_kw_missing)
12481           << OE->getName().getAsString() << "";
12482         return ExprError();
12483       }
12484     }
12485 
12486     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12487     if (LHS.isInvalid()) return ExprError();
12488     LHSExpr = LHS.get();
12489   }
12490 
12491   // Handle pseudo-objects in the RHS.
12492   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12493     // An overload in the RHS can potentially be resolved by the type
12494     // being assigned to.
12495     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12496       if (getLangOpts().CPlusPlus &&
12497           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12498            LHSExpr->getType()->isOverloadableType()))
12499         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12500 
12501       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12502     }
12503 
12504     // Don't resolve overloads if the other type is overloadable.
12505     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12506         LHSExpr->getType()->isOverloadableType())
12507       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12508 
12509     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12510     if (!resolvedRHS.isUsable()) return ExprError();
12511     RHSExpr = resolvedRHS.get();
12512   }
12513 
12514   if (getLangOpts().CPlusPlus) {
12515     // If either expression is type-dependent, always build an
12516     // overloaded op.
12517     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12518       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12519 
12520     // Otherwise, build an overloaded op if either expression has an
12521     // overloadable type.
12522     if (LHSExpr->getType()->isOverloadableType() ||
12523         RHSExpr->getType()->isOverloadableType())
12524       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12525   }
12526 
12527   // Build a built-in binary operation.
12528   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12529 }
12530 
12531 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12532   if (T.isNull() || T->isDependentType())
12533     return false;
12534 
12535   if (!T->isPromotableIntegerType())
12536     return true;
12537 
12538   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12539 }
12540 
12541 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12542                                       UnaryOperatorKind Opc,
12543                                       Expr *InputExpr) {
12544   ExprResult Input = InputExpr;
12545   ExprValueKind VK = VK_RValue;
12546   ExprObjectKind OK = OK_Ordinary;
12547   QualType resultType;
12548   bool CanOverflow = false;
12549 
12550   bool ConvertHalfVec = false;
12551   if (getLangOpts().OpenCL) {
12552     QualType Ty = InputExpr->getType();
12553     // The only legal unary operation for atomics is '&'.
12554     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12555     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12556     // only with a builtin functions and therefore should be disallowed here.
12557         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12558         || Ty->isBlockPointerType())) {
12559       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12560                        << InputExpr->getType()
12561                        << Input.get()->getSourceRange());
12562     }
12563   }
12564   switch (Opc) {
12565   case UO_PreInc:
12566   case UO_PreDec:
12567   case UO_PostInc:
12568   case UO_PostDec:
12569     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12570                                                 OpLoc,
12571                                                 Opc == UO_PreInc ||
12572                                                 Opc == UO_PostInc,
12573                                                 Opc == UO_PreInc ||
12574                                                 Opc == UO_PreDec);
12575     CanOverflow = isOverflowingIntegerType(Context, resultType);
12576     break;
12577   case UO_AddrOf:
12578     resultType = CheckAddressOfOperand(Input, OpLoc);
12579     RecordModifiableNonNullParam(*this, InputExpr);
12580     break;
12581   case UO_Deref: {
12582     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12583     if (Input.isInvalid()) return ExprError();
12584     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12585     break;
12586   }
12587   case UO_Plus:
12588   case UO_Minus:
12589     CanOverflow = Opc == UO_Minus &&
12590                   isOverflowingIntegerType(Context, Input.get()->getType());
12591     Input = UsualUnaryConversions(Input.get());
12592     if (Input.isInvalid()) return ExprError();
12593     // Unary plus and minus require promoting an operand of half vector to a
12594     // float vector and truncating the result back to a half vector. For now, we
12595     // do this only when HalfArgsAndReturns is set (that is, when the target is
12596     // arm or arm64).
12597     ConvertHalfVec =
12598         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12599 
12600     // If the operand is a half vector, promote it to a float vector.
12601     if (ConvertHalfVec)
12602       Input = convertVector(Input.get(), Context.FloatTy, *this);
12603     resultType = Input.get()->getType();
12604     if (resultType->isDependentType())
12605       break;
12606     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12607       break;
12608     else if (resultType->isVectorType() &&
12609              // The z vector extensions don't allow + or - with bool vectors.
12610              (!Context.getLangOpts().ZVector ||
12611               resultType->getAs<VectorType>()->getVectorKind() !=
12612               VectorType::AltiVecBool))
12613       break;
12614     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12615              Opc == UO_Plus &&
12616              resultType->isPointerType())
12617       break;
12618 
12619     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12620       << resultType << Input.get()->getSourceRange());
12621 
12622   case UO_Not: // bitwise complement
12623     Input = UsualUnaryConversions(Input.get());
12624     if (Input.isInvalid())
12625       return ExprError();
12626     resultType = Input.get()->getType();
12627 
12628     if (resultType->isDependentType())
12629       break;
12630     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12631     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12632       // C99 does not support '~' for complex conjugation.
12633       Diag(OpLoc, diag::ext_integer_complement_complex)
12634           << resultType << Input.get()->getSourceRange();
12635     else if (resultType->hasIntegerRepresentation())
12636       break;
12637     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12638       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12639       // on vector float types.
12640       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12641       if (!T->isIntegerType())
12642         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12643                           << resultType << Input.get()->getSourceRange());
12644     } else {
12645       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12646                        << resultType << Input.get()->getSourceRange());
12647     }
12648     break;
12649 
12650   case UO_LNot: // logical negation
12651     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12652     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12653     if (Input.isInvalid()) return ExprError();
12654     resultType = Input.get()->getType();
12655 
12656     // Though we still have to promote half FP to float...
12657     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12658       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12659       resultType = Context.FloatTy;
12660     }
12661 
12662     if (resultType->isDependentType())
12663       break;
12664     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12665       // C99 6.5.3.3p1: ok, fallthrough;
12666       if (Context.getLangOpts().CPlusPlus) {
12667         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12668         // operand contextually converted to bool.
12669         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12670                                   ScalarTypeToBooleanCastKind(resultType));
12671       } else if (Context.getLangOpts().OpenCL &&
12672                  Context.getLangOpts().OpenCLVersion < 120) {
12673         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12674         // operate on scalar float types.
12675         if (!resultType->isIntegerType() && !resultType->isPointerType())
12676           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12677                            << resultType << Input.get()->getSourceRange());
12678       }
12679     } else if (resultType->isExtVectorType()) {
12680       if (Context.getLangOpts().OpenCL &&
12681           Context.getLangOpts().OpenCLVersion < 120) {
12682         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12683         // operate on vector float types.
12684         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12685         if (!T->isIntegerType())
12686           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12687                            << resultType << Input.get()->getSourceRange());
12688       }
12689       // Vector logical not returns the signed variant of the operand type.
12690       resultType = GetSignedVectorType(resultType);
12691       break;
12692     } else {
12693       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12694       //        type in C++. We should allow that here too.
12695       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12696         << resultType << Input.get()->getSourceRange());
12697     }
12698 
12699     // LNot always has type int. C99 6.5.3.3p5.
12700     // In C++, it's bool. C++ 5.3.1p8
12701     resultType = Context.getLogicalOperationType();
12702     break;
12703   case UO_Real:
12704   case UO_Imag:
12705     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12706     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12707     // complex l-values to ordinary l-values and all other values to r-values.
12708     if (Input.isInvalid()) return ExprError();
12709     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12710       if (Input.get()->getValueKind() != VK_RValue &&
12711           Input.get()->getObjectKind() == OK_Ordinary)
12712         VK = Input.get()->getValueKind();
12713     } else if (!getLangOpts().CPlusPlus) {
12714       // In C, a volatile scalar is read by __imag. In C++, it is not.
12715       Input = DefaultLvalueConversion(Input.get());
12716     }
12717     break;
12718   case UO_Extension:
12719     resultType = Input.get()->getType();
12720     VK = Input.get()->getValueKind();
12721     OK = Input.get()->getObjectKind();
12722     break;
12723   case UO_Coawait:
12724     // It's unnecessary to represent the pass-through operator co_await in the
12725     // AST; just return the input expression instead.
12726     assert(!Input.get()->getType()->isDependentType() &&
12727                    "the co_await expression must be non-dependant before "
12728                    "building operator co_await");
12729     return Input;
12730   }
12731   if (resultType.isNull() || Input.isInvalid())
12732     return ExprError();
12733 
12734   // Check for array bounds violations in the operand of the UnaryOperator,
12735   // except for the '*' and '&' operators that have to be handled specially
12736   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12737   // that are explicitly defined as valid by the standard).
12738   if (Opc != UO_AddrOf && Opc != UO_Deref)
12739     CheckArrayAccess(Input.get());
12740 
12741   auto *UO = new (Context)
12742       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12743   // Convert the result back to a half vector.
12744   if (ConvertHalfVec)
12745     return convertVector(UO, Context.HalfTy, *this);
12746   return UO;
12747 }
12748 
12749 /// Determine whether the given expression is a qualified member
12750 /// access expression, of a form that could be turned into a pointer to member
12751 /// with the address-of operator.
12752 static bool isQualifiedMemberAccess(Expr *E) {
12753   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12754     if (!DRE->getQualifier())
12755       return false;
12756 
12757     ValueDecl *VD = DRE->getDecl();
12758     if (!VD->isCXXClassMember())
12759       return false;
12760 
12761     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12762       return true;
12763     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12764       return Method->isInstance();
12765 
12766     return false;
12767   }
12768 
12769   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12770     if (!ULE->getQualifier())
12771       return false;
12772 
12773     for (NamedDecl *D : ULE->decls()) {
12774       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12775         if (Method->isInstance())
12776           return true;
12777       } else {
12778         // Overload set does not contain methods.
12779         break;
12780       }
12781     }
12782 
12783     return false;
12784   }
12785 
12786   return false;
12787 }
12788 
12789 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12790                               UnaryOperatorKind Opc, Expr *Input) {
12791   // First things first: handle placeholders so that the
12792   // overloaded-operator check considers the right type.
12793   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12794     // Increment and decrement of pseudo-object references.
12795     if (pty->getKind() == BuiltinType::PseudoObject &&
12796         UnaryOperator::isIncrementDecrementOp(Opc))
12797       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12798 
12799     // extension is always a builtin operator.
12800     if (Opc == UO_Extension)
12801       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12802 
12803     // & gets special logic for several kinds of placeholder.
12804     // The builtin code knows what to do.
12805     if (Opc == UO_AddrOf &&
12806         (pty->getKind() == BuiltinType::Overload ||
12807          pty->getKind() == BuiltinType::UnknownAny ||
12808          pty->getKind() == BuiltinType::BoundMember))
12809       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12810 
12811     // Anything else needs to be handled now.
12812     ExprResult Result = CheckPlaceholderExpr(Input);
12813     if (Result.isInvalid()) return ExprError();
12814     Input = Result.get();
12815   }
12816 
12817   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12818       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12819       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12820     // Find all of the overloaded operators visible from this
12821     // point. We perform both an operator-name lookup from the local
12822     // scope and an argument-dependent lookup based on the types of
12823     // the arguments.
12824     UnresolvedSet<16> Functions;
12825     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12826     if (S && OverOp != OO_None)
12827       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12828                                    Functions);
12829 
12830     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12831   }
12832 
12833   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12834 }
12835 
12836 // Unary Operators.  'Tok' is the token for the operator.
12837 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12838                               tok::TokenKind Op, Expr *Input) {
12839   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12840 }
12841 
12842 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12843 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12844                                 LabelDecl *TheDecl) {
12845   TheDecl->markUsed(Context);
12846   // Create the AST node.  The address of a label always has type 'void*'.
12847   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12848                                      Context.getPointerType(Context.VoidTy));
12849 }
12850 
12851 /// Given the last statement in a statement-expression, check whether
12852 /// the result is a producing expression (like a call to an
12853 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12854 /// release out of the full-expression.  Otherwise, return null.
12855 /// Cannot fail.
12856 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12857   // Should always be wrapped with one of these.
12858   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12859   if (!cleanups) return nullptr;
12860 
12861   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12862   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12863     return nullptr;
12864 
12865   // Splice out the cast.  This shouldn't modify any interesting
12866   // features of the statement.
12867   Expr *producer = cast->getSubExpr();
12868   assert(producer->getType() == cast->getType());
12869   assert(producer->getValueKind() == cast->getValueKind());
12870   cleanups->setSubExpr(producer);
12871   return cleanups;
12872 }
12873 
12874 void Sema::ActOnStartStmtExpr() {
12875   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12876 }
12877 
12878 void Sema::ActOnStmtExprError() {
12879   // Note that function is also called by TreeTransform when leaving a
12880   // StmtExpr scope without rebuilding anything.
12881 
12882   DiscardCleanupsInEvaluationContext();
12883   PopExpressionEvaluationContext();
12884 }
12885 
12886 ExprResult
12887 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12888                     SourceLocation RPLoc) { // "({..})"
12889   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12890   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12891 
12892   if (hasAnyUnrecoverableErrorsInThisFunction())
12893     DiscardCleanupsInEvaluationContext();
12894   assert(!Cleanup.exprNeedsCleanups() &&
12895          "cleanups within StmtExpr not correctly bound!");
12896   PopExpressionEvaluationContext();
12897 
12898   // FIXME: there are a variety of strange constraints to enforce here, for
12899   // example, it is not possible to goto into a stmt expression apparently.
12900   // More semantic analysis is needed.
12901 
12902   // If there are sub-stmts in the compound stmt, take the type of the last one
12903   // as the type of the stmtexpr.
12904   QualType Ty = Context.VoidTy;
12905   bool StmtExprMayBindToTemp = false;
12906   if (!Compound->body_empty()) {
12907     Stmt *LastStmt = Compound->body_back();
12908     LabelStmt *LastLabelStmt = nullptr;
12909     // If LastStmt is a label, skip down through into the body.
12910     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12911       LastLabelStmt = Label;
12912       LastStmt = Label->getSubStmt();
12913     }
12914 
12915     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12916       // Do function/array conversion on the last expression, but not
12917       // lvalue-to-rvalue.  However, initialize an unqualified type.
12918       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12919       if (LastExpr.isInvalid())
12920         return ExprError();
12921       Ty = LastExpr.get()->getType().getUnqualifiedType();
12922 
12923       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12924         // In ARC, if the final expression ends in a consume, splice
12925         // the consume out and bind it later.  In the alternate case
12926         // (when dealing with a retainable type), the result
12927         // initialization will create a produce.  In both cases the
12928         // result will be +1, and we'll need to balance that out with
12929         // a bind.
12930         if (Expr *rebuiltLastStmt
12931               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12932           LastExpr = rebuiltLastStmt;
12933         } else {
12934           LastExpr = PerformCopyInitialization(
12935                             InitializedEntity::InitializeResult(LPLoc,
12936                                                                 Ty,
12937                                                                 false),
12938                                                    SourceLocation(),
12939                                                LastExpr);
12940         }
12941 
12942         if (LastExpr.isInvalid())
12943           return ExprError();
12944         if (LastExpr.get() != nullptr) {
12945           if (!LastLabelStmt)
12946             Compound->setLastStmt(LastExpr.get());
12947           else
12948             LastLabelStmt->setSubStmt(LastExpr.get());
12949           StmtExprMayBindToTemp = true;
12950         }
12951       }
12952     }
12953   }
12954 
12955   // FIXME: Check that expression type is complete/non-abstract; statement
12956   // expressions are not lvalues.
12957   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12958   if (StmtExprMayBindToTemp)
12959     return MaybeBindToTemporary(ResStmtExpr);
12960   return ResStmtExpr;
12961 }
12962 
12963 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12964                                       TypeSourceInfo *TInfo,
12965                                       ArrayRef<OffsetOfComponent> Components,
12966                                       SourceLocation RParenLoc) {
12967   QualType ArgTy = TInfo->getType();
12968   bool Dependent = ArgTy->isDependentType();
12969   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12970 
12971   // We must have at least one component that refers to the type, and the first
12972   // one is known to be a field designator.  Verify that the ArgTy represents
12973   // a struct/union/class.
12974   if (!Dependent && !ArgTy->isRecordType())
12975     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12976                        << ArgTy << TypeRange);
12977 
12978   // Type must be complete per C99 7.17p3 because a declaring a variable
12979   // with an incomplete type would be ill-formed.
12980   if (!Dependent
12981       && RequireCompleteType(BuiltinLoc, ArgTy,
12982                              diag::err_offsetof_incomplete_type, TypeRange))
12983     return ExprError();
12984 
12985   bool DidWarnAboutNonPOD = false;
12986   QualType CurrentType = ArgTy;
12987   SmallVector<OffsetOfNode, 4> Comps;
12988   SmallVector<Expr*, 4> Exprs;
12989   for (const OffsetOfComponent &OC : Components) {
12990     if (OC.isBrackets) {
12991       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12992       if (!CurrentType->isDependentType()) {
12993         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12994         if(!AT)
12995           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12996                            << CurrentType);
12997         CurrentType = AT->getElementType();
12998       } else
12999         CurrentType = Context.DependentTy;
13000 
13001       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13002       if (IdxRval.isInvalid())
13003         return ExprError();
13004       Expr *Idx = IdxRval.get();
13005 
13006       // The expression must be an integral expression.
13007       // FIXME: An integral constant expression?
13008       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13009           !Idx->getType()->isIntegerType())
13010         return ExprError(Diag(Idx->getLocStart(),
13011                               diag::err_typecheck_subscript_not_integer)
13012                          << Idx->getSourceRange());
13013 
13014       // Record this array index.
13015       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13016       Exprs.push_back(Idx);
13017       continue;
13018     }
13019 
13020     // Offset of a field.
13021     if (CurrentType->isDependentType()) {
13022       // We have the offset of a field, but we can't look into the dependent
13023       // type. Just record the identifier of the field.
13024       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13025       CurrentType = Context.DependentTy;
13026       continue;
13027     }
13028 
13029     // We need to have a complete type to look into.
13030     if (RequireCompleteType(OC.LocStart, CurrentType,
13031                             diag::err_offsetof_incomplete_type))
13032       return ExprError();
13033 
13034     // Look for the designated field.
13035     const RecordType *RC = CurrentType->getAs<RecordType>();
13036     if (!RC)
13037       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13038                        << CurrentType);
13039     RecordDecl *RD = RC->getDecl();
13040 
13041     // C++ [lib.support.types]p5:
13042     //   The macro offsetof accepts a restricted set of type arguments in this
13043     //   International Standard. type shall be a POD structure or a POD union
13044     //   (clause 9).
13045     // C++11 [support.types]p4:
13046     //   If type is not a standard-layout class (Clause 9), the results are
13047     //   undefined.
13048     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13049       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13050       unsigned DiagID =
13051         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13052                             : diag::ext_offsetof_non_pod_type;
13053 
13054       if (!IsSafe && !DidWarnAboutNonPOD &&
13055           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13056                               PDiag(DiagID)
13057                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13058                               << CurrentType))
13059         DidWarnAboutNonPOD = true;
13060     }
13061 
13062     // Look for the field.
13063     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13064     LookupQualifiedName(R, RD);
13065     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13066     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13067     if (!MemberDecl) {
13068       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13069         MemberDecl = IndirectMemberDecl->getAnonField();
13070     }
13071 
13072     if (!MemberDecl)
13073       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13074                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13075                                                               OC.LocEnd));
13076 
13077     // C99 7.17p3:
13078     //   (If the specified member is a bit-field, the behavior is undefined.)
13079     //
13080     // We diagnose this as an error.
13081     if (MemberDecl->isBitField()) {
13082       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13083         << MemberDecl->getDeclName()
13084         << SourceRange(BuiltinLoc, RParenLoc);
13085       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13086       return ExprError();
13087     }
13088 
13089     RecordDecl *Parent = MemberDecl->getParent();
13090     if (IndirectMemberDecl)
13091       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13092 
13093     // If the member was found in a base class, introduce OffsetOfNodes for
13094     // the base class indirections.
13095     CXXBasePaths Paths;
13096     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13097                       Paths)) {
13098       if (Paths.getDetectedVirtual()) {
13099         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13100           << MemberDecl->getDeclName()
13101           << SourceRange(BuiltinLoc, RParenLoc);
13102         return ExprError();
13103       }
13104 
13105       CXXBasePath &Path = Paths.front();
13106       for (const CXXBasePathElement &B : Path)
13107         Comps.push_back(OffsetOfNode(B.Base));
13108     }
13109 
13110     if (IndirectMemberDecl) {
13111       for (auto *FI : IndirectMemberDecl->chain()) {
13112         assert(isa<FieldDecl>(FI));
13113         Comps.push_back(OffsetOfNode(OC.LocStart,
13114                                      cast<FieldDecl>(FI), OC.LocEnd));
13115       }
13116     } else
13117       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13118 
13119     CurrentType = MemberDecl->getType().getNonReferenceType();
13120   }
13121 
13122   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13123                               Comps, Exprs, RParenLoc);
13124 }
13125 
13126 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13127                                       SourceLocation BuiltinLoc,
13128                                       SourceLocation TypeLoc,
13129                                       ParsedType ParsedArgTy,
13130                                       ArrayRef<OffsetOfComponent> Components,
13131                                       SourceLocation RParenLoc) {
13132 
13133   TypeSourceInfo *ArgTInfo;
13134   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13135   if (ArgTy.isNull())
13136     return ExprError();
13137 
13138   if (!ArgTInfo)
13139     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13140 
13141   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13142 }
13143 
13144 
13145 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13146                                  Expr *CondExpr,
13147                                  Expr *LHSExpr, Expr *RHSExpr,
13148                                  SourceLocation RPLoc) {
13149   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13150 
13151   ExprValueKind VK = VK_RValue;
13152   ExprObjectKind OK = OK_Ordinary;
13153   QualType resType;
13154   bool ValueDependent = false;
13155   bool CondIsTrue = false;
13156   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13157     resType = Context.DependentTy;
13158     ValueDependent = true;
13159   } else {
13160     // The conditional expression is required to be a constant expression.
13161     llvm::APSInt condEval(32);
13162     ExprResult CondICE
13163       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13164           diag::err_typecheck_choose_expr_requires_constant, false);
13165     if (CondICE.isInvalid())
13166       return ExprError();
13167     CondExpr = CondICE.get();
13168     CondIsTrue = condEval.getZExtValue();
13169 
13170     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13171     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13172 
13173     resType = ActiveExpr->getType();
13174     ValueDependent = ActiveExpr->isValueDependent();
13175     VK = ActiveExpr->getValueKind();
13176     OK = ActiveExpr->getObjectKind();
13177   }
13178 
13179   return new (Context)
13180       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13181                  CondIsTrue, resType->isDependentType(), ValueDependent);
13182 }
13183 
13184 //===----------------------------------------------------------------------===//
13185 // Clang Extensions.
13186 //===----------------------------------------------------------------------===//
13187 
13188 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13189 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13190   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13191 
13192   if (LangOpts.CPlusPlus) {
13193     Decl *ManglingContextDecl;
13194     if (MangleNumberingContext *MCtx =
13195             getCurrentMangleNumberContext(Block->getDeclContext(),
13196                                           ManglingContextDecl)) {
13197       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13198       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13199     }
13200   }
13201 
13202   PushBlockScope(CurScope, Block);
13203   CurContext->addDecl(Block);
13204   if (CurScope)
13205     PushDeclContext(CurScope, Block);
13206   else
13207     CurContext = Block;
13208 
13209   getCurBlock()->HasImplicitReturnType = true;
13210 
13211   // Enter a new evaluation context to insulate the block from any
13212   // cleanups from the enclosing full-expression.
13213   PushExpressionEvaluationContext(
13214       ExpressionEvaluationContext::PotentiallyEvaluated);
13215 }
13216 
13217 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13218                                Scope *CurScope) {
13219   assert(ParamInfo.getIdentifier() == nullptr &&
13220          "block-id should have no identifier!");
13221   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13222   BlockScopeInfo *CurBlock = getCurBlock();
13223 
13224   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13225   QualType T = Sig->getType();
13226 
13227   // FIXME: We should allow unexpanded parameter packs here, but that would,
13228   // in turn, make the block expression contain unexpanded parameter packs.
13229   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13230     // Drop the parameters.
13231     FunctionProtoType::ExtProtoInfo EPI;
13232     EPI.HasTrailingReturn = false;
13233     EPI.TypeQuals |= DeclSpec::TQ_const;
13234     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13235     Sig = Context.getTrivialTypeSourceInfo(T);
13236   }
13237 
13238   // GetTypeForDeclarator always produces a function type for a block
13239   // literal signature.  Furthermore, it is always a FunctionProtoType
13240   // unless the function was written with a typedef.
13241   assert(T->isFunctionType() &&
13242          "GetTypeForDeclarator made a non-function block signature");
13243 
13244   // Look for an explicit signature in that function type.
13245   FunctionProtoTypeLoc ExplicitSignature;
13246 
13247   if ((ExplicitSignature =
13248            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13249 
13250     // Check whether that explicit signature was synthesized by
13251     // GetTypeForDeclarator.  If so, don't save that as part of the
13252     // written signature.
13253     if (ExplicitSignature.getLocalRangeBegin() ==
13254         ExplicitSignature.getLocalRangeEnd()) {
13255       // This would be much cheaper if we stored TypeLocs instead of
13256       // TypeSourceInfos.
13257       TypeLoc Result = ExplicitSignature.getReturnLoc();
13258       unsigned Size = Result.getFullDataSize();
13259       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13260       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13261 
13262       ExplicitSignature = FunctionProtoTypeLoc();
13263     }
13264   }
13265 
13266   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13267   CurBlock->FunctionType = T;
13268 
13269   const FunctionType *Fn = T->getAs<FunctionType>();
13270   QualType RetTy = Fn->getReturnType();
13271   bool isVariadic =
13272     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13273 
13274   CurBlock->TheDecl->setIsVariadic(isVariadic);
13275 
13276   // Context.DependentTy is used as a placeholder for a missing block
13277   // return type.  TODO:  what should we do with declarators like:
13278   //   ^ * { ... }
13279   // If the answer is "apply template argument deduction"....
13280   if (RetTy != Context.DependentTy) {
13281     CurBlock->ReturnType = RetTy;
13282     CurBlock->TheDecl->setBlockMissingReturnType(false);
13283     CurBlock->HasImplicitReturnType = false;
13284   }
13285 
13286   // Push block parameters from the declarator if we had them.
13287   SmallVector<ParmVarDecl*, 8> Params;
13288   if (ExplicitSignature) {
13289     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13290       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13291       if (Param->getIdentifier() == nullptr &&
13292           !Param->isImplicit() &&
13293           !Param->isInvalidDecl() &&
13294           !getLangOpts().CPlusPlus)
13295         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13296       Params.push_back(Param);
13297     }
13298 
13299   // Fake up parameter variables if we have a typedef, like
13300   //   ^ fntype { ... }
13301   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13302     for (const auto &I : Fn->param_types()) {
13303       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13304           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13305       Params.push_back(Param);
13306     }
13307   }
13308 
13309   // Set the parameters on the block decl.
13310   if (!Params.empty()) {
13311     CurBlock->TheDecl->setParams(Params);
13312     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13313                              /*CheckParameterNames=*/false);
13314   }
13315 
13316   // Finally we can process decl attributes.
13317   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13318 
13319   // Put the parameter variables in scope.
13320   for (auto AI : CurBlock->TheDecl->parameters()) {
13321     AI->setOwningFunction(CurBlock->TheDecl);
13322 
13323     // If this has an identifier, add it to the scope stack.
13324     if (AI->getIdentifier()) {
13325       CheckShadow(CurBlock->TheScope, AI);
13326 
13327       PushOnScopeChains(AI, CurBlock->TheScope);
13328     }
13329   }
13330 }
13331 
13332 /// ActOnBlockError - If there is an error parsing a block, this callback
13333 /// is invoked to pop the information about the block from the action impl.
13334 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13335   // Leave the expression-evaluation context.
13336   DiscardCleanupsInEvaluationContext();
13337   PopExpressionEvaluationContext();
13338 
13339   // Pop off CurBlock, handle nested blocks.
13340   PopDeclContext();
13341   PopFunctionScopeInfo();
13342 }
13343 
13344 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13345 /// literal was successfully completed.  ^(int x){...}
13346 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13347                                     Stmt *Body, Scope *CurScope) {
13348   // If blocks are disabled, emit an error.
13349   if (!LangOpts.Blocks)
13350     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13351 
13352   // Leave the expression-evaluation context.
13353   if (hasAnyUnrecoverableErrorsInThisFunction())
13354     DiscardCleanupsInEvaluationContext();
13355   assert(!Cleanup.exprNeedsCleanups() &&
13356          "cleanups within block not correctly bound!");
13357   PopExpressionEvaluationContext();
13358 
13359   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13360 
13361   if (BSI->HasImplicitReturnType)
13362     deduceClosureReturnType(*BSI);
13363 
13364   PopDeclContext();
13365 
13366   QualType RetTy = Context.VoidTy;
13367   if (!BSI->ReturnType.isNull())
13368     RetTy = BSI->ReturnType;
13369 
13370   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13371   QualType BlockTy;
13372 
13373   // Set the captured variables on the block.
13374   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13375   SmallVector<BlockDecl::Capture, 4> Captures;
13376   for (Capture &Cap : BSI->Captures) {
13377     if (Cap.isThisCapture())
13378       continue;
13379     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13380                               Cap.isNested(), Cap.getInitExpr());
13381     Captures.push_back(NewCap);
13382   }
13383   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13384 
13385   // If the user wrote a function type in some form, try to use that.
13386   if (!BSI->FunctionType.isNull()) {
13387     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13388 
13389     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13390     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13391 
13392     // Turn protoless block types into nullary block types.
13393     if (isa<FunctionNoProtoType>(FTy)) {
13394       FunctionProtoType::ExtProtoInfo EPI;
13395       EPI.ExtInfo = Ext;
13396       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13397 
13398     // Otherwise, if we don't need to change anything about the function type,
13399     // preserve its sugar structure.
13400     } else if (FTy->getReturnType() == RetTy &&
13401                (!NoReturn || FTy->getNoReturnAttr())) {
13402       BlockTy = BSI->FunctionType;
13403 
13404     // Otherwise, make the minimal modifications to the function type.
13405     } else {
13406       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13407       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13408       EPI.TypeQuals = 0; // FIXME: silently?
13409       EPI.ExtInfo = Ext;
13410       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13411     }
13412 
13413   // If we don't have a function type, just build one from nothing.
13414   } else {
13415     FunctionProtoType::ExtProtoInfo EPI;
13416     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13417     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13418   }
13419 
13420   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13421   BlockTy = Context.getBlockPointerType(BlockTy);
13422 
13423   // If needed, diagnose invalid gotos and switches in the block.
13424   if (getCurFunction()->NeedsScopeChecking() &&
13425       !PP.isCodeCompletionEnabled())
13426     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13427 
13428   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13429 
13430   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13431     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13432 
13433   // Try to apply the named return value optimization. We have to check again
13434   // if we can do this, though, because blocks keep return statements around
13435   // to deduce an implicit return type.
13436   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13437       !BSI->TheDecl->isDependentContext())
13438     computeNRVO(Body, BSI);
13439 
13440   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13441   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13442   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13443 
13444   // If the block isn't obviously global, i.e. it captures anything at
13445   // all, then we need to do a few things in the surrounding context:
13446   if (Result->getBlockDecl()->hasCaptures()) {
13447     // First, this expression has a new cleanup object.
13448     ExprCleanupObjects.push_back(Result->getBlockDecl());
13449     Cleanup.setExprNeedsCleanups(true);
13450 
13451     // It also gets a branch-protected scope if any of the captured
13452     // variables needs destruction.
13453     for (const auto &CI : Result->getBlockDecl()->captures()) {
13454       const VarDecl *var = CI.getVariable();
13455       if (var->getType().isDestructedType() != QualType::DK_none) {
13456         setFunctionHasBranchProtectedScope();
13457         break;
13458       }
13459     }
13460   }
13461 
13462   return Result;
13463 }
13464 
13465 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13466                             SourceLocation RPLoc) {
13467   TypeSourceInfo *TInfo;
13468   GetTypeFromParser(Ty, &TInfo);
13469   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13470 }
13471 
13472 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13473                                 Expr *E, TypeSourceInfo *TInfo,
13474                                 SourceLocation RPLoc) {
13475   Expr *OrigExpr = E;
13476   bool IsMS = false;
13477 
13478   // CUDA device code does not support varargs.
13479   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13480     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13481       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13482       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13483         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13484     }
13485   }
13486 
13487   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13488   // as Microsoft ABI on an actual Microsoft platform, where
13489   // __builtin_ms_va_list and __builtin_va_list are the same.)
13490   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13491       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13492     QualType MSVaListType = Context.getBuiltinMSVaListType();
13493     if (Context.hasSameType(MSVaListType, E->getType())) {
13494       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13495         return ExprError();
13496       IsMS = true;
13497     }
13498   }
13499 
13500   // Get the va_list type
13501   QualType VaListType = Context.getBuiltinVaListType();
13502   if (!IsMS) {
13503     if (VaListType->isArrayType()) {
13504       // Deal with implicit array decay; for example, on x86-64,
13505       // va_list is an array, but it's supposed to decay to
13506       // a pointer for va_arg.
13507       VaListType = Context.getArrayDecayedType(VaListType);
13508       // Make sure the input expression also decays appropriately.
13509       ExprResult Result = UsualUnaryConversions(E);
13510       if (Result.isInvalid())
13511         return ExprError();
13512       E = Result.get();
13513     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13514       // If va_list is a record type and we are compiling in C++ mode,
13515       // check the argument using reference binding.
13516       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13517           Context, Context.getLValueReferenceType(VaListType), false);
13518       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13519       if (Init.isInvalid())
13520         return ExprError();
13521       E = Init.getAs<Expr>();
13522     } else {
13523       // Otherwise, the va_list argument must be an l-value because
13524       // it is modified by va_arg.
13525       if (!E->isTypeDependent() &&
13526           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13527         return ExprError();
13528     }
13529   }
13530 
13531   if (!IsMS && !E->isTypeDependent() &&
13532       !Context.hasSameType(VaListType, E->getType()))
13533     return ExprError(Diag(E->getLocStart(),
13534                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13535       << OrigExpr->getType() << E->getSourceRange());
13536 
13537   if (!TInfo->getType()->isDependentType()) {
13538     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13539                             diag::err_second_parameter_to_va_arg_incomplete,
13540                             TInfo->getTypeLoc()))
13541       return ExprError();
13542 
13543     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13544                                TInfo->getType(),
13545                                diag::err_second_parameter_to_va_arg_abstract,
13546                                TInfo->getTypeLoc()))
13547       return ExprError();
13548 
13549     if (!TInfo->getType().isPODType(Context)) {
13550       Diag(TInfo->getTypeLoc().getBeginLoc(),
13551            TInfo->getType()->isObjCLifetimeType()
13552              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13553              : diag::warn_second_parameter_to_va_arg_not_pod)
13554         << TInfo->getType()
13555         << TInfo->getTypeLoc().getSourceRange();
13556     }
13557 
13558     // Check for va_arg where arguments of the given type will be promoted
13559     // (i.e. this va_arg is guaranteed to have undefined behavior).
13560     QualType PromoteType;
13561     if (TInfo->getType()->isPromotableIntegerType()) {
13562       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13563       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13564         PromoteType = QualType();
13565     }
13566     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13567       PromoteType = Context.DoubleTy;
13568     if (!PromoteType.isNull())
13569       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13570                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13571                           << TInfo->getType()
13572                           << PromoteType
13573                           << TInfo->getTypeLoc().getSourceRange());
13574   }
13575 
13576   QualType T = TInfo->getType().getNonLValueExprType(Context);
13577   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13578 }
13579 
13580 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13581   // The type of __null will be int or long, depending on the size of
13582   // pointers on the target.
13583   QualType Ty;
13584   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13585   if (pw == Context.getTargetInfo().getIntWidth())
13586     Ty = Context.IntTy;
13587   else if (pw == Context.getTargetInfo().getLongWidth())
13588     Ty = Context.LongTy;
13589   else if (pw == Context.getTargetInfo().getLongLongWidth())
13590     Ty = Context.LongLongTy;
13591   else {
13592     llvm_unreachable("I don't know size of pointer!");
13593   }
13594 
13595   return new (Context) GNUNullExpr(Ty, TokenLoc);
13596 }
13597 
13598 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13599                                               bool Diagnose) {
13600   if (!getLangOpts().ObjC1)
13601     return false;
13602 
13603   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13604   if (!PT)
13605     return false;
13606 
13607   if (!PT->isObjCIdType()) {
13608     // Check if the destination is the 'NSString' interface.
13609     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13610     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13611       return false;
13612   }
13613 
13614   // Ignore any parens, implicit casts (should only be
13615   // array-to-pointer decays), and not-so-opaque values.  The last is
13616   // important for making this trigger for property assignments.
13617   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13618   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13619     if (OV->getSourceExpr())
13620       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13621 
13622   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13623   if (!SL || !SL->isAscii())
13624     return false;
13625   if (Diagnose) {
13626     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13627       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13628     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13629   }
13630   return true;
13631 }
13632 
13633 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13634                                               const Expr *SrcExpr) {
13635   if (!DstType->isFunctionPointerType() ||
13636       !SrcExpr->getType()->isFunctionType())
13637     return false;
13638 
13639   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13640   if (!DRE)
13641     return false;
13642 
13643   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13644   if (!FD)
13645     return false;
13646 
13647   return !S.checkAddressOfFunctionIsAvailable(FD,
13648                                               /*Complain=*/true,
13649                                               SrcExpr->getLocStart());
13650 }
13651 
13652 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13653                                     SourceLocation Loc,
13654                                     QualType DstType, QualType SrcType,
13655                                     Expr *SrcExpr, AssignmentAction Action,
13656                                     bool *Complained) {
13657   if (Complained)
13658     *Complained = false;
13659 
13660   // Decode the result (notice that AST's are still created for extensions).
13661   bool CheckInferredResultType = false;
13662   bool isInvalid = false;
13663   unsigned DiagKind = 0;
13664   FixItHint Hint;
13665   ConversionFixItGenerator ConvHints;
13666   bool MayHaveConvFixit = false;
13667   bool MayHaveFunctionDiff = false;
13668   const ObjCInterfaceDecl *IFace = nullptr;
13669   const ObjCProtocolDecl *PDecl = nullptr;
13670 
13671   switch (ConvTy) {
13672   case Compatible:
13673       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13674       return false;
13675 
13676   case PointerToInt:
13677     DiagKind = diag::ext_typecheck_convert_pointer_int;
13678     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13679     MayHaveConvFixit = true;
13680     break;
13681   case IntToPointer:
13682     DiagKind = diag::ext_typecheck_convert_int_pointer;
13683     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13684     MayHaveConvFixit = true;
13685     break;
13686   case IncompatiblePointer:
13687     if (Action == AA_Passing_CFAudited)
13688       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13689     else if (SrcType->isFunctionPointerType() &&
13690              DstType->isFunctionPointerType())
13691       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13692     else
13693       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13694 
13695     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13696       SrcType->isObjCObjectPointerType();
13697     if (Hint.isNull() && !CheckInferredResultType) {
13698       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13699     }
13700     else if (CheckInferredResultType) {
13701       SrcType = SrcType.getUnqualifiedType();
13702       DstType = DstType.getUnqualifiedType();
13703     }
13704     MayHaveConvFixit = true;
13705     break;
13706   case IncompatiblePointerSign:
13707     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13708     break;
13709   case FunctionVoidPointer:
13710     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13711     break;
13712   case IncompatiblePointerDiscardsQualifiers: {
13713     // Perform array-to-pointer decay if necessary.
13714     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13715 
13716     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13717     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13718     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13719       DiagKind = diag::err_typecheck_incompatible_address_space;
13720       break;
13721 
13722     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13723       DiagKind = diag::err_typecheck_incompatible_ownership;
13724       break;
13725     }
13726 
13727     llvm_unreachable("unknown error case for discarding qualifiers!");
13728     // fallthrough
13729   }
13730   case CompatiblePointerDiscardsQualifiers:
13731     // If the qualifiers lost were because we were applying the
13732     // (deprecated) C++ conversion from a string literal to a char*
13733     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13734     // Ideally, this check would be performed in
13735     // checkPointerTypesForAssignment. However, that would require a
13736     // bit of refactoring (so that the second argument is an
13737     // expression, rather than a type), which should be done as part
13738     // of a larger effort to fix checkPointerTypesForAssignment for
13739     // C++ semantics.
13740     if (getLangOpts().CPlusPlus &&
13741         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13742       return false;
13743     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13744     break;
13745   case IncompatibleNestedPointerQualifiers:
13746     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13747     break;
13748   case IntToBlockPointer:
13749     DiagKind = diag::err_int_to_block_pointer;
13750     break;
13751   case IncompatibleBlockPointer:
13752     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13753     break;
13754   case IncompatibleObjCQualifiedId: {
13755     if (SrcType->isObjCQualifiedIdType()) {
13756       const ObjCObjectPointerType *srcOPT =
13757                 SrcType->getAs<ObjCObjectPointerType>();
13758       for (auto *srcProto : srcOPT->quals()) {
13759         PDecl = srcProto;
13760         break;
13761       }
13762       if (const ObjCInterfaceType *IFaceT =
13763             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13764         IFace = IFaceT->getDecl();
13765     }
13766     else if (DstType->isObjCQualifiedIdType()) {
13767       const ObjCObjectPointerType *dstOPT =
13768         DstType->getAs<ObjCObjectPointerType>();
13769       for (auto *dstProto : dstOPT->quals()) {
13770         PDecl = dstProto;
13771         break;
13772       }
13773       if (const ObjCInterfaceType *IFaceT =
13774             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13775         IFace = IFaceT->getDecl();
13776     }
13777     DiagKind = diag::warn_incompatible_qualified_id;
13778     break;
13779   }
13780   case IncompatibleVectors:
13781     DiagKind = diag::warn_incompatible_vectors;
13782     break;
13783   case IncompatibleObjCWeakRef:
13784     DiagKind = diag::err_arc_weak_unavailable_assign;
13785     break;
13786   case Incompatible:
13787     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13788       if (Complained)
13789         *Complained = true;
13790       return true;
13791     }
13792 
13793     DiagKind = diag::err_typecheck_convert_incompatible;
13794     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13795     MayHaveConvFixit = true;
13796     isInvalid = true;
13797     MayHaveFunctionDiff = true;
13798     break;
13799   }
13800 
13801   QualType FirstType, SecondType;
13802   switch (Action) {
13803   case AA_Assigning:
13804   case AA_Initializing:
13805     // The destination type comes first.
13806     FirstType = DstType;
13807     SecondType = SrcType;
13808     break;
13809 
13810   case AA_Returning:
13811   case AA_Passing:
13812   case AA_Passing_CFAudited:
13813   case AA_Converting:
13814   case AA_Sending:
13815   case AA_Casting:
13816     // The source type comes first.
13817     FirstType = SrcType;
13818     SecondType = DstType;
13819     break;
13820   }
13821 
13822   PartialDiagnostic FDiag = PDiag(DiagKind);
13823   if (Action == AA_Passing_CFAudited)
13824     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13825   else
13826     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13827 
13828   // If we can fix the conversion, suggest the FixIts.
13829   assert(ConvHints.isNull() || Hint.isNull());
13830   if (!ConvHints.isNull()) {
13831     for (FixItHint &H : ConvHints.Hints)
13832       FDiag << H;
13833   } else {
13834     FDiag << Hint;
13835   }
13836   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13837 
13838   if (MayHaveFunctionDiff)
13839     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13840 
13841   Diag(Loc, FDiag);
13842   if (DiagKind == diag::warn_incompatible_qualified_id &&
13843       PDecl && IFace && !IFace->hasDefinition())
13844       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13845         << IFace << PDecl;
13846 
13847   if (SecondType == Context.OverloadTy)
13848     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13849                               FirstType, /*TakingAddress=*/true);
13850 
13851   if (CheckInferredResultType)
13852     EmitRelatedResultTypeNote(SrcExpr);
13853 
13854   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13855     EmitRelatedResultTypeNoteForReturn(DstType);
13856 
13857   if (Complained)
13858     *Complained = true;
13859   return isInvalid;
13860 }
13861 
13862 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13863                                                  llvm::APSInt *Result) {
13864   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13865   public:
13866     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13867       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13868     }
13869   } Diagnoser;
13870 
13871   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13872 }
13873 
13874 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13875                                                  llvm::APSInt *Result,
13876                                                  unsigned DiagID,
13877                                                  bool AllowFold) {
13878   class IDDiagnoser : public VerifyICEDiagnoser {
13879     unsigned DiagID;
13880 
13881   public:
13882     IDDiagnoser(unsigned DiagID)
13883       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13884 
13885     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13886       S.Diag(Loc, DiagID) << SR;
13887     }
13888   } Diagnoser(DiagID);
13889 
13890   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13891 }
13892 
13893 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13894                                             SourceRange SR) {
13895   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13896 }
13897 
13898 ExprResult
13899 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13900                                       VerifyICEDiagnoser &Diagnoser,
13901                                       bool AllowFold) {
13902   SourceLocation DiagLoc = E->getLocStart();
13903 
13904   if (getLangOpts().CPlusPlus11) {
13905     // C++11 [expr.const]p5:
13906     //   If an expression of literal class type is used in a context where an
13907     //   integral constant expression is required, then that class type shall
13908     //   have a single non-explicit conversion function to an integral or
13909     //   unscoped enumeration type
13910     ExprResult Converted;
13911     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13912     public:
13913       CXX11ConvertDiagnoser(bool Silent)
13914           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13915                                 Silent, true) {}
13916 
13917       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13918                                            QualType T) override {
13919         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13920       }
13921 
13922       SemaDiagnosticBuilder diagnoseIncomplete(
13923           Sema &S, SourceLocation Loc, QualType T) override {
13924         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13925       }
13926 
13927       SemaDiagnosticBuilder diagnoseExplicitConv(
13928           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13929         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13930       }
13931 
13932       SemaDiagnosticBuilder noteExplicitConv(
13933           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13934         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13935                  << ConvTy->isEnumeralType() << ConvTy;
13936       }
13937 
13938       SemaDiagnosticBuilder diagnoseAmbiguous(
13939           Sema &S, SourceLocation Loc, QualType T) override {
13940         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13941       }
13942 
13943       SemaDiagnosticBuilder noteAmbiguous(
13944           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13945         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13946                  << ConvTy->isEnumeralType() << ConvTy;
13947       }
13948 
13949       SemaDiagnosticBuilder diagnoseConversion(
13950           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13951         llvm_unreachable("conversion functions are permitted");
13952       }
13953     } ConvertDiagnoser(Diagnoser.Suppress);
13954 
13955     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13956                                                     ConvertDiagnoser);
13957     if (Converted.isInvalid())
13958       return Converted;
13959     E = Converted.get();
13960     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13961       return ExprError();
13962   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13963     // An ICE must be of integral or unscoped enumeration type.
13964     if (!Diagnoser.Suppress)
13965       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13966     return ExprError();
13967   }
13968 
13969   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13970   // in the non-ICE case.
13971   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13972     if (Result)
13973       *Result = E->EvaluateKnownConstInt(Context);
13974     return E;
13975   }
13976 
13977   Expr::EvalResult EvalResult;
13978   SmallVector<PartialDiagnosticAt, 8> Notes;
13979   EvalResult.Diag = &Notes;
13980 
13981   // Try to evaluate the expression, and produce diagnostics explaining why it's
13982   // not a constant expression as a side-effect.
13983   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13984                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13985 
13986   // In C++11, we can rely on diagnostics being produced for any expression
13987   // which is not a constant expression. If no diagnostics were produced, then
13988   // this is a constant expression.
13989   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13990     if (Result)
13991       *Result = EvalResult.Val.getInt();
13992     return E;
13993   }
13994 
13995   // If our only note is the usual "invalid subexpression" note, just point
13996   // the caret at its location rather than producing an essentially
13997   // redundant note.
13998   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13999         diag::note_invalid_subexpr_in_const_expr) {
14000     DiagLoc = Notes[0].first;
14001     Notes.clear();
14002   }
14003 
14004   if (!Folded || !AllowFold) {
14005     if (!Diagnoser.Suppress) {
14006       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14007       for (const PartialDiagnosticAt &Note : Notes)
14008         Diag(Note.first, Note.second);
14009     }
14010 
14011     return ExprError();
14012   }
14013 
14014   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14015   for (const PartialDiagnosticAt &Note : Notes)
14016     Diag(Note.first, Note.second);
14017 
14018   if (Result)
14019     *Result = EvalResult.Val.getInt();
14020   return E;
14021 }
14022 
14023 namespace {
14024   // Handle the case where we conclude a expression which we speculatively
14025   // considered to be unevaluated is actually evaluated.
14026   class TransformToPE : public TreeTransform<TransformToPE> {
14027     typedef TreeTransform<TransformToPE> BaseTransform;
14028 
14029   public:
14030     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14031 
14032     // Make sure we redo semantic analysis
14033     bool AlwaysRebuild() { return true; }
14034 
14035     // Make sure we handle LabelStmts correctly.
14036     // FIXME: This does the right thing, but maybe we need a more general
14037     // fix to TreeTransform?
14038     StmtResult TransformLabelStmt(LabelStmt *S) {
14039       S->getDecl()->setStmt(nullptr);
14040       return BaseTransform::TransformLabelStmt(S);
14041     }
14042 
14043     // We need to special-case DeclRefExprs referring to FieldDecls which
14044     // are not part of a member pointer formation; normal TreeTransforming
14045     // doesn't catch this case because of the way we represent them in the AST.
14046     // FIXME: This is a bit ugly; is it really the best way to handle this
14047     // case?
14048     //
14049     // Error on DeclRefExprs referring to FieldDecls.
14050     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14051       if (isa<FieldDecl>(E->getDecl()) &&
14052           !SemaRef.isUnevaluatedContext())
14053         return SemaRef.Diag(E->getLocation(),
14054                             diag::err_invalid_non_static_member_use)
14055             << E->getDecl() << E->getSourceRange();
14056 
14057       return BaseTransform::TransformDeclRefExpr(E);
14058     }
14059 
14060     // Exception: filter out member pointer formation
14061     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14062       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14063         return E;
14064 
14065       return BaseTransform::TransformUnaryOperator(E);
14066     }
14067 
14068     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14069       // Lambdas never need to be transformed.
14070       return E;
14071     }
14072   };
14073 }
14074 
14075 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14076   assert(isUnevaluatedContext() &&
14077          "Should only transform unevaluated expressions");
14078   ExprEvalContexts.back().Context =
14079       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14080   if (isUnevaluatedContext())
14081     return E;
14082   return TransformToPE(*this).TransformExpr(E);
14083 }
14084 
14085 void
14086 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
14087                                       Decl *LambdaContextDecl,
14088                                       bool IsDecltype) {
14089   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14090                                 LambdaContextDecl, IsDecltype);
14091   Cleanup.reset();
14092   if (!MaybeODRUseExprs.empty())
14093     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14094 }
14095 
14096 void
14097 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
14098                                       ReuseLambdaContextDecl_t,
14099                                       bool IsDecltype) {
14100   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14101   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
14102 }
14103 
14104 void Sema::PopExpressionEvaluationContext() {
14105   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14106   unsigned NumTypos = Rec.NumTypos;
14107 
14108   if (!Rec.Lambdas.empty()) {
14109     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14110       unsigned D;
14111       if (Rec.isUnevaluated()) {
14112         // C++11 [expr.prim.lambda]p2:
14113         //   A lambda-expression shall not appear in an unevaluated operand
14114         //   (Clause 5).
14115         D = diag::err_lambda_unevaluated_operand;
14116       } else {
14117         // C++1y [expr.const]p2:
14118         //   A conditional-expression e is a core constant expression unless the
14119         //   evaluation of e, following the rules of the abstract machine, would
14120         //   evaluate [...] a lambda-expression.
14121         D = diag::err_lambda_in_constant_expression;
14122       }
14123 
14124       // C++1z allows lambda expressions as core constant expressions.
14125       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
14126       // 1607) from appearing within template-arguments and array-bounds that
14127       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
14128       // unevaluated contexts) might lift some of these restrictions in a
14129       // future version.
14130       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
14131         for (const auto *L : Rec.Lambdas)
14132           Diag(L->getLocStart(), D);
14133     } else {
14134       // Mark the capture expressions odr-used. This was deferred
14135       // during lambda expression creation.
14136       for (auto *Lambda : Rec.Lambdas) {
14137         for (auto *C : Lambda->capture_inits())
14138           MarkDeclarationsReferencedInExpr(C);
14139       }
14140     }
14141   }
14142 
14143   // When are coming out of an unevaluated context, clear out any
14144   // temporaries that we may have created as part of the evaluation of
14145   // the expression in that context: they aren't relevant because they
14146   // will never be constructed.
14147   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14148     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14149                              ExprCleanupObjects.end());
14150     Cleanup = Rec.ParentCleanup;
14151     CleanupVarDeclMarking();
14152     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14153   // Otherwise, merge the contexts together.
14154   } else {
14155     Cleanup.mergeFrom(Rec.ParentCleanup);
14156     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14157                             Rec.SavedMaybeODRUseExprs.end());
14158   }
14159 
14160   // Pop the current expression evaluation context off the stack.
14161   ExprEvalContexts.pop_back();
14162 
14163   if (!ExprEvalContexts.empty())
14164     ExprEvalContexts.back().NumTypos += NumTypos;
14165   else
14166     assert(NumTypos == 0 && "There are outstanding typos after popping the "
14167                             "last ExpressionEvaluationContextRecord");
14168 }
14169 
14170 void Sema::DiscardCleanupsInEvaluationContext() {
14171   ExprCleanupObjects.erase(
14172          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14173          ExprCleanupObjects.end());
14174   Cleanup.reset();
14175   MaybeODRUseExprs.clear();
14176 }
14177 
14178 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14179   if (!E->getType()->isVariablyModifiedType())
14180     return E;
14181   return TransformToPotentiallyEvaluated(E);
14182 }
14183 
14184 /// Are we within a context in which some evaluation could be performed (be it
14185 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14186 /// captured by C++'s idea of an "unevaluated context".
14187 static bool isEvaluatableContext(Sema &SemaRef) {
14188   switch (SemaRef.ExprEvalContexts.back().Context) {
14189     case Sema::ExpressionEvaluationContext::Unevaluated:
14190     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14191     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14192       // Expressions in this context are never evaluated.
14193       return false;
14194 
14195     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14196     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14197     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14198       // Expressions in this context could be evaluated.
14199       return true;
14200 
14201     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14202       // Referenced declarations will only be used if the construct in the
14203       // containing expression is used, at which point we'll be given another
14204       // turn to mark them.
14205       return false;
14206   }
14207   llvm_unreachable("Invalid context");
14208 }
14209 
14210 /// Are we within a context in which references to resolved functions or to
14211 /// variables result in odr-use?
14212 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14213   // An expression in a template is not really an expression until it's been
14214   // instantiated, so it doesn't trigger odr-use.
14215   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14216     return false;
14217 
14218   switch (SemaRef.ExprEvalContexts.back().Context) {
14219     case Sema::ExpressionEvaluationContext::Unevaluated:
14220     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14221     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14222     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14223       return false;
14224 
14225     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14226     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14227       return true;
14228 
14229     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14230       return false;
14231   }
14232   llvm_unreachable("Invalid context");
14233 }
14234 
14235 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14236   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14237   return Func->isConstexpr() &&
14238          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14239 }
14240 
14241 /// Mark a function referenced, and check whether it is odr-used
14242 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14243 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14244                                   bool MightBeOdrUse) {
14245   assert(Func && "No function?");
14246 
14247   Func->setReferenced();
14248 
14249   // C++11 [basic.def.odr]p3:
14250   //   A function whose name appears as a potentially-evaluated expression is
14251   //   odr-used if it is the unique lookup result or the selected member of a
14252   //   set of overloaded functions [...].
14253   //
14254   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14255   // can just check that here.
14256   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14257 
14258   // Determine whether we require a function definition to exist, per
14259   // C++11 [temp.inst]p3:
14260   //   Unless a function template specialization has been explicitly
14261   //   instantiated or explicitly specialized, the function template
14262   //   specialization is implicitly instantiated when the specialization is
14263   //   referenced in a context that requires a function definition to exist.
14264   //
14265   // That is either when this is an odr-use, or when a usage of a constexpr
14266   // function occurs within an evaluatable context.
14267   bool NeedDefinition =
14268       OdrUse || (isEvaluatableContext(*this) &&
14269                  isImplicitlyDefinableConstexprFunction(Func));
14270 
14271   // C++14 [temp.expl.spec]p6:
14272   //   If a template [...] is explicitly specialized then that specialization
14273   //   shall be declared before the first use of that specialization that would
14274   //   cause an implicit instantiation to take place, in every translation unit
14275   //   in which such a use occurs
14276   if (NeedDefinition &&
14277       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14278        Func->getMemberSpecializationInfo()))
14279     checkSpecializationVisibility(Loc, Func);
14280 
14281   // C++14 [except.spec]p17:
14282   //   An exception-specification is considered to be needed when:
14283   //   - the function is odr-used or, if it appears in an unevaluated operand,
14284   //     would be odr-used if the expression were potentially-evaluated;
14285   //
14286   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14287   // function is a pure virtual function we're calling, and in that case the
14288   // function was selected by overload resolution and we need to resolve its
14289   // exception specification for a different reason.
14290   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14291   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14292     ResolveExceptionSpec(Loc, FPT);
14293 
14294   // If we don't need to mark the function as used, and we don't need to
14295   // try to provide a definition, there's nothing more to do.
14296   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14297       (!NeedDefinition || Func->getBody()))
14298     return;
14299 
14300   // Note that this declaration has been used.
14301   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14302     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14303     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14304       if (Constructor->isDefaultConstructor()) {
14305         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14306           return;
14307         DefineImplicitDefaultConstructor(Loc, Constructor);
14308       } else if (Constructor->isCopyConstructor()) {
14309         DefineImplicitCopyConstructor(Loc, Constructor);
14310       } else if (Constructor->isMoveConstructor()) {
14311         DefineImplicitMoveConstructor(Loc, Constructor);
14312       }
14313     } else if (Constructor->getInheritedConstructor()) {
14314       DefineInheritingConstructor(Loc, Constructor);
14315     }
14316   } else if (CXXDestructorDecl *Destructor =
14317                  dyn_cast<CXXDestructorDecl>(Func)) {
14318     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14319     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14320       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14321         return;
14322       DefineImplicitDestructor(Loc, Destructor);
14323     }
14324     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14325       MarkVTableUsed(Loc, Destructor->getParent());
14326   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14327     if (MethodDecl->isOverloadedOperator() &&
14328         MethodDecl->getOverloadedOperator() == OO_Equal) {
14329       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14330       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14331         if (MethodDecl->isCopyAssignmentOperator())
14332           DefineImplicitCopyAssignment(Loc, MethodDecl);
14333         else if (MethodDecl->isMoveAssignmentOperator())
14334           DefineImplicitMoveAssignment(Loc, MethodDecl);
14335       }
14336     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14337                MethodDecl->getParent()->isLambda()) {
14338       CXXConversionDecl *Conversion =
14339           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14340       if (Conversion->isLambdaToBlockPointerConversion())
14341         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14342       else
14343         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14344     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14345       MarkVTableUsed(Loc, MethodDecl->getParent());
14346   }
14347 
14348   // Recursive functions should be marked when used from another function.
14349   // FIXME: Is this really right?
14350   if (CurContext == Func) return;
14351 
14352   // Implicit instantiation of function templates and member functions of
14353   // class templates.
14354   if (Func->isImplicitlyInstantiable()) {
14355     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14356     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14357     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14358     if (FirstInstantiation) {
14359       PointOfInstantiation = Loc;
14360       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14361     } else if (TSK != TSK_ImplicitInstantiation) {
14362       // Use the point of use as the point of instantiation, instead of the
14363       // point of explicit instantiation (which we track as the actual point of
14364       // instantiation). This gives better backtraces in diagnostics.
14365       PointOfInstantiation = Loc;
14366     }
14367 
14368     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14369         Func->isConstexpr()) {
14370       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14371           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14372           CodeSynthesisContexts.size())
14373         PendingLocalImplicitInstantiations.push_back(
14374             std::make_pair(Func, PointOfInstantiation));
14375       else if (Func->isConstexpr())
14376         // Do not defer instantiations of constexpr functions, to avoid the
14377         // expression evaluator needing to call back into Sema if it sees a
14378         // call to such a function.
14379         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14380       else {
14381         Func->setInstantiationIsPending(true);
14382         PendingInstantiations.push_back(std::make_pair(Func,
14383                                                        PointOfInstantiation));
14384         // Notify the consumer that a function was implicitly instantiated.
14385         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14386       }
14387     }
14388   } else {
14389     // Walk redefinitions, as some of them may be instantiable.
14390     for (auto i : Func->redecls()) {
14391       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14392         MarkFunctionReferenced(Loc, i, OdrUse);
14393     }
14394   }
14395 
14396   if (!OdrUse) return;
14397 
14398   // Keep track of used but undefined functions.
14399   if (!Func->isDefined()) {
14400     if (mightHaveNonExternalLinkage(Func))
14401       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14402     else if (Func->getMostRecentDecl()->isInlined() &&
14403              !LangOpts.GNUInline &&
14404              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14405       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14406     else if (isExternalWithNoLinkageType(Func))
14407       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14408   }
14409 
14410   Func->markUsed(Context);
14411 }
14412 
14413 static void
14414 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14415                                    ValueDecl *var, DeclContext *DC) {
14416   DeclContext *VarDC = var->getDeclContext();
14417 
14418   //  If the parameter still belongs to the translation unit, then
14419   //  we're actually just using one parameter in the declaration of
14420   //  the next.
14421   if (isa<ParmVarDecl>(var) &&
14422       isa<TranslationUnitDecl>(VarDC))
14423     return;
14424 
14425   // For C code, don't diagnose about capture if we're not actually in code
14426   // right now; it's impossible to write a non-constant expression outside of
14427   // function context, so we'll get other (more useful) diagnostics later.
14428   //
14429   // For C++, things get a bit more nasty... it would be nice to suppress this
14430   // diagnostic for certain cases like using a local variable in an array bound
14431   // for a member of a local class, but the correct predicate is not obvious.
14432   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14433     return;
14434 
14435   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14436   unsigned ContextKind = 3; // unknown
14437   if (isa<CXXMethodDecl>(VarDC) &&
14438       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14439     ContextKind = 2;
14440   } else if (isa<FunctionDecl>(VarDC)) {
14441     ContextKind = 0;
14442   } else if (isa<BlockDecl>(VarDC)) {
14443     ContextKind = 1;
14444   }
14445 
14446   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14447     << var << ValueKind << ContextKind << VarDC;
14448   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14449       << var;
14450 
14451   // FIXME: Add additional diagnostic info about class etc. which prevents
14452   // capture.
14453 }
14454 
14455 
14456 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14457                                       bool &SubCapturesAreNested,
14458                                       QualType &CaptureType,
14459                                       QualType &DeclRefType) {
14460    // Check whether we've already captured it.
14461   if (CSI->CaptureMap.count(Var)) {
14462     // If we found a capture, any subcaptures are nested.
14463     SubCapturesAreNested = true;
14464 
14465     // Retrieve the capture type for this variable.
14466     CaptureType = CSI->getCapture(Var).getCaptureType();
14467 
14468     // Compute the type of an expression that refers to this variable.
14469     DeclRefType = CaptureType.getNonReferenceType();
14470 
14471     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14472     // are mutable in the sense that user can change their value - they are
14473     // private instances of the captured declarations.
14474     const Capture &Cap = CSI->getCapture(Var);
14475     if (Cap.isCopyCapture() &&
14476         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14477         !(isa<CapturedRegionScopeInfo>(CSI) &&
14478           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14479       DeclRefType.addConst();
14480     return true;
14481   }
14482   return false;
14483 }
14484 
14485 // Only block literals, captured statements, and lambda expressions can
14486 // capture; other scopes don't work.
14487 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14488                                  SourceLocation Loc,
14489                                  const bool Diagnose, Sema &S) {
14490   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14491     return getLambdaAwareParentOfDeclContext(DC);
14492   else if (Var->hasLocalStorage()) {
14493     if (Diagnose)
14494        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14495   }
14496   return nullptr;
14497 }
14498 
14499 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14500 // certain types of variables (unnamed, variably modified types etc.)
14501 // so check for eligibility.
14502 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14503                                  SourceLocation Loc,
14504                                  const bool Diagnose, Sema &S) {
14505 
14506   bool IsBlock = isa<BlockScopeInfo>(CSI);
14507   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14508 
14509   // Lambdas are not allowed to capture unnamed variables
14510   // (e.g. anonymous unions).
14511   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14512   // assuming that's the intent.
14513   if (IsLambda && !Var->getDeclName()) {
14514     if (Diagnose) {
14515       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14516       S.Diag(Var->getLocation(), diag::note_declared_at);
14517     }
14518     return false;
14519   }
14520 
14521   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14522   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14523     if (Diagnose) {
14524       S.Diag(Loc, diag::err_ref_vm_type);
14525       S.Diag(Var->getLocation(), diag::note_previous_decl)
14526         << Var->getDeclName();
14527     }
14528     return false;
14529   }
14530   // Prohibit structs with flexible array members too.
14531   // We cannot capture what is in the tail end of the struct.
14532   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14533     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14534       if (Diagnose) {
14535         if (IsBlock)
14536           S.Diag(Loc, diag::err_ref_flexarray_type);
14537         else
14538           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14539             << Var->getDeclName();
14540         S.Diag(Var->getLocation(), diag::note_previous_decl)
14541           << Var->getDeclName();
14542       }
14543       return false;
14544     }
14545   }
14546   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14547   // Lambdas and captured statements are not allowed to capture __block
14548   // variables; they don't support the expected semantics.
14549   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14550     if (Diagnose) {
14551       S.Diag(Loc, diag::err_capture_block_variable)
14552         << Var->getDeclName() << !IsLambda;
14553       S.Diag(Var->getLocation(), diag::note_previous_decl)
14554         << Var->getDeclName();
14555     }
14556     return false;
14557   }
14558   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14559   if (S.getLangOpts().OpenCL && IsBlock &&
14560       Var->getType()->isBlockPointerType()) {
14561     if (Diagnose)
14562       S.Diag(Loc, diag::err_opencl_block_ref_block);
14563     return false;
14564   }
14565 
14566   return true;
14567 }
14568 
14569 // Returns true if the capture by block was successful.
14570 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14571                                  SourceLocation Loc,
14572                                  const bool BuildAndDiagnose,
14573                                  QualType &CaptureType,
14574                                  QualType &DeclRefType,
14575                                  const bool Nested,
14576                                  Sema &S) {
14577   Expr *CopyExpr = nullptr;
14578   bool ByRef = false;
14579 
14580   // Blocks are not allowed to capture arrays.
14581   if (CaptureType->isArrayType()) {
14582     if (BuildAndDiagnose) {
14583       S.Diag(Loc, diag::err_ref_array_type);
14584       S.Diag(Var->getLocation(), diag::note_previous_decl)
14585       << Var->getDeclName();
14586     }
14587     return false;
14588   }
14589 
14590   // Forbid the block-capture of autoreleasing variables.
14591   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14592     if (BuildAndDiagnose) {
14593       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14594         << /*block*/ 0;
14595       S.Diag(Var->getLocation(), diag::note_previous_decl)
14596         << Var->getDeclName();
14597     }
14598     return false;
14599   }
14600 
14601   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14602   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14603     // This function finds out whether there is an AttributedType of kind
14604     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14605     // attr_objc_ownership implies __autoreleasing was explicitly specified
14606     // rather than being added implicitly by the compiler.
14607     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14608       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14609         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14610           return true;
14611 
14612         // Peel off AttributedTypes that are not of kind objc_ownership.
14613         Ty = AttrTy->getModifiedType();
14614       }
14615 
14616       return false;
14617     };
14618 
14619     QualType PointeeTy = PT->getPointeeType();
14620 
14621     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14622         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14623         !IsObjCOwnershipAttributedType(PointeeTy)) {
14624       if (BuildAndDiagnose) {
14625         SourceLocation VarLoc = Var->getLocation();
14626         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14627         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14628       }
14629     }
14630   }
14631 
14632   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14633   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14634       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14635     // Block capture by reference does not change the capture or
14636     // declaration reference types.
14637     ByRef = true;
14638   } else {
14639     // Block capture by copy introduces 'const'.
14640     CaptureType = CaptureType.getNonReferenceType().withConst();
14641     DeclRefType = CaptureType;
14642 
14643     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14644       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14645         // The capture logic needs the destructor, so make sure we mark it.
14646         // Usually this is unnecessary because most local variables have
14647         // their destructors marked at declaration time, but parameters are
14648         // an exception because it's technically only the call site that
14649         // actually requires the destructor.
14650         if (isa<ParmVarDecl>(Var))
14651           S.FinalizeVarWithDestructor(Var, Record);
14652 
14653         // Enter a new evaluation context to insulate the copy
14654         // full-expression.
14655         EnterExpressionEvaluationContext scope(
14656             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14657 
14658         // According to the blocks spec, the capture of a variable from
14659         // the stack requires a const copy constructor.  This is not true
14660         // of the copy/move done to move a __block variable to the heap.
14661         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14662                                                   DeclRefType.withConst(),
14663                                                   VK_LValue, Loc);
14664 
14665         ExprResult Result
14666           = S.PerformCopyInitialization(
14667               InitializedEntity::InitializeBlock(Var->getLocation(),
14668                                                   CaptureType, false),
14669               Loc, DeclRef);
14670 
14671         // Build a full-expression copy expression if initialization
14672         // succeeded and used a non-trivial constructor.  Recover from
14673         // errors by pretending that the copy isn't necessary.
14674         if (!Result.isInvalid() &&
14675             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14676                 ->isTrivial()) {
14677           Result = S.MaybeCreateExprWithCleanups(Result);
14678           CopyExpr = Result.get();
14679         }
14680       }
14681     }
14682   }
14683 
14684   // Actually capture the variable.
14685   if (BuildAndDiagnose)
14686     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14687                     SourceLocation(), CaptureType, CopyExpr);
14688 
14689   return true;
14690 
14691 }
14692 
14693 
14694 /// Capture the given variable in the captured region.
14695 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14696                                     VarDecl *Var,
14697                                     SourceLocation Loc,
14698                                     const bool BuildAndDiagnose,
14699                                     QualType &CaptureType,
14700                                     QualType &DeclRefType,
14701                                     const bool RefersToCapturedVariable,
14702                                     Sema &S) {
14703   // By default, capture variables by reference.
14704   bool ByRef = true;
14705   // Using an LValue reference type is consistent with Lambdas (see below).
14706   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14707     if (S.isOpenMPCapturedDecl(Var)) {
14708       bool HasConst = DeclRefType.isConstQualified();
14709       DeclRefType = DeclRefType.getUnqualifiedType();
14710       // Don't lose diagnostics about assignments to const.
14711       if (HasConst)
14712         DeclRefType.addConst();
14713     }
14714     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14715   }
14716 
14717   if (ByRef)
14718     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14719   else
14720     CaptureType = DeclRefType;
14721 
14722   Expr *CopyExpr = nullptr;
14723   if (BuildAndDiagnose) {
14724     // The current implementation assumes that all variables are captured
14725     // by references. Since there is no capture by copy, no expression
14726     // evaluation will be needed.
14727     RecordDecl *RD = RSI->TheRecordDecl;
14728 
14729     FieldDecl *Field
14730       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14731                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14732                           nullptr, false, ICIS_NoInit);
14733     Field->setImplicit(true);
14734     Field->setAccess(AS_private);
14735     RD->addDecl(Field);
14736     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14737       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14738 
14739     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14740                                             DeclRefType, VK_LValue, Loc);
14741     Var->setReferenced(true);
14742     Var->markUsed(S.Context);
14743   }
14744 
14745   // Actually capture the variable.
14746   if (BuildAndDiagnose)
14747     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14748                     SourceLocation(), CaptureType, CopyExpr);
14749 
14750 
14751   return true;
14752 }
14753 
14754 /// Create a field within the lambda class for the variable
14755 /// being captured.
14756 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14757                                     QualType FieldType, QualType DeclRefType,
14758                                     SourceLocation Loc,
14759                                     bool RefersToCapturedVariable) {
14760   CXXRecordDecl *Lambda = LSI->Lambda;
14761 
14762   // Build the non-static data member.
14763   FieldDecl *Field
14764     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14765                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14766                         nullptr, false, ICIS_NoInit);
14767   Field->setImplicit(true);
14768   Field->setAccess(AS_private);
14769   Lambda->addDecl(Field);
14770 }
14771 
14772 /// Capture the given variable in the lambda.
14773 static bool captureInLambda(LambdaScopeInfo *LSI,
14774                             VarDecl *Var,
14775                             SourceLocation Loc,
14776                             const bool BuildAndDiagnose,
14777                             QualType &CaptureType,
14778                             QualType &DeclRefType,
14779                             const bool RefersToCapturedVariable,
14780                             const Sema::TryCaptureKind Kind,
14781                             SourceLocation EllipsisLoc,
14782                             const bool IsTopScope,
14783                             Sema &S) {
14784 
14785   // Determine whether we are capturing by reference or by value.
14786   bool ByRef = false;
14787   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14788     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14789   } else {
14790     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14791   }
14792 
14793   // Compute the type of the field that will capture this variable.
14794   if (ByRef) {
14795     // C++11 [expr.prim.lambda]p15:
14796     //   An entity is captured by reference if it is implicitly or
14797     //   explicitly captured but not captured by copy. It is
14798     //   unspecified whether additional unnamed non-static data
14799     //   members are declared in the closure type for entities
14800     //   captured by reference.
14801     //
14802     // FIXME: It is not clear whether we want to build an lvalue reference
14803     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14804     // to do the former, while EDG does the latter. Core issue 1249 will
14805     // clarify, but for now we follow GCC because it's a more permissive and
14806     // easily defensible position.
14807     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14808   } else {
14809     // C++11 [expr.prim.lambda]p14:
14810     //   For each entity captured by copy, an unnamed non-static
14811     //   data member is declared in the closure type. The
14812     //   declaration order of these members is unspecified. The type
14813     //   of such a data member is the type of the corresponding
14814     //   captured entity if the entity is not a reference to an
14815     //   object, or the referenced type otherwise. [Note: If the
14816     //   captured entity is a reference to a function, the
14817     //   corresponding data member is also a reference to a
14818     //   function. - end note ]
14819     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14820       if (!RefType->getPointeeType()->isFunctionType())
14821         CaptureType = RefType->getPointeeType();
14822     }
14823 
14824     // Forbid the lambda copy-capture of autoreleasing variables.
14825     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14826       if (BuildAndDiagnose) {
14827         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14828         S.Diag(Var->getLocation(), diag::note_previous_decl)
14829           << Var->getDeclName();
14830       }
14831       return false;
14832     }
14833 
14834     // Make sure that by-copy captures are of a complete and non-abstract type.
14835     if (BuildAndDiagnose) {
14836       if (!CaptureType->isDependentType() &&
14837           S.RequireCompleteType(Loc, CaptureType,
14838                                 diag::err_capture_of_incomplete_type,
14839                                 Var->getDeclName()))
14840         return false;
14841 
14842       if (S.RequireNonAbstractType(Loc, CaptureType,
14843                                    diag::err_capture_of_abstract_type))
14844         return false;
14845     }
14846   }
14847 
14848   // Capture this variable in the lambda.
14849   if (BuildAndDiagnose)
14850     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14851                             RefersToCapturedVariable);
14852 
14853   // Compute the type of a reference to this captured variable.
14854   if (ByRef)
14855     DeclRefType = CaptureType.getNonReferenceType();
14856   else {
14857     // C++ [expr.prim.lambda]p5:
14858     //   The closure type for a lambda-expression has a public inline
14859     //   function call operator [...]. This function call operator is
14860     //   declared const (9.3.1) if and only if the lambda-expression's
14861     //   parameter-declaration-clause is not followed by mutable.
14862     DeclRefType = CaptureType.getNonReferenceType();
14863     if (!LSI->Mutable && !CaptureType->isReferenceType())
14864       DeclRefType.addConst();
14865   }
14866 
14867   // Add the capture.
14868   if (BuildAndDiagnose)
14869     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14870                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14871 
14872   return true;
14873 }
14874 
14875 bool Sema::tryCaptureVariable(
14876     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14877     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14878     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14879   // An init-capture is notionally from the context surrounding its
14880   // declaration, but its parent DC is the lambda class.
14881   DeclContext *VarDC = Var->getDeclContext();
14882   if (Var->isInitCapture())
14883     VarDC = VarDC->getParent();
14884 
14885   DeclContext *DC = CurContext;
14886   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14887       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14888   // We need to sync up the Declaration Context with the
14889   // FunctionScopeIndexToStopAt
14890   if (FunctionScopeIndexToStopAt) {
14891     unsigned FSIndex = FunctionScopes.size() - 1;
14892     while (FSIndex != MaxFunctionScopesIndex) {
14893       DC = getLambdaAwareParentOfDeclContext(DC);
14894       --FSIndex;
14895     }
14896   }
14897 
14898 
14899   // If the variable is declared in the current context, there is no need to
14900   // capture it.
14901   if (VarDC == DC) return true;
14902 
14903   // Capture global variables if it is required to use private copy of this
14904   // variable.
14905   bool IsGlobal = !Var->hasLocalStorage();
14906   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14907     return true;
14908   Var = Var->getCanonicalDecl();
14909 
14910   // Walk up the stack to determine whether we can capture the variable,
14911   // performing the "simple" checks that don't depend on type. We stop when
14912   // we've either hit the declared scope of the variable or find an existing
14913   // capture of that variable.  We start from the innermost capturing-entity
14914   // (the DC) and ensure that all intervening capturing-entities
14915   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14916   // declcontext can either capture the variable or have already captured
14917   // the variable.
14918   CaptureType = Var->getType();
14919   DeclRefType = CaptureType.getNonReferenceType();
14920   bool Nested = false;
14921   bool Explicit = (Kind != TryCapture_Implicit);
14922   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14923   do {
14924     // Only block literals, captured statements, and lambda expressions can
14925     // capture; other scopes don't work.
14926     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14927                                                               ExprLoc,
14928                                                               BuildAndDiagnose,
14929                                                               *this);
14930     // We need to check for the parent *first* because, if we *have*
14931     // private-captured a global variable, we need to recursively capture it in
14932     // intermediate blocks, lambdas, etc.
14933     if (!ParentDC) {
14934       if (IsGlobal) {
14935         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14936         break;
14937       }
14938       return true;
14939     }
14940 
14941     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14942     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14943 
14944 
14945     // Check whether we've already captured it.
14946     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14947                                              DeclRefType)) {
14948       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14949       break;
14950     }
14951     // If we are instantiating a generic lambda call operator body,
14952     // we do not want to capture new variables.  What was captured
14953     // during either a lambdas transformation or initial parsing
14954     // should be used.
14955     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14956       if (BuildAndDiagnose) {
14957         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14958         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14959           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14960           Diag(Var->getLocation(), diag::note_previous_decl)
14961              << Var->getDeclName();
14962           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14963         } else
14964           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14965       }
14966       return true;
14967     }
14968     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14969     // certain types of variables (unnamed, variably modified types etc.)
14970     // so check for eligibility.
14971     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14972        return true;
14973 
14974     // Try to capture variable-length arrays types.
14975     if (Var->getType()->isVariablyModifiedType()) {
14976       // We're going to walk down into the type and look for VLA
14977       // expressions.
14978       QualType QTy = Var->getType();
14979       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14980         QTy = PVD->getOriginalType();
14981       captureVariablyModifiedType(Context, QTy, CSI);
14982     }
14983 
14984     if (getLangOpts().OpenMP) {
14985       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14986         // OpenMP private variables should not be captured in outer scope, so
14987         // just break here. Similarly, global variables that are captured in a
14988         // target region should not be captured outside the scope of the region.
14989         if (RSI->CapRegionKind == CR_OpenMP) {
14990           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
14991           auto IsTargetCap = !IsOpenMPPrivateDecl &&
14992                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14993           // When we detect target captures we are looking from inside the
14994           // target region, therefore we need to propagate the capture from the
14995           // enclosing region. Therefore, the capture is not initially nested.
14996           if (IsTargetCap)
14997             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
14998 
14999           if (IsTargetCap || IsOpenMPPrivateDecl) {
15000             Nested = !IsTargetCap;
15001             DeclRefType = DeclRefType.getUnqualifiedType();
15002             CaptureType = Context.getLValueReferenceType(DeclRefType);
15003             break;
15004           }
15005         }
15006       }
15007     }
15008     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15009       // No capture-default, and this is not an explicit capture
15010       // so cannot capture this variable.
15011       if (BuildAndDiagnose) {
15012         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15013         Diag(Var->getLocation(), diag::note_previous_decl)
15014           << Var->getDeclName();
15015         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15016           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
15017                diag::note_lambda_decl);
15018         // FIXME: If we error out because an outer lambda can not implicitly
15019         // capture a variable that an inner lambda explicitly captures, we
15020         // should have the inner lambda do the explicit capture - because
15021         // it makes for cleaner diagnostics later.  This would purely be done
15022         // so that the diagnostic does not misleadingly claim that a variable
15023         // can not be captured by a lambda implicitly even though it is captured
15024         // explicitly.  Suggestion:
15025         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15026         //    at the function head
15027         //  - cache the StartingDeclContext - this must be a lambda
15028         //  - captureInLambda in the innermost lambda the variable.
15029       }
15030       return true;
15031     }
15032 
15033     FunctionScopesIndex--;
15034     DC = ParentDC;
15035     Explicit = false;
15036   } while (!VarDC->Equals(DC));
15037 
15038   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15039   // computing the type of the capture at each step, checking type-specific
15040   // requirements, and adding captures if requested.
15041   // If the variable had already been captured previously, we start capturing
15042   // at the lambda nested within that one.
15043   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15044        ++I) {
15045     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15046 
15047     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15048       if (!captureInBlock(BSI, Var, ExprLoc,
15049                           BuildAndDiagnose, CaptureType,
15050                           DeclRefType, Nested, *this))
15051         return true;
15052       Nested = true;
15053     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15054       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15055                                    BuildAndDiagnose, CaptureType,
15056                                    DeclRefType, Nested, *this))
15057         return true;
15058       Nested = true;
15059     } else {
15060       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15061       if (!captureInLambda(LSI, Var, ExprLoc,
15062                            BuildAndDiagnose, CaptureType,
15063                            DeclRefType, Nested, Kind, EllipsisLoc,
15064                             /*IsTopScope*/I == N - 1, *this))
15065         return true;
15066       Nested = true;
15067     }
15068   }
15069   return false;
15070 }
15071 
15072 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15073                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15074   QualType CaptureType;
15075   QualType DeclRefType;
15076   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15077                             /*BuildAndDiagnose=*/true, CaptureType,
15078                             DeclRefType, nullptr);
15079 }
15080 
15081 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15082   QualType CaptureType;
15083   QualType DeclRefType;
15084   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15085                              /*BuildAndDiagnose=*/false, CaptureType,
15086                              DeclRefType, nullptr);
15087 }
15088 
15089 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15090   QualType CaptureType;
15091   QualType DeclRefType;
15092 
15093   // Determine whether we can capture this variable.
15094   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15095                          /*BuildAndDiagnose=*/false, CaptureType,
15096                          DeclRefType, nullptr))
15097     return QualType();
15098 
15099   return DeclRefType;
15100 }
15101 
15102 
15103 
15104 // If either the type of the variable or the initializer is dependent,
15105 // return false. Otherwise, determine whether the variable is a constant
15106 // expression. Use this if you need to know if a variable that might or
15107 // might not be dependent is truly a constant expression.
15108 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15109     ASTContext &Context) {
15110 
15111   if (Var->getType()->isDependentType())
15112     return false;
15113   const VarDecl *DefVD = nullptr;
15114   Var->getAnyInitializer(DefVD);
15115   if (!DefVD)
15116     return false;
15117   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15118   Expr *Init = cast<Expr>(Eval->Value);
15119   if (Init->isValueDependent())
15120     return false;
15121   return IsVariableAConstantExpression(Var, Context);
15122 }
15123 
15124 
15125 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15126   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15127   // an object that satisfies the requirements for appearing in a
15128   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15129   // is immediately applied."  This function handles the lvalue-to-rvalue
15130   // conversion part.
15131   MaybeODRUseExprs.erase(E->IgnoreParens());
15132 
15133   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15134   // to a variable that is a constant expression, and if so, identify it as
15135   // a reference to a variable that does not involve an odr-use of that
15136   // variable.
15137   if (LambdaScopeInfo *LSI = getCurLambda()) {
15138     Expr *SansParensExpr = E->IgnoreParens();
15139     VarDecl *Var = nullptr;
15140     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15141       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15142     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15143       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15144 
15145     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15146       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15147   }
15148 }
15149 
15150 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15151   Res = CorrectDelayedTyposInExpr(Res);
15152 
15153   if (!Res.isUsable())
15154     return Res;
15155 
15156   // If a constant-expression is a reference to a variable where we delay
15157   // deciding whether it is an odr-use, just assume we will apply the
15158   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15159   // (a non-type template argument), we have special handling anyway.
15160   UpdateMarkingForLValueToRValue(Res.get());
15161   return Res;
15162 }
15163 
15164 void Sema::CleanupVarDeclMarking() {
15165   for (Expr *E : MaybeODRUseExprs) {
15166     VarDecl *Var;
15167     SourceLocation Loc;
15168     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15169       Var = cast<VarDecl>(DRE->getDecl());
15170       Loc = DRE->getLocation();
15171     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15172       Var = cast<VarDecl>(ME->getMemberDecl());
15173       Loc = ME->getMemberLoc();
15174     } else {
15175       llvm_unreachable("Unexpected expression");
15176     }
15177 
15178     MarkVarDeclODRUsed(Var, Loc, *this,
15179                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15180   }
15181 
15182   MaybeODRUseExprs.clear();
15183 }
15184 
15185 
15186 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15187                                     VarDecl *Var, Expr *E) {
15188   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15189          "Invalid Expr argument to DoMarkVarDeclReferenced");
15190   Var->setReferenced();
15191 
15192   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15193 
15194   bool OdrUseContext = isOdrUseContext(SemaRef);
15195   bool UsableInConstantExpr =
15196       Var->isUsableInConstantExpressions(SemaRef.Context);
15197   bool NeedDefinition =
15198       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15199 
15200   VarTemplateSpecializationDecl *VarSpec =
15201       dyn_cast<VarTemplateSpecializationDecl>(Var);
15202   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15203          "Can't instantiate a partial template specialization.");
15204 
15205   // If this might be a member specialization of a static data member, check
15206   // the specialization is visible. We already did the checks for variable
15207   // template specializations when we created them.
15208   if (NeedDefinition && TSK != TSK_Undeclared &&
15209       !isa<VarTemplateSpecializationDecl>(Var))
15210     SemaRef.checkSpecializationVisibility(Loc, Var);
15211 
15212   // Perform implicit instantiation of static data members, static data member
15213   // templates of class templates, and variable template specializations. Delay
15214   // instantiations of variable templates, except for those that could be used
15215   // in a constant expression.
15216   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15217     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15218     // instantiation declaration if a variable is usable in a constant
15219     // expression (among other cases).
15220     bool TryInstantiating =
15221         TSK == TSK_ImplicitInstantiation ||
15222         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15223 
15224     if (TryInstantiating) {
15225       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15226       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15227       if (FirstInstantiation) {
15228         PointOfInstantiation = Loc;
15229         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15230       }
15231 
15232       bool InstantiationDependent = false;
15233       bool IsNonDependent =
15234           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15235                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15236                   : true;
15237 
15238       // Do not instantiate specializations that are still type-dependent.
15239       if (IsNonDependent) {
15240         if (UsableInConstantExpr) {
15241           // Do not defer instantiations of variables that could be used in a
15242           // constant expression.
15243           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15244         } else if (FirstInstantiation ||
15245                    isa<VarTemplateSpecializationDecl>(Var)) {
15246           // FIXME: For a specialization of a variable template, we don't
15247           // distinguish between "declaration and type implicitly instantiated"
15248           // and "implicit instantiation of definition requested", so we have
15249           // no direct way to avoid enqueueing the pending instantiation
15250           // multiple times.
15251           SemaRef.PendingInstantiations
15252               .push_back(std::make_pair(Var, PointOfInstantiation));
15253         }
15254       }
15255     }
15256   }
15257 
15258   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15259   // the requirements for appearing in a constant expression (5.19) and, if
15260   // it is an object, the lvalue-to-rvalue conversion (4.1)
15261   // is immediately applied."  We check the first part here, and
15262   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15263   // Note that we use the C++11 definition everywhere because nothing in
15264   // C++03 depends on whether we get the C++03 version correct. The second
15265   // part does not apply to references, since they are not objects.
15266   if (OdrUseContext && E &&
15267       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15268     // A reference initialized by a constant expression can never be
15269     // odr-used, so simply ignore it.
15270     if (!Var->getType()->isReferenceType() ||
15271         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15272       SemaRef.MaybeODRUseExprs.insert(E);
15273   } else if (OdrUseContext) {
15274     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15275                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15276   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15277     // If this is a dependent context, we don't need to mark variables as
15278     // odr-used, but we may still need to track them for lambda capture.
15279     // FIXME: Do we also need to do this inside dependent typeid expressions
15280     // (which are modeled as unevaluated at this point)?
15281     const bool RefersToEnclosingScope =
15282         (SemaRef.CurContext != Var->getDeclContext() &&
15283          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15284     if (RefersToEnclosingScope) {
15285       LambdaScopeInfo *const LSI =
15286           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15287       if (LSI && (!LSI->CallOperator ||
15288                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15289         // If a variable could potentially be odr-used, defer marking it so
15290         // until we finish analyzing the full expression for any
15291         // lvalue-to-rvalue
15292         // or discarded value conversions that would obviate odr-use.
15293         // Add it to the list of potential captures that will be analyzed
15294         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15295         // unless the variable is a reference that was initialized by a constant
15296         // expression (this will never need to be captured or odr-used).
15297         assert(E && "Capture variable should be used in an expression.");
15298         if (!Var->getType()->isReferenceType() ||
15299             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15300           LSI->addPotentialCapture(E->IgnoreParens());
15301       }
15302     }
15303   }
15304 }
15305 
15306 /// Mark a variable referenced, and check whether it is odr-used
15307 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15308 /// used directly for normal expressions referring to VarDecl.
15309 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15310   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15311 }
15312 
15313 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15314                                Decl *D, Expr *E, bool MightBeOdrUse) {
15315   if (SemaRef.isInOpenMPDeclareTargetContext())
15316     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15317 
15318   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15319     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15320     return;
15321   }
15322 
15323   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15324 
15325   // If this is a call to a method via a cast, also mark the method in the
15326   // derived class used in case codegen can devirtualize the call.
15327   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15328   if (!ME)
15329     return;
15330   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15331   if (!MD)
15332     return;
15333   // Only attempt to devirtualize if this is truly a virtual call.
15334   bool IsVirtualCall = MD->isVirtual() &&
15335                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15336   if (!IsVirtualCall)
15337     return;
15338 
15339   // If it's possible to devirtualize the call, mark the called function
15340   // referenced.
15341   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15342       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15343   if (DM)
15344     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15345 }
15346 
15347 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15348 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15349   // TODO: update this with DR# once a defect report is filed.
15350   // C++11 defect. The address of a pure member should not be an ODR use, even
15351   // if it's a qualified reference.
15352   bool OdrUse = true;
15353   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15354     if (Method->isVirtual() &&
15355         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15356       OdrUse = false;
15357   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15358 }
15359 
15360 /// Perform reference-marking and odr-use handling for a MemberExpr.
15361 void Sema::MarkMemberReferenced(MemberExpr *E) {
15362   // C++11 [basic.def.odr]p2:
15363   //   A non-overloaded function whose name appears as a potentially-evaluated
15364   //   expression or a member of a set of candidate functions, if selected by
15365   //   overload resolution when referred to from a potentially-evaluated
15366   //   expression, is odr-used, unless it is a pure virtual function and its
15367   //   name is not explicitly qualified.
15368   bool MightBeOdrUse = true;
15369   if (E->performsVirtualDispatch(getLangOpts())) {
15370     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15371       if (Method->isPure())
15372         MightBeOdrUse = false;
15373   }
15374   SourceLocation Loc = E->getMemberLoc().isValid() ?
15375                             E->getMemberLoc() : E->getLocStart();
15376   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15377 }
15378 
15379 /// Perform marking for a reference to an arbitrary declaration.  It
15380 /// marks the declaration referenced, and performs odr-use checking for
15381 /// functions and variables. This method should not be used when building a
15382 /// normal expression which refers to a variable.
15383 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15384                                  bool MightBeOdrUse) {
15385   if (MightBeOdrUse) {
15386     if (auto *VD = dyn_cast<VarDecl>(D)) {
15387       MarkVariableReferenced(Loc, VD);
15388       return;
15389     }
15390   }
15391   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15392     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15393     return;
15394   }
15395   D->setReferenced();
15396 }
15397 
15398 namespace {
15399   // Mark all of the declarations used by a type as referenced.
15400   // FIXME: Not fully implemented yet! We need to have a better understanding
15401   // of when we're entering a context we should not recurse into.
15402   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15403   // TreeTransforms rebuilding the type in a new context. Rather than
15404   // duplicating the TreeTransform logic, we should consider reusing it here.
15405   // Currently that causes problems when rebuilding LambdaExprs.
15406   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15407     Sema &S;
15408     SourceLocation Loc;
15409 
15410   public:
15411     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15412 
15413     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15414 
15415     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15416   };
15417 }
15418 
15419 bool MarkReferencedDecls::TraverseTemplateArgument(
15420     const TemplateArgument &Arg) {
15421   {
15422     // A non-type template argument is a constant-evaluated context.
15423     EnterExpressionEvaluationContext Evaluated(
15424         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15425     if (Arg.getKind() == TemplateArgument::Declaration) {
15426       if (Decl *D = Arg.getAsDecl())
15427         S.MarkAnyDeclReferenced(Loc, D, true);
15428     } else if (Arg.getKind() == TemplateArgument::Expression) {
15429       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15430     }
15431   }
15432 
15433   return Inherited::TraverseTemplateArgument(Arg);
15434 }
15435 
15436 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15437   MarkReferencedDecls Marker(*this, Loc);
15438   Marker.TraverseType(T);
15439 }
15440 
15441 namespace {
15442   /// Helper class that marks all of the declarations referenced by
15443   /// potentially-evaluated subexpressions as "referenced".
15444   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15445     Sema &S;
15446     bool SkipLocalVariables;
15447 
15448   public:
15449     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15450 
15451     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15452       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15453 
15454     void VisitDeclRefExpr(DeclRefExpr *E) {
15455       // If we were asked not to visit local variables, don't.
15456       if (SkipLocalVariables) {
15457         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15458           if (VD->hasLocalStorage())
15459             return;
15460       }
15461 
15462       S.MarkDeclRefReferenced(E);
15463     }
15464 
15465     void VisitMemberExpr(MemberExpr *E) {
15466       S.MarkMemberReferenced(E);
15467       Inherited::VisitMemberExpr(E);
15468     }
15469 
15470     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15471       S.MarkFunctionReferenced(E->getLocStart(),
15472             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15473       Visit(E->getSubExpr());
15474     }
15475 
15476     void VisitCXXNewExpr(CXXNewExpr *E) {
15477       if (E->getOperatorNew())
15478         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15479       if (E->getOperatorDelete())
15480         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15481       Inherited::VisitCXXNewExpr(E);
15482     }
15483 
15484     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15485       if (E->getOperatorDelete())
15486         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15487       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15488       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15489         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15490         S.MarkFunctionReferenced(E->getLocStart(),
15491                                     S.LookupDestructor(Record));
15492       }
15493 
15494       Inherited::VisitCXXDeleteExpr(E);
15495     }
15496 
15497     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15498       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15499       Inherited::VisitCXXConstructExpr(E);
15500     }
15501 
15502     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15503       Visit(E->getExpr());
15504     }
15505 
15506     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15507       Inherited::VisitImplicitCastExpr(E);
15508 
15509       if (E->getCastKind() == CK_LValueToRValue)
15510         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15511     }
15512   };
15513 }
15514 
15515 /// Mark any declarations that appear within this expression or any
15516 /// potentially-evaluated subexpressions as "referenced".
15517 ///
15518 /// \param SkipLocalVariables If true, don't mark local variables as
15519 /// 'referenced'.
15520 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15521                                             bool SkipLocalVariables) {
15522   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15523 }
15524 
15525 /// Emit a diagnostic that describes an effect on the run-time behavior
15526 /// of the program being compiled.
15527 ///
15528 /// This routine emits the given diagnostic when the code currently being
15529 /// type-checked is "potentially evaluated", meaning that there is a
15530 /// possibility that the code will actually be executable. Code in sizeof()
15531 /// expressions, code used only during overload resolution, etc., are not
15532 /// potentially evaluated. This routine will suppress such diagnostics or,
15533 /// in the absolutely nutty case of potentially potentially evaluated
15534 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15535 /// later.
15536 ///
15537 /// This routine should be used for all diagnostics that describe the run-time
15538 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15539 /// Failure to do so will likely result in spurious diagnostics or failures
15540 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15541 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15542                                const PartialDiagnostic &PD) {
15543   switch (ExprEvalContexts.back().Context) {
15544   case ExpressionEvaluationContext::Unevaluated:
15545   case ExpressionEvaluationContext::UnevaluatedList:
15546   case ExpressionEvaluationContext::UnevaluatedAbstract:
15547   case ExpressionEvaluationContext::DiscardedStatement:
15548     // The argument will never be evaluated, so don't complain.
15549     break;
15550 
15551   case ExpressionEvaluationContext::ConstantEvaluated:
15552     // Relevant diagnostics should be produced by constant evaluation.
15553     break;
15554 
15555   case ExpressionEvaluationContext::PotentiallyEvaluated:
15556   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15557     if (Statement && getCurFunctionOrMethodDecl()) {
15558       FunctionScopes.back()->PossiblyUnreachableDiags.
15559         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15560       return true;
15561     }
15562 
15563     // The initializer of a constexpr variable or of the first declaration of a
15564     // static data member is not syntactically a constant evaluated constant,
15565     // but nonetheless is always required to be a constant expression, so we
15566     // can skip diagnosing.
15567     // FIXME: Using the mangling context here is a hack.
15568     if (auto *VD = dyn_cast_or_null<VarDecl>(
15569             ExprEvalContexts.back().ManglingContextDecl)) {
15570       if (VD->isConstexpr() ||
15571           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15572         break;
15573       // FIXME: For any other kind of variable, we should build a CFG for its
15574       // initializer and check whether the context in question is reachable.
15575     }
15576 
15577     Diag(Loc, PD);
15578     return true;
15579   }
15580 
15581   return false;
15582 }
15583 
15584 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15585                                CallExpr *CE, FunctionDecl *FD) {
15586   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15587     return false;
15588 
15589   // If we're inside a decltype's expression, don't check for a valid return
15590   // type or construct temporaries until we know whether this is the last call.
15591   if (ExprEvalContexts.back().IsDecltype) {
15592     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15593     return false;
15594   }
15595 
15596   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15597     FunctionDecl *FD;
15598     CallExpr *CE;
15599 
15600   public:
15601     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15602       : FD(FD), CE(CE) { }
15603 
15604     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15605       if (!FD) {
15606         S.Diag(Loc, diag::err_call_incomplete_return)
15607           << T << CE->getSourceRange();
15608         return;
15609       }
15610 
15611       S.Diag(Loc, diag::err_call_function_incomplete_return)
15612         << CE->getSourceRange() << FD->getDeclName() << T;
15613       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15614           << FD->getDeclName();
15615     }
15616   } Diagnoser(FD, CE);
15617 
15618   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15619     return true;
15620 
15621   return false;
15622 }
15623 
15624 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15625 // will prevent this condition from triggering, which is what we want.
15626 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15627   SourceLocation Loc;
15628 
15629   unsigned diagnostic = diag::warn_condition_is_assignment;
15630   bool IsOrAssign = false;
15631 
15632   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15633     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15634       return;
15635 
15636     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15637 
15638     // Greylist some idioms by putting them into a warning subcategory.
15639     if (ObjCMessageExpr *ME
15640           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15641       Selector Sel = ME->getSelector();
15642 
15643       // self = [<foo> init...]
15644       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15645         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15646 
15647       // <foo> = [<bar> nextObject]
15648       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15649         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15650     }
15651 
15652     Loc = Op->getOperatorLoc();
15653   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15654     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15655       return;
15656 
15657     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15658     Loc = Op->getOperatorLoc();
15659   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15660     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15661   else {
15662     // Not an assignment.
15663     return;
15664   }
15665 
15666   Diag(Loc, diagnostic) << E->getSourceRange();
15667 
15668   SourceLocation Open = E->getLocStart();
15669   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15670   Diag(Loc, diag::note_condition_assign_silence)
15671         << FixItHint::CreateInsertion(Open, "(")
15672         << FixItHint::CreateInsertion(Close, ")");
15673 
15674   if (IsOrAssign)
15675     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15676       << FixItHint::CreateReplacement(Loc, "!=");
15677   else
15678     Diag(Loc, diag::note_condition_assign_to_comparison)
15679       << FixItHint::CreateReplacement(Loc, "==");
15680 }
15681 
15682 /// Redundant parentheses over an equality comparison can indicate
15683 /// that the user intended an assignment used as condition.
15684 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15685   // Don't warn if the parens came from a macro.
15686   SourceLocation parenLoc = ParenE->getLocStart();
15687   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15688     return;
15689   // Don't warn for dependent expressions.
15690   if (ParenE->isTypeDependent())
15691     return;
15692 
15693   Expr *E = ParenE->IgnoreParens();
15694 
15695   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15696     if (opE->getOpcode() == BO_EQ &&
15697         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15698                                                            == Expr::MLV_Valid) {
15699       SourceLocation Loc = opE->getOperatorLoc();
15700 
15701       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15702       SourceRange ParenERange = ParenE->getSourceRange();
15703       Diag(Loc, diag::note_equality_comparison_silence)
15704         << FixItHint::CreateRemoval(ParenERange.getBegin())
15705         << FixItHint::CreateRemoval(ParenERange.getEnd());
15706       Diag(Loc, diag::note_equality_comparison_to_assign)
15707         << FixItHint::CreateReplacement(Loc, "=");
15708     }
15709 }
15710 
15711 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15712                                        bool IsConstexpr) {
15713   DiagnoseAssignmentAsCondition(E);
15714   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15715     DiagnoseEqualityWithExtraParens(parenE);
15716 
15717   ExprResult result = CheckPlaceholderExpr(E);
15718   if (result.isInvalid()) return ExprError();
15719   E = result.get();
15720 
15721   if (!E->isTypeDependent()) {
15722     if (getLangOpts().CPlusPlus)
15723       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15724 
15725     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15726     if (ERes.isInvalid())
15727       return ExprError();
15728     E = ERes.get();
15729 
15730     QualType T = E->getType();
15731     if (!T->isScalarType()) { // C99 6.8.4.1p1
15732       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15733         << T << E->getSourceRange();
15734       return ExprError();
15735     }
15736     CheckBoolLikeConversion(E, Loc);
15737   }
15738 
15739   return E;
15740 }
15741 
15742 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15743                                            Expr *SubExpr, ConditionKind CK) {
15744   // Empty conditions are valid in for-statements.
15745   if (!SubExpr)
15746     return ConditionResult();
15747 
15748   ExprResult Cond;
15749   switch (CK) {
15750   case ConditionKind::Boolean:
15751     Cond = CheckBooleanCondition(Loc, SubExpr);
15752     break;
15753 
15754   case ConditionKind::ConstexprIf:
15755     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15756     break;
15757 
15758   case ConditionKind::Switch:
15759     Cond = CheckSwitchCondition(Loc, SubExpr);
15760     break;
15761   }
15762   if (Cond.isInvalid())
15763     return ConditionError();
15764 
15765   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15766   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15767   if (!FullExpr.get())
15768     return ConditionError();
15769 
15770   return ConditionResult(*this, nullptr, FullExpr,
15771                          CK == ConditionKind::ConstexprIf);
15772 }
15773 
15774 namespace {
15775   /// A visitor for rebuilding a call to an __unknown_any expression
15776   /// to have an appropriate type.
15777   struct RebuildUnknownAnyFunction
15778     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15779 
15780     Sema &S;
15781 
15782     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15783 
15784     ExprResult VisitStmt(Stmt *S) {
15785       llvm_unreachable("unexpected statement!");
15786     }
15787 
15788     ExprResult VisitExpr(Expr *E) {
15789       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15790         << E->getSourceRange();
15791       return ExprError();
15792     }
15793 
15794     /// Rebuild an expression which simply semantically wraps another
15795     /// expression which it shares the type and value kind of.
15796     template <class T> ExprResult rebuildSugarExpr(T *E) {
15797       ExprResult SubResult = Visit(E->getSubExpr());
15798       if (SubResult.isInvalid()) return ExprError();
15799 
15800       Expr *SubExpr = SubResult.get();
15801       E->setSubExpr(SubExpr);
15802       E->setType(SubExpr->getType());
15803       E->setValueKind(SubExpr->getValueKind());
15804       assert(E->getObjectKind() == OK_Ordinary);
15805       return E;
15806     }
15807 
15808     ExprResult VisitParenExpr(ParenExpr *E) {
15809       return rebuildSugarExpr(E);
15810     }
15811 
15812     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15813       return rebuildSugarExpr(E);
15814     }
15815 
15816     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15817       ExprResult SubResult = Visit(E->getSubExpr());
15818       if (SubResult.isInvalid()) return ExprError();
15819 
15820       Expr *SubExpr = SubResult.get();
15821       E->setSubExpr(SubExpr);
15822       E->setType(S.Context.getPointerType(SubExpr->getType()));
15823       assert(E->getValueKind() == VK_RValue);
15824       assert(E->getObjectKind() == OK_Ordinary);
15825       return E;
15826     }
15827 
15828     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15829       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15830 
15831       E->setType(VD->getType());
15832 
15833       assert(E->getValueKind() == VK_RValue);
15834       if (S.getLangOpts().CPlusPlus &&
15835           !(isa<CXXMethodDecl>(VD) &&
15836             cast<CXXMethodDecl>(VD)->isInstance()))
15837         E->setValueKind(VK_LValue);
15838 
15839       return E;
15840     }
15841 
15842     ExprResult VisitMemberExpr(MemberExpr *E) {
15843       return resolveDecl(E, E->getMemberDecl());
15844     }
15845 
15846     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15847       return resolveDecl(E, E->getDecl());
15848     }
15849   };
15850 }
15851 
15852 /// Given a function expression of unknown-any type, try to rebuild it
15853 /// to have a function type.
15854 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15855   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15856   if (Result.isInvalid()) return ExprError();
15857   return S.DefaultFunctionArrayConversion(Result.get());
15858 }
15859 
15860 namespace {
15861   /// A visitor for rebuilding an expression of type __unknown_anytype
15862   /// into one which resolves the type directly on the referring
15863   /// expression.  Strict preservation of the original source
15864   /// structure is not a goal.
15865   struct RebuildUnknownAnyExpr
15866     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15867 
15868     Sema &S;
15869 
15870     /// The current destination type.
15871     QualType DestType;
15872 
15873     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15874       : S(S), DestType(CastType) {}
15875 
15876     ExprResult VisitStmt(Stmt *S) {
15877       llvm_unreachable("unexpected statement!");
15878     }
15879 
15880     ExprResult VisitExpr(Expr *E) {
15881       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15882         << E->getSourceRange();
15883       return ExprError();
15884     }
15885 
15886     ExprResult VisitCallExpr(CallExpr *E);
15887     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15888 
15889     /// Rebuild an expression which simply semantically wraps another
15890     /// expression which it shares the type and value kind of.
15891     template <class T> ExprResult rebuildSugarExpr(T *E) {
15892       ExprResult SubResult = Visit(E->getSubExpr());
15893       if (SubResult.isInvalid()) return ExprError();
15894       Expr *SubExpr = SubResult.get();
15895       E->setSubExpr(SubExpr);
15896       E->setType(SubExpr->getType());
15897       E->setValueKind(SubExpr->getValueKind());
15898       assert(E->getObjectKind() == OK_Ordinary);
15899       return E;
15900     }
15901 
15902     ExprResult VisitParenExpr(ParenExpr *E) {
15903       return rebuildSugarExpr(E);
15904     }
15905 
15906     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15907       return rebuildSugarExpr(E);
15908     }
15909 
15910     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15911       const PointerType *Ptr = DestType->getAs<PointerType>();
15912       if (!Ptr) {
15913         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15914           << E->getSourceRange();
15915         return ExprError();
15916       }
15917 
15918       if (isa<CallExpr>(E->getSubExpr())) {
15919         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15920           << E->getSourceRange();
15921         return ExprError();
15922       }
15923 
15924       assert(E->getValueKind() == VK_RValue);
15925       assert(E->getObjectKind() == OK_Ordinary);
15926       E->setType(DestType);
15927 
15928       // Build the sub-expression as if it were an object of the pointee type.
15929       DestType = Ptr->getPointeeType();
15930       ExprResult SubResult = Visit(E->getSubExpr());
15931       if (SubResult.isInvalid()) return ExprError();
15932       E->setSubExpr(SubResult.get());
15933       return E;
15934     }
15935 
15936     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15937 
15938     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15939 
15940     ExprResult VisitMemberExpr(MemberExpr *E) {
15941       return resolveDecl(E, E->getMemberDecl());
15942     }
15943 
15944     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15945       return resolveDecl(E, E->getDecl());
15946     }
15947   };
15948 }
15949 
15950 /// Rebuilds a call expression which yielded __unknown_anytype.
15951 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15952   Expr *CalleeExpr = E->getCallee();
15953 
15954   enum FnKind {
15955     FK_MemberFunction,
15956     FK_FunctionPointer,
15957     FK_BlockPointer
15958   };
15959 
15960   FnKind Kind;
15961   QualType CalleeType = CalleeExpr->getType();
15962   if (CalleeType == S.Context.BoundMemberTy) {
15963     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15964     Kind = FK_MemberFunction;
15965     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15966   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15967     CalleeType = Ptr->getPointeeType();
15968     Kind = FK_FunctionPointer;
15969   } else {
15970     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15971     Kind = FK_BlockPointer;
15972   }
15973   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15974 
15975   // Verify that this is a legal result type of a function.
15976   if (DestType->isArrayType() || DestType->isFunctionType()) {
15977     unsigned diagID = diag::err_func_returning_array_function;
15978     if (Kind == FK_BlockPointer)
15979       diagID = diag::err_block_returning_array_function;
15980 
15981     S.Diag(E->getExprLoc(), diagID)
15982       << DestType->isFunctionType() << DestType;
15983     return ExprError();
15984   }
15985 
15986   // Otherwise, go ahead and set DestType as the call's result.
15987   E->setType(DestType.getNonLValueExprType(S.Context));
15988   E->setValueKind(Expr::getValueKindForType(DestType));
15989   assert(E->getObjectKind() == OK_Ordinary);
15990 
15991   // Rebuild the function type, replacing the result type with DestType.
15992   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15993   if (Proto) {
15994     // __unknown_anytype(...) is a special case used by the debugger when
15995     // it has no idea what a function's signature is.
15996     //
15997     // We want to build this call essentially under the K&R
15998     // unprototyped rules, but making a FunctionNoProtoType in C++
15999     // would foul up all sorts of assumptions.  However, we cannot
16000     // simply pass all arguments as variadic arguments, nor can we
16001     // portably just call the function under a non-variadic type; see
16002     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16003     // However, it turns out that in practice it is generally safe to
16004     // call a function declared as "A foo(B,C,D);" under the prototype
16005     // "A foo(B,C,D,...);".  The only known exception is with the
16006     // Windows ABI, where any variadic function is implicitly cdecl
16007     // regardless of its normal CC.  Therefore we change the parameter
16008     // types to match the types of the arguments.
16009     //
16010     // This is a hack, but it is far superior to moving the
16011     // corresponding target-specific code from IR-gen to Sema/AST.
16012 
16013     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16014     SmallVector<QualType, 8> ArgTypes;
16015     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16016       ArgTypes.reserve(E->getNumArgs());
16017       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16018         Expr *Arg = E->getArg(i);
16019         QualType ArgType = Arg->getType();
16020         if (E->isLValue()) {
16021           ArgType = S.Context.getLValueReferenceType(ArgType);
16022         } else if (E->isXValue()) {
16023           ArgType = S.Context.getRValueReferenceType(ArgType);
16024         }
16025         ArgTypes.push_back(ArgType);
16026       }
16027       ParamTypes = ArgTypes;
16028     }
16029     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16030                                          Proto->getExtProtoInfo());
16031   } else {
16032     DestType = S.Context.getFunctionNoProtoType(DestType,
16033                                                 FnType->getExtInfo());
16034   }
16035 
16036   // Rebuild the appropriate pointer-to-function type.
16037   switch (Kind) {
16038   case FK_MemberFunction:
16039     // Nothing to do.
16040     break;
16041 
16042   case FK_FunctionPointer:
16043     DestType = S.Context.getPointerType(DestType);
16044     break;
16045 
16046   case FK_BlockPointer:
16047     DestType = S.Context.getBlockPointerType(DestType);
16048     break;
16049   }
16050 
16051   // Finally, we can recurse.
16052   ExprResult CalleeResult = Visit(CalleeExpr);
16053   if (!CalleeResult.isUsable()) return ExprError();
16054   E->setCallee(CalleeResult.get());
16055 
16056   // Bind a temporary if necessary.
16057   return S.MaybeBindToTemporary(E);
16058 }
16059 
16060 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16061   // Verify that this is a legal result type of a call.
16062   if (DestType->isArrayType() || DestType->isFunctionType()) {
16063     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16064       << DestType->isFunctionType() << DestType;
16065     return ExprError();
16066   }
16067 
16068   // Rewrite the method result type if available.
16069   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16070     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16071     Method->setReturnType(DestType);
16072   }
16073 
16074   // Change the type of the message.
16075   E->setType(DestType.getNonReferenceType());
16076   E->setValueKind(Expr::getValueKindForType(DestType));
16077 
16078   return S.MaybeBindToTemporary(E);
16079 }
16080 
16081 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16082   // The only case we should ever see here is a function-to-pointer decay.
16083   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16084     assert(E->getValueKind() == VK_RValue);
16085     assert(E->getObjectKind() == OK_Ordinary);
16086 
16087     E->setType(DestType);
16088 
16089     // Rebuild the sub-expression as the pointee (function) type.
16090     DestType = DestType->castAs<PointerType>()->getPointeeType();
16091 
16092     ExprResult Result = Visit(E->getSubExpr());
16093     if (!Result.isUsable()) return ExprError();
16094 
16095     E->setSubExpr(Result.get());
16096     return E;
16097   } else if (E->getCastKind() == CK_LValueToRValue) {
16098     assert(E->getValueKind() == VK_RValue);
16099     assert(E->getObjectKind() == OK_Ordinary);
16100 
16101     assert(isa<BlockPointerType>(E->getType()));
16102 
16103     E->setType(DestType);
16104 
16105     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16106     DestType = S.Context.getLValueReferenceType(DestType);
16107 
16108     ExprResult Result = Visit(E->getSubExpr());
16109     if (!Result.isUsable()) return ExprError();
16110 
16111     E->setSubExpr(Result.get());
16112     return E;
16113   } else {
16114     llvm_unreachable("Unhandled cast type!");
16115   }
16116 }
16117 
16118 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16119   ExprValueKind ValueKind = VK_LValue;
16120   QualType Type = DestType;
16121 
16122   // We know how to make this work for certain kinds of decls:
16123 
16124   //  - functions
16125   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16126     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16127       DestType = Ptr->getPointeeType();
16128       ExprResult Result = resolveDecl(E, VD);
16129       if (Result.isInvalid()) return ExprError();
16130       return S.ImpCastExprToType(Result.get(), Type,
16131                                  CK_FunctionToPointerDecay, VK_RValue);
16132     }
16133 
16134     if (!Type->isFunctionType()) {
16135       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16136         << VD << E->getSourceRange();
16137       return ExprError();
16138     }
16139     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16140       // We must match the FunctionDecl's type to the hack introduced in
16141       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16142       // type. See the lengthy commentary in that routine.
16143       QualType FDT = FD->getType();
16144       const FunctionType *FnType = FDT->castAs<FunctionType>();
16145       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16146       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16147       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16148         SourceLocation Loc = FD->getLocation();
16149         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16150                                       FD->getDeclContext(),
16151                                       Loc, Loc, FD->getNameInfo().getName(),
16152                                       DestType, FD->getTypeSourceInfo(),
16153                                       SC_None, false/*isInlineSpecified*/,
16154                                       FD->hasPrototype(),
16155                                       false/*isConstexprSpecified*/);
16156 
16157         if (FD->getQualifier())
16158           NewFD->setQualifierInfo(FD->getQualifierLoc());
16159 
16160         SmallVector<ParmVarDecl*, 16> Params;
16161         for (const auto &AI : FT->param_types()) {
16162           ParmVarDecl *Param =
16163             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16164           Param->setScopeInfo(0, Params.size());
16165           Params.push_back(Param);
16166         }
16167         NewFD->setParams(Params);
16168         DRE->setDecl(NewFD);
16169         VD = DRE->getDecl();
16170       }
16171     }
16172 
16173     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16174       if (MD->isInstance()) {
16175         ValueKind = VK_RValue;
16176         Type = S.Context.BoundMemberTy;
16177       }
16178 
16179     // Function references aren't l-values in C.
16180     if (!S.getLangOpts().CPlusPlus)
16181       ValueKind = VK_RValue;
16182 
16183   //  - variables
16184   } else if (isa<VarDecl>(VD)) {
16185     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16186       Type = RefTy->getPointeeType();
16187     } else if (Type->isFunctionType()) {
16188       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16189         << VD << E->getSourceRange();
16190       return ExprError();
16191     }
16192 
16193   //  - nothing else
16194   } else {
16195     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16196       << VD << E->getSourceRange();
16197     return ExprError();
16198   }
16199 
16200   // Modifying the declaration like this is friendly to IR-gen but
16201   // also really dangerous.
16202   VD->setType(DestType);
16203   E->setType(Type);
16204   E->setValueKind(ValueKind);
16205   return E;
16206 }
16207 
16208 /// Check a cast of an unknown-any type.  We intentionally only
16209 /// trigger this for C-style casts.
16210 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16211                                      Expr *CastExpr, CastKind &CastKind,
16212                                      ExprValueKind &VK, CXXCastPath &Path) {
16213   // The type we're casting to must be either void or complete.
16214   if (!CastType->isVoidType() &&
16215       RequireCompleteType(TypeRange.getBegin(), CastType,
16216                           diag::err_typecheck_cast_to_incomplete))
16217     return ExprError();
16218 
16219   // Rewrite the casted expression from scratch.
16220   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16221   if (!result.isUsable()) return ExprError();
16222 
16223   CastExpr = result.get();
16224   VK = CastExpr->getValueKind();
16225   CastKind = CK_NoOp;
16226 
16227   return CastExpr;
16228 }
16229 
16230 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16231   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16232 }
16233 
16234 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16235                                     Expr *arg, QualType &paramType) {
16236   // If the syntactic form of the argument is not an explicit cast of
16237   // any sort, just do default argument promotion.
16238   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16239   if (!castArg) {
16240     ExprResult result = DefaultArgumentPromotion(arg);
16241     if (result.isInvalid()) return ExprError();
16242     paramType = result.get()->getType();
16243     return result;
16244   }
16245 
16246   // Otherwise, use the type that was written in the explicit cast.
16247   assert(!arg->hasPlaceholderType());
16248   paramType = castArg->getTypeAsWritten();
16249 
16250   // Copy-initialize a parameter of that type.
16251   InitializedEntity entity =
16252     InitializedEntity::InitializeParameter(Context, paramType,
16253                                            /*consumed*/ false);
16254   return PerformCopyInitialization(entity, callLoc, arg);
16255 }
16256 
16257 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16258   Expr *orig = E;
16259   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16260   while (true) {
16261     E = E->IgnoreParenImpCasts();
16262     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16263       E = call->getCallee();
16264       diagID = diag::err_uncasted_call_of_unknown_any;
16265     } else {
16266       break;
16267     }
16268   }
16269 
16270   SourceLocation loc;
16271   NamedDecl *d;
16272   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16273     loc = ref->getLocation();
16274     d = ref->getDecl();
16275   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16276     loc = mem->getMemberLoc();
16277     d = mem->getMemberDecl();
16278   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16279     diagID = diag::err_uncasted_call_of_unknown_any;
16280     loc = msg->getSelectorStartLoc();
16281     d = msg->getMethodDecl();
16282     if (!d) {
16283       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16284         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16285         << orig->getSourceRange();
16286       return ExprError();
16287     }
16288   } else {
16289     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16290       << E->getSourceRange();
16291     return ExprError();
16292   }
16293 
16294   S.Diag(loc, diagID) << d << orig->getSourceRange();
16295 
16296   // Never recoverable.
16297   return ExprError();
16298 }
16299 
16300 /// Check for operands with placeholder types and complain if found.
16301 /// Returns ExprError() if there was an error and no recovery was possible.
16302 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16303   if (!getLangOpts().CPlusPlus) {
16304     // C cannot handle TypoExpr nodes on either side of a binop because it
16305     // doesn't handle dependent types properly, so make sure any TypoExprs have
16306     // been dealt with before checking the operands.
16307     ExprResult Result = CorrectDelayedTyposInExpr(E);
16308     if (!Result.isUsable()) return ExprError();
16309     E = Result.get();
16310   }
16311 
16312   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16313   if (!placeholderType) return E;
16314 
16315   switch (placeholderType->getKind()) {
16316 
16317   // Overloaded expressions.
16318   case BuiltinType::Overload: {
16319     // Try to resolve a single function template specialization.
16320     // This is obligatory.
16321     ExprResult Result = E;
16322     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16323       return Result;
16324 
16325     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16326     // leaves Result unchanged on failure.
16327     Result = E;
16328     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16329       return Result;
16330 
16331     // If that failed, try to recover with a call.
16332     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16333                          /*complain*/ true);
16334     return Result;
16335   }
16336 
16337   // Bound member functions.
16338   case BuiltinType::BoundMember: {
16339     ExprResult result = E;
16340     const Expr *BME = E->IgnoreParens();
16341     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16342     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16343     if (isa<CXXPseudoDestructorExpr>(BME)) {
16344       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16345     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16346       if (ME->getMemberNameInfo().getName().getNameKind() ==
16347           DeclarationName::CXXDestructorName)
16348         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16349     }
16350     tryToRecoverWithCall(result, PD,
16351                          /*complain*/ true);
16352     return result;
16353   }
16354 
16355   // ARC unbridged casts.
16356   case BuiltinType::ARCUnbridgedCast: {
16357     Expr *realCast = stripARCUnbridgedCast(E);
16358     diagnoseARCUnbridgedCast(realCast);
16359     return realCast;
16360   }
16361 
16362   // Expressions of unknown type.
16363   case BuiltinType::UnknownAny:
16364     return diagnoseUnknownAnyExpr(*this, E);
16365 
16366   // Pseudo-objects.
16367   case BuiltinType::PseudoObject:
16368     return checkPseudoObjectRValue(E);
16369 
16370   case BuiltinType::BuiltinFn: {
16371     // Accept __noop without parens by implicitly converting it to a call expr.
16372     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16373     if (DRE) {
16374       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16375       if (FD->getBuiltinID() == Builtin::BI__noop) {
16376         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16377                               CK_BuiltinFnToFnPtr).get();
16378         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16379                                       VK_RValue, SourceLocation());
16380       }
16381     }
16382 
16383     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16384     return ExprError();
16385   }
16386 
16387   // Expressions of unknown type.
16388   case BuiltinType::OMPArraySection:
16389     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16390     return ExprError();
16391 
16392   // Everything else should be impossible.
16393 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16394   case BuiltinType::Id:
16395 #include "clang/Basic/OpenCLImageTypes.def"
16396 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16397 #define PLACEHOLDER_TYPE(Id, SingletonId)
16398 #include "clang/AST/BuiltinTypes.def"
16399     break;
16400   }
16401 
16402   llvm_unreachable("invalid placeholder type!");
16403 }
16404 
16405 bool Sema::CheckCaseExpression(Expr *E) {
16406   if (E->isTypeDependent())
16407     return true;
16408   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16409     return E->getType()->isIntegralOrEnumerationType();
16410   return false;
16411 }
16412 
16413 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16414 ExprResult
16415 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16416   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16417          "Unknown Objective-C Boolean value!");
16418   QualType BoolT = Context.ObjCBuiltinBoolTy;
16419   if (!Context.getBOOLDecl()) {
16420     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16421                         Sema::LookupOrdinaryName);
16422     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16423       NamedDecl *ND = Result.getFoundDecl();
16424       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16425         Context.setBOOLDecl(TD);
16426     }
16427   }
16428   if (Context.getBOOLDecl())
16429     BoolT = Context.getBOOLType();
16430   return new (Context)
16431       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16432 }
16433 
16434 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16435     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16436     SourceLocation RParen) {
16437 
16438   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16439 
16440   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16441                            [&](const AvailabilitySpec &Spec) {
16442                              return Spec.getPlatform() == Platform;
16443                            });
16444 
16445   VersionTuple Version;
16446   if (Spec != AvailSpecs.end())
16447     Version = Spec->getVersion();
16448 
16449   // The use of `@available` in the enclosing function should be analyzed to
16450   // warn when it's used inappropriately (i.e. not if(@available)).
16451   if (getCurFunctionOrMethodDecl())
16452     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16453   else if (getCurBlock() || getCurLambda())
16454     getCurFunction()->HasPotentialAvailabilityViolations = true;
16455 
16456   return new (Context)
16457       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16458 }
16459