1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprOpenMP.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/FixedPoint.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68 
69     // See if this is an aligned allocation/deallocation function that is
70     // unavailable.
71     if (TreatUnavailableAsInvalid &&
72         isUnavailableAlignedAllocationFunction(*FD))
73       return false;
74   }
75 
76   // See if this function is unavailable.
77   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
78       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
79     return false;
80 
81   return true;
82 }
83 
84 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
85   // Warn if this is used but marked unused.
86   if (const auto *A = D->getAttr<UnusedAttr>()) {
87     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
88     // should diagnose them.
89     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
90         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
91       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
92       if (DC && !DC->hasAttr<UnusedAttr>())
93         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
94     }
95   }
96 }
97 
98 /// Emit a note explaining that this function is deleted.
99 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
100   assert(Decl->isDeleted());
101 
102   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
103 
104   if (Method && Method->isDeleted() && Method->isDefaulted()) {
105     // If the method was explicitly defaulted, point at that declaration.
106     if (!Method->isImplicit())
107       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108 
109     // Try to diagnose why this special member function was implicitly
110     // deleted. This might fail, if that reason no longer applies.
111     CXXSpecialMember CSM = getSpecialMember(Method);
112     if (CSM != CXXInvalid)
113       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
114 
115     return;
116   }
117 
118   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119   if (Ctor && Ctor->isInheritingConstructor())
120     return NoteDeletedInheritingConstructor(Ctor);
121 
122   Diag(Decl->getLocation(), diag::note_availability_specified_here)
123     << Decl << 1;
124 }
125 
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129   for (auto I : D->redecls()) {
130     if (I->getStorageClass() != SC_None)
131       return true;
132   }
133   return false;
134 }
135 
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145                                                       const NamedDecl *D,
146                                                       SourceLocation Loc) {
147   // This is disabled under C++; there are too many ways for this to fire in
148   // contexts where the warning is a false positive, or where it is technically
149   // correct but benign.
150   if (S.getLangOpts().CPlusPlus)
151     return;
152 
153   // Check if this is an inlined function or method.
154   FunctionDecl *Current = S.getCurFunctionDecl();
155   if (!Current)
156     return;
157   if (!Current->isInlined())
158     return;
159   if (!Current->isExternallyVisible())
160     return;
161 
162   // Check if the decl has internal linkage.
163   if (D->getFormalLinkage() != InternalLinkage)
164     return;
165 
166   // Downgrade from ExtWarn to Extension if
167   //  (1) the supposedly external inline function is in the main file,
168   //      and probably won't be included anywhere else.
169   //  (2) the thing we're referencing is a pure function.
170   //  (3) the thing we're referencing is another inline function.
171   // This last can give us false negatives, but it's better than warning on
172   // wrappers for simple C library functions.
173   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175   if (!DowngradeWarning && UsedFn)
176     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177 
178   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179                                : diag::ext_internal_in_extern_inline)
180     << /*IsVar=*/!UsedFn << D;
181 
182   S.MaybeSuggestAddingStaticToDecl(Current);
183 
184   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185       << D;
186 }
187 
188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189   const FunctionDecl *First = Cur->getFirstDecl();
190 
191   // Suggest "static" on the function, if possible.
192   if (!hasAnyExplicitStorageClass(First)) {
193     SourceLocation DeclBegin = First->getSourceRange().getBegin();
194     Diag(DeclBegin, diag::note_convert_inline_to_static)
195       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196   }
197 }
198 
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212                              const ObjCInterfaceDecl *UnknownObjCClass,
213                              bool ObjCPropertyAccess,
214                              bool AvoidPartialAvailabilityChecks,
215                              ObjCInterfaceDecl *ClassReceiver) {
216   SourceLocation Loc = Locs.front();
217   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218     // If there were any diagnostics suppressed by template argument deduction,
219     // emit them now.
220     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221     if (Pos != SuppressedDiagnostics.end()) {
222       for (const PartialDiagnosticAt &Suppressed : Pos->second)
223         Diag(Suppressed.first, Suppressed.second);
224 
225       // Clear out the list of suppressed diagnostics, so that we don't emit
226       // them again for this specialization. However, we don't obsolete this
227       // entry from the table, because we want to avoid ever emitting these
228       // diagnostics again.
229       Pos->second.clear();
230     }
231 
232     // C++ [basic.start.main]p3:
233     //   The function 'main' shall not be used within a program.
234     if (cast<FunctionDecl>(D)->isMain())
235       Diag(Loc, diag::ext_main_used);
236 
237     diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238   }
239 
240   // See if this is an auto-typed variable whose initializer we are parsing.
241   if (ParsingInitForAutoVars.count(D)) {
242     if (isa<BindingDecl>(D)) {
243       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244         << D->getDeclName();
245     } else {
246       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247         << D->getDeclName() << cast<VarDecl>(D)->getType();
248     }
249     return true;
250   }
251 
252   // See if this is a deleted function.
253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254     if (FD->isDeleted()) {
255       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256       if (Ctor && Ctor->isInheritingConstructor())
257         Diag(Loc, diag::err_deleted_inherited_ctor_use)
258             << Ctor->getParent()
259             << Ctor->getInheritedConstructor().getConstructor()->getParent();
260       else
261         Diag(Loc, diag::err_deleted_function_use);
262       NoteDeletedFunction(FD);
263       return true;
264     }
265 
266     // If the function has a deduced return type, and we can't deduce it,
267     // then we can't use it either.
268     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
269         DeduceReturnType(FD, Loc))
270       return true;
271 
272     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
273       return true;
274   }
275 
276   if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
277     // Lambdas are only default-constructible or assignable in C++2a onwards.
278     if (MD->getParent()->isLambda() &&
279         ((isa<CXXConstructorDecl>(MD) &&
280           cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
281          MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
282       Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
283         << !isa<CXXConstructorDecl>(MD);
284     }
285   }
286 
287   auto getReferencedObjCProp = [](const NamedDecl *D) ->
288                                       const ObjCPropertyDecl * {
289     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
290       return MD->findPropertyDecl();
291     return nullptr;
292   };
293   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
294     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
295       return true;
296   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
297       return true;
298   }
299 
300   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
301   // Only the variables omp_in and omp_out are allowed in the combiner.
302   // Only the variables omp_priv and omp_orig are allowed in the
303   // initializer-clause.
304   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
305   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
306       isa<VarDecl>(D)) {
307     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
308         << getCurFunction()->HasOMPDeclareReductionCombiner;
309     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
310     return true;
311   }
312 
313   // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
314   //  List-items in map clauses on this construct may only refer to the declared
315   //  variable var and entities that could be referenced by a procedure defined
316   //  at the same location
317   auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
318   if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
319       isa<VarDecl>(D)) {
320     Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
321         << DMD->getVarName().getAsString();
322     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
323     return true;
324   }
325 
326   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
327                              AvoidPartialAvailabilityChecks, ClassReceiver);
328 
329   DiagnoseUnusedOfDecl(*this, D, Loc);
330 
331   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
332 
333   return false;
334 }
335 
336 /// Retrieve the message suffix that should be added to a
337 /// diagnostic complaining about the given function being deleted or
338 /// unavailable.
339 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
340   std::string Message;
341   if (FD->getAvailability(&Message))
342     return ": " + Message;
343 
344   return std::string();
345 }
346 
347 /// DiagnoseSentinelCalls - This routine checks whether a call or
348 /// message-send is to a declaration with the sentinel attribute, and
349 /// if so, it checks that the requirements of the sentinel are
350 /// satisfied.
351 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
352                                  ArrayRef<Expr *> Args) {
353   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
354   if (!attr)
355     return;
356 
357   // The number of formal parameters of the declaration.
358   unsigned numFormalParams;
359 
360   // The kind of declaration.  This is also an index into a %select in
361   // the diagnostic.
362   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
363 
364   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
365     numFormalParams = MD->param_size();
366     calleeType = CT_Method;
367   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
368     numFormalParams = FD->param_size();
369     calleeType = CT_Function;
370   } else if (isa<VarDecl>(D)) {
371     QualType type = cast<ValueDecl>(D)->getType();
372     const FunctionType *fn = nullptr;
373     if (const PointerType *ptr = type->getAs<PointerType>()) {
374       fn = ptr->getPointeeType()->getAs<FunctionType>();
375       if (!fn) return;
376       calleeType = CT_Function;
377     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
378       fn = ptr->getPointeeType()->castAs<FunctionType>();
379       calleeType = CT_Block;
380     } else {
381       return;
382     }
383 
384     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
385       numFormalParams = proto->getNumParams();
386     } else {
387       numFormalParams = 0;
388     }
389   } else {
390     return;
391   }
392 
393   // "nullPos" is the number of formal parameters at the end which
394   // effectively count as part of the variadic arguments.  This is
395   // useful if you would prefer to not have *any* formal parameters,
396   // but the language forces you to have at least one.
397   unsigned nullPos = attr->getNullPos();
398   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
399   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
400 
401   // The number of arguments which should follow the sentinel.
402   unsigned numArgsAfterSentinel = attr->getSentinel();
403 
404   // If there aren't enough arguments for all the formal parameters,
405   // the sentinel, and the args after the sentinel, complain.
406   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
407     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
408     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
409     return;
410   }
411 
412   // Otherwise, find the sentinel expression.
413   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
414   if (!sentinelExpr) return;
415   if (sentinelExpr->isValueDependent()) return;
416   if (Context.isSentinelNullExpr(sentinelExpr)) return;
417 
418   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
419   // or 'NULL' if those are actually defined in the context.  Only use
420   // 'nil' for ObjC methods, where it's much more likely that the
421   // variadic arguments form a list of object pointers.
422   SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
423   std::string NullValue;
424   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
425     NullValue = "nil";
426   else if (getLangOpts().CPlusPlus11)
427     NullValue = "nullptr";
428   else if (PP.isMacroDefined("NULL"))
429     NullValue = "NULL";
430   else
431     NullValue = "(void*) 0";
432 
433   if (MissingNilLoc.isInvalid())
434     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
435   else
436     Diag(MissingNilLoc, diag::warn_missing_sentinel)
437       << int(calleeType)
438       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
439   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
440 }
441 
442 SourceRange Sema::getExprRange(Expr *E) const {
443   return E ? E->getSourceRange() : SourceRange();
444 }
445 
446 //===----------------------------------------------------------------------===//
447 //  Standard Promotions and Conversions
448 //===----------------------------------------------------------------------===//
449 
450 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
451 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
452   // Handle any placeholder expressions which made it here.
453   if (E->getType()->isPlaceholderType()) {
454     ExprResult result = CheckPlaceholderExpr(E);
455     if (result.isInvalid()) return ExprError();
456     E = result.get();
457   }
458 
459   QualType Ty = E->getType();
460   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
461 
462   if (Ty->isFunctionType()) {
463     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
464       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
465         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
466           return ExprError();
467 
468     E = ImpCastExprToType(E, Context.getPointerType(Ty),
469                           CK_FunctionToPointerDecay).get();
470   } else if (Ty->isArrayType()) {
471     // In C90 mode, arrays only promote to pointers if the array expression is
472     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
473     // type 'array of type' is converted to an expression that has type 'pointer
474     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
475     // that has type 'array of type' ...".  The relevant change is "an lvalue"
476     // (C90) to "an expression" (C99).
477     //
478     // C++ 4.2p1:
479     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
480     // T" can be converted to an rvalue of type "pointer to T".
481     //
482     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
483       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
484                             CK_ArrayToPointerDecay).get();
485   }
486   return E;
487 }
488 
489 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
490   // Check to see if we are dereferencing a null pointer.  If so,
491   // and if not volatile-qualified, this is undefined behavior that the
492   // optimizer will delete, so warn about it.  People sometimes try to use this
493   // to get a deterministic trap and are surprised by clang's behavior.  This
494   // only handles the pattern "*null", which is a very syntactic check.
495   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
496     if (UO->getOpcode() == UO_Deref &&
497         UO->getSubExpr()->IgnoreParenCasts()->
498           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
499         !UO->getType().isVolatileQualified()) {
500     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
501                           S.PDiag(diag::warn_indirection_through_null)
502                             << UO->getSubExpr()->getSourceRange());
503     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
504                         S.PDiag(diag::note_indirection_through_null));
505   }
506 }
507 
508 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
509                                     SourceLocation AssignLoc,
510                                     const Expr* RHS) {
511   const ObjCIvarDecl *IV = OIRE->getDecl();
512   if (!IV)
513     return;
514 
515   DeclarationName MemberName = IV->getDeclName();
516   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
517   if (!Member || !Member->isStr("isa"))
518     return;
519 
520   const Expr *Base = OIRE->getBase();
521   QualType BaseType = Base->getType();
522   if (OIRE->isArrow())
523     BaseType = BaseType->getPointeeType();
524   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
525     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
526       ObjCInterfaceDecl *ClassDeclared = nullptr;
527       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
528       if (!ClassDeclared->getSuperClass()
529           && (*ClassDeclared->ivar_begin()) == IV) {
530         if (RHS) {
531           NamedDecl *ObjectSetClass =
532             S.LookupSingleName(S.TUScope,
533                                &S.Context.Idents.get("object_setClass"),
534                                SourceLocation(), S.LookupOrdinaryName);
535           if (ObjectSetClass) {
536             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
537             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
538                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
539                                               "object_setClass(")
540                 << FixItHint::CreateReplacement(
541                        SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
542                 << FixItHint::CreateInsertion(RHSLocEnd, ")");
543           }
544           else
545             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
546         } else {
547           NamedDecl *ObjectGetClass =
548             S.LookupSingleName(S.TUScope,
549                                &S.Context.Idents.get("object_getClass"),
550                                SourceLocation(), S.LookupOrdinaryName);
551           if (ObjectGetClass)
552             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
553                 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
554                                               "object_getClass(")
555                 << FixItHint::CreateReplacement(
556                        SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
557           else
558             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
559         }
560         S.Diag(IV->getLocation(), diag::note_ivar_decl);
561       }
562     }
563 }
564 
565 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
566   // Handle any placeholder expressions which made it here.
567   if (E->getType()->isPlaceholderType()) {
568     ExprResult result = CheckPlaceholderExpr(E);
569     if (result.isInvalid()) return ExprError();
570     E = result.get();
571   }
572 
573   // C++ [conv.lval]p1:
574   //   A glvalue of a non-function, non-array type T can be
575   //   converted to a prvalue.
576   if (!E->isGLValue()) return E;
577 
578   QualType T = E->getType();
579   assert(!T.isNull() && "r-value conversion on typeless expression?");
580 
581   // We don't want to throw lvalue-to-rvalue casts on top of
582   // expressions of certain types in C++.
583   if (getLangOpts().CPlusPlus &&
584       (E->getType() == Context.OverloadTy ||
585        T->isDependentType() ||
586        T->isRecordType()))
587     return E;
588 
589   // The C standard is actually really unclear on this point, and
590   // DR106 tells us what the result should be but not why.  It's
591   // generally best to say that void types just doesn't undergo
592   // lvalue-to-rvalue at all.  Note that expressions of unqualified
593   // 'void' type are never l-values, but qualified void can be.
594   if (T->isVoidType())
595     return E;
596 
597   // OpenCL usually rejects direct accesses to values of 'half' type.
598   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
599       T->isHalfType()) {
600     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
601       << 0 << T;
602     return ExprError();
603   }
604 
605   CheckForNullPointerDereference(*this, E);
606   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
607     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
608                                      &Context.Idents.get("object_getClass"),
609                                      SourceLocation(), LookupOrdinaryName);
610     if (ObjectGetClass)
611       Diag(E->getExprLoc(), diag::warn_objc_isa_use)
612           << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
613           << FixItHint::CreateReplacement(
614                  SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
615     else
616       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
617   }
618   else if (const ObjCIvarRefExpr *OIRE =
619             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
620     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
621 
622   // C++ [conv.lval]p1:
623   //   [...] If T is a non-class type, the type of the prvalue is the
624   //   cv-unqualified version of T. Otherwise, the type of the
625   //   rvalue is T.
626   //
627   // C99 6.3.2.1p2:
628   //   If the lvalue has qualified type, the value has the unqualified
629   //   version of the type of the lvalue; otherwise, the value has the
630   //   type of the lvalue.
631   if (T.hasQualifiers())
632     T = T.getUnqualifiedType();
633 
634   // Under the MS ABI, lock down the inheritance model now.
635   if (T->isMemberPointerType() &&
636       Context.getTargetInfo().getCXXABI().isMicrosoft())
637     (void)isCompleteType(E->getExprLoc(), T);
638 
639   UpdateMarkingForLValueToRValue(E);
640 
641   // Loading a __weak object implicitly retains the value, so we need a cleanup to
642   // balance that.
643   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
644     Cleanup.setExprNeedsCleanups(true);
645 
646   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
647                                             nullptr, VK_RValue);
648 
649   // C11 6.3.2.1p2:
650   //   ... if the lvalue has atomic type, the value has the non-atomic version
651   //   of the type of the lvalue ...
652   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
653     T = Atomic->getValueType().getUnqualifiedType();
654     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
655                                    nullptr, VK_RValue);
656   }
657 
658   return Res;
659 }
660 
661 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
662   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
663   if (Res.isInvalid())
664     return ExprError();
665   Res = DefaultLvalueConversion(Res.get());
666   if (Res.isInvalid())
667     return ExprError();
668   return Res;
669 }
670 
671 /// CallExprUnaryConversions - a special case of an unary conversion
672 /// performed on a function designator of a call expression.
673 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
674   QualType Ty = E->getType();
675   ExprResult Res = E;
676   // Only do implicit cast for a function type, but not for a pointer
677   // to function type.
678   if (Ty->isFunctionType()) {
679     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
680                             CK_FunctionToPointerDecay).get();
681     if (Res.isInvalid())
682       return ExprError();
683   }
684   Res = DefaultLvalueConversion(Res.get());
685   if (Res.isInvalid())
686     return ExprError();
687   return Res.get();
688 }
689 
690 /// UsualUnaryConversions - Performs various conversions that are common to most
691 /// operators (C99 6.3). The conversions of array and function types are
692 /// sometimes suppressed. For example, the array->pointer conversion doesn't
693 /// apply if the array is an argument to the sizeof or address (&) operators.
694 /// In these instances, this routine should *not* be called.
695 ExprResult Sema::UsualUnaryConversions(Expr *E) {
696   // First, convert to an r-value.
697   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
698   if (Res.isInvalid())
699     return ExprError();
700   E = Res.get();
701 
702   QualType Ty = E->getType();
703   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
704 
705   // Half FP have to be promoted to float unless it is natively supported
706   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
707     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
708 
709   // Try to perform integral promotions if the object has a theoretically
710   // promotable type.
711   if (Ty->isIntegralOrUnscopedEnumerationType()) {
712     // C99 6.3.1.1p2:
713     //
714     //   The following may be used in an expression wherever an int or
715     //   unsigned int may be used:
716     //     - an object or expression with an integer type whose integer
717     //       conversion rank is less than or equal to the rank of int
718     //       and unsigned int.
719     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
720     //
721     //   If an int can represent all values of the original type, the
722     //   value is converted to an int; otherwise, it is converted to an
723     //   unsigned int. These are called the integer promotions. All
724     //   other types are unchanged by the integer promotions.
725 
726     QualType PTy = Context.isPromotableBitField(E);
727     if (!PTy.isNull()) {
728       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
729       return E;
730     }
731     if (Ty->isPromotableIntegerType()) {
732       QualType PT = Context.getPromotedIntegerType(Ty);
733       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
734       return E;
735     }
736   }
737   return E;
738 }
739 
740 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
741 /// do not have a prototype. Arguments that have type float or __fp16
742 /// are promoted to double. All other argument types are converted by
743 /// UsualUnaryConversions().
744 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
745   QualType Ty = E->getType();
746   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
747 
748   ExprResult Res = UsualUnaryConversions(E);
749   if (Res.isInvalid())
750     return ExprError();
751   E = Res.get();
752 
753   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
754   // promote to double.
755   // Note that default argument promotion applies only to float (and
756   // half/fp16); it does not apply to _Float16.
757   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
758   if (BTy && (BTy->getKind() == BuiltinType::Half ||
759               BTy->getKind() == BuiltinType::Float)) {
760     if (getLangOpts().OpenCL &&
761         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
762         if (BTy->getKind() == BuiltinType::Half) {
763             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
764         }
765     } else {
766       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
767     }
768   }
769 
770   // C++ performs lvalue-to-rvalue conversion as a default argument
771   // promotion, even on class types, but note:
772   //   C++11 [conv.lval]p2:
773   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
774   //     operand or a subexpression thereof the value contained in the
775   //     referenced object is not accessed. Otherwise, if the glvalue
776   //     has a class type, the conversion copy-initializes a temporary
777   //     of type T from the glvalue and the result of the conversion
778   //     is a prvalue for the temporary.
779   // FIXME: add some way to gate this entire thing for correctness in
780   // potentially potentially evaluated contexts.
781   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
782     ExprResult Temp = PerformCopyInitialization(
783                        InitializedEntity::InitializeTemporary(E->getType()),
784                                                 E->getExprLoc(), E);
785     if (Temp.isInvalid())
786       return ExprError();
787     E = Temp.get();
788   }
789 
790   return E;
791 }
792 
793 /// Determine the degree of POD-ness for an expression.
794 /// Incomplete types are considered POD, since this check can be performed
795 /// when we're in an unevaluated context.
796 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
797   if (Ty->isIncompleteType()) {
798     // C++11 [expr.call]p7:
799     //   After these conversions, if the argument does not have arithmetic,
800     //   enumeration, pointer, pointer to member, or class type, the program
801     //   is ill-formed.
802     //
803     // Since we've already performed array-to-pointer and function-to-pointer
804     // decay, the only such type in C++ is cv void. This also handles
805     // initializer lists as variadic arguments.
806     if (Ty->isVoidType())
807       return VAK_Invalid;
808 
809     if (Ty->isObjCObjectType())
810       return VAK_Invalid;
811     return VAK_Valid;
812   }
813 
814   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
815     return VAK_Invalid;
816 
817   if (Ty.isCXX98PODType(Context))
818     return VAK_Valid;
819 
820   // C++11 [expr.call]p7:
821   //   Passing a potentially-evaluated argument of class type (Clause 9)
822   //   having a non-trivial copy constructor, a non-trivial move constructor,
823   //   or a non-trivial destructor, with no corresponding parameter,
824   //   is conditionally-supported with implementation-defined semantics.
825   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
826     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
827       if (!Record->hasNonTrivialCopyConstructor() &&
828           !Record->hasNonTrivialMoveConstructor() &&
829           !Record->hasNonTrivialDestructor())
830         return VAK_ValidInCXX11;
831 
832   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
833     return VAK_Valid;
834 
835   if (Ty->isObjCObjectType())
836     return VAK_Invalid;
837 
838   if (getLangOpts().MSVCCompat)
839     return VAK_MSVCUndefined;
840 
841   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
842   // permitted to reject them. We should consider doing so.
843   return VAK_Undefined;
844 }
845 
846 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
847   // Don't allow one to pass an Objective-C interface to a vararg.
848   const QualType &Ty = E->getType();
849   VarArgKind VAK = isValidVarArgType(Ty);
850 
851   // Complain about passing non-POD types through varargs.
852   switch (VAK) {
853   case VAK_ValidInCXX11:
854     DiagRuntimeBehavior(
855         E->getBeginLoc(), nullptr,
856         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
857     LLVM_FALLTHROUGH;
858   case VAK_Valid:
859     if (Ty->isRecordType()) {
860       // This is unlikely to be what the user intended. If the class has a
861       // 'c_str' member function, the user probably meant to call that.
862       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
863                           PDiag(diag::warn_pass_class_arg_to_vararg)
864                               << Ty << CT << hasCStrMethod(E) << ".c_str()");
865     }
866     break;
867 
868   case VAK_Undefined:
869   case VAK_MSVCUndefined:
870     DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
871                         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
872                             << getLangOpts().CPlusPlus11 << Ty << CT);
873     break;
874 
875   case VAK_Invalid:
876     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
877       Diag(E->getBeginLoc(),
878            diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
879           << Ty << CT;
880     else if (Ty->isObjCObjectType())
881       DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
882                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
883                               << Ty << CT);
884     else
885       Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
886           << isa<InitListExpr>(E) << Ty << CT;
887     break;
888   }
889 }
890 
891 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
892 /// will create a trap if the resulting type is not a POD type.
893 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
894                                                   FunctionDecl *FDecl) {
895   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
896     // Strip the unbridged-cast placeholder expression off, if applicable.
897     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
898         (CT == VariadicMethod ||
899          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
900       E = stripARCUnbridgedCast(E);
901 
902     // Otherwise, do normal placeholder checking.
903     } else {
904       ExprResult ExprRes = CheckPlaceholderExpr(E);
905       if (ExprRes.isInvalid())
906         return ExprError();
907       E = ExprRes.get();
908     }
909   }
910 
911   ExprResult ExprRes = DefaultArgumentPromotion(E);
912   if (ExprRes.isInvalid())
913     return ExprError();
914   E = ExprRes.get();
915 
916   // Diagnostics regarding non-POD argument types are
917   // emitted along with format string checking in Sema::CheckFunctionCall().
918   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
919     // Turn this into a trap.
920     CXXScopeSpec SS;
921     SourceLocation TemplateKWLoc;
922     UnqualifiedId Name;
923     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
924                        E->getBeginLoc());
925     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
926                                           Name, true, false);
927     if (TrapFn.isInvalid())
928       return ExprError();
929 
930     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
931                                     None, E->getEndLoc());
932     if (Call.isInvalid())
933       return ExprError();
934 
935     ExprResult Comma =
936         ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
937     if (Comma.isInvalid())
938       return ExprError();
939     return Comma.get();
940   }
941 
942   if (!getLangOpts().CPlusPlus &&
943       RequireCompleteType(E->getExprLoc(), E->getType(),
944                           diag::err_call_incomplete_argument))
945     return ExprError();
946 
947   return E;
948 }
949 
950 /// Converts an integer to complex float type.  Helper function of
951 /// UsualArithmeticConversions()
952 ///
953 /// \return false if the integer expression is an integer type and is
954 /// successfully converted to the complex type.
955 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
956                                                   ExprResult &ComplexExpr,
957                                                   QualType IntTy,
958                                                   QualType ComplexTy,
959                                                   bool SkipCast) {
960   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
961   if (SkipCast) return false;
962   if (IntTy->isIntegerType()) {
963     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
964     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
965     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
966                                   CK_FloatingRealToComplex);
967   } else {
968     assert(IntTy->isComplexIntegerType());
969     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
970                                   CK_IntegralComplexToFloatingComplex);
971   }
972   return false;
973 }
974 
975 /// Handle arithmetic conversion with complex types.  Helper function of
976 /// UsualArithmeticConversions()
977 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
978                                              ExprResult &RHS, QualType LHSType,
979                                              QualType RHSType,
980                                              bool IsCompAssign) {
981   // if we have an integer operand, the result is the complex type.
982   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
983                                              /*skipCast*/false))
984     return LHSType;
985   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
986                                              /*skipCast*/IsCompAssign))
987     return RHSType;
988 
989   // This handles complex/complex, complex/float, or float/complex.
990   // When both operands are complex, the shorter operand is converted to the
991   // type of the longer, and that is the type of the result. This corresponds
992   // to what is done when combining two real floating-point operands.
993   // The fun begins when size promotion occur across type domains.
994   // From H&S 6.3.4: When one operand is complex and the other is a real
995   // floating-point type, the less precise type is converted, within it's
996   // real or complex domain, to the precision of the other type. For example,
997   // when combining a "long double" with a "double _Complex", the
998   // "double _Complex" is promoted to "long double _Complex".
999 
1000   // Compute the rank of the two types, regardless of whether they are complex.
1001   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1002 
1003   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1004   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1005   QualType LHSElementType =
1006       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1007   QualType RHSElementType =
1008       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1009 
1010   QualType ResultType = S.Context.getComplexType(LHSElementType);
1011   if (Order < 0) {
1012     // Promote the precision of the LHS if not an assignment.
1013     ResultType = S.Context.getComplexType(RHSElementType);
1014     if (!IsCompAssign) {
1015       if (LHSComplexType)
1016         LHS =
1017             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1018       else
1019         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1020     }
1021   } else if (Order > 0) {
1022     // Promote the precision of the RHS.
1023     if (RHSComplexType)
1024       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1025     else
1026       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1027   }
1028   return ResultType;
1029 }
1030 
1031 /// Handle arithmetic conversion from integer to float.  Helper function
1032 /// of UsualArithmeticConversions()
1033 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1034                                            ExprResult &IntExpr,
1035                                            QualType FloatTy, QualType IntTy,
1036                                            bool ConvertFloat, bool ConvertInt) {
1037   if (IntTy->isIntegerType()) {
1038     if (ConvertInt)
1039       // Convert intExpr to the lhs floating point type.
1040       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1041                                     CK_IntegralToFloating);
1042     return FloatTy;
1043   }
1044 
1045   // Convert both sides to the appropriate complex float.
1046   assert(IntTy->isComplexIntegerType());
1047   QualType result = S.Context.getComplexType(FloatTy);
1048 
1049   // _Complex int -> _Complex float
1050   if (ConvertInt)
1051     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1052                                   CK_IntegralComplexToFloatingComplex);
1053 
1054   // float -> _Complex float
1055   if (ConvertFloat)
1056     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1057                                     CK_FloatingRealToComplex);
1058 
1059   return result;
1060 }
1061 
1062 /// Handle arithmethic conversion with floating point types.  Helper
1063 /// function of UsualArithmeticConversions()
1064 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1065                                       ExprResult &RHS, QualType LHSType,
1066                                       QualType RHSType, bool IsCompAssign) {
1067   bool LHSFloat = LHSType->isRealFloatingType();
1068   bool RHSFloat = RHSType->isRealFloatingType();
1069 
1070   // If we have two real floating types, convert the smaller operand
1071   // to the bigger result.
1072   if (LHSFloat && RHSFloat) {
1073     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1074     if (order > 0) {
1075       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1076       return LHSType;
1077     }
1078 
1079     assert(order < 0 && "illegal float comparison");
1080     if (!IsCompAssign)
1081       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1082     return RHSType;
1083   }
1084 
1085   if (LHSFloat) {
1086     // Half FP has to be promoted to float unless it is natively supported
1087     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1088       LHSType = S.Context.FloatTy;
1089 
1090     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1091                                       /*convertFloat=*/!IsCompAssign,
1092                                       /*convertInt=*/ true);
1093   }
1094   assert(RHSFloat);
1095   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1096                                     /*convertInt=*/ true,
1097                                     /*convertFloat=*/!IsCompAssign);
1098 }
1099 
1100 /// Diagnose attempts to convert between __float128 and long double if
1101 /// there is no support for such conversion. Helper function of
1102 /// UsualArithmeticConversions().
1103 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1104                                       QualType RHSType) {
1105   /*  No issue converting if at least one of the types is not a floating point
1106       type or the two types have the same rank.
1107   */
1108   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1109       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1110     return false;
1111 
1112   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1113          "The remaining types must be floating point types.");
1114 
1115   auto *LHSComplex = LHSType->getAs<ComplexType>();
1116   auto *RHSComplex = RHSType->getAs<ComplexType>();
1117 
1118   QualType LHSElemType = LHSComplex ?
1119     LHSComplex->getElementType() : LHSType;
1120   QualType RHSElemType = RHSComplex ?
1121     RHSComplex->getElementType() : RHSType;
1122 
1123   // No issue if the two types have the same representation
1124   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1125       &S.Context.getFloatTypeSemantics(RHSElemType))
1126     return false;
1127 
1128   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1129                                 RHSElemType == S.Context.LongDoubleTy);
1130   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1131                             RHSElemType == S.Context.Float128Ty);
1132 
1133   // We've handled the situation where __float128 and long double have the same
1134   // representation. We allow all conversions for all possible long double types
1135   // except PPC's double double.
1136   return Float128AndLongDouble &&
1137     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1138      &llvm::APFloat::PPCDoubleDouble());
1139 }
1140 
1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1142 
1143 namespace {
1144 /// These helper callbacks are placed in an anonymous namespace to
1145 /// permit their use as function template parameters.
1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1147   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1148 }
1149 
1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1151   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1152                              CK_IntegralComplexCast);
1153 }
1154 }
1155 
1156 /// Handle integer arithmetic conversions.  Helper function of
1157 /// UsualArithmeticConversions()
1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1160                                         ExprResult &RHS, QualType LHSType,
1161                                         QualType RHSType, bool IsCompAssign) {
1162   // The rules for this case are in C99 6.3.1.8
1163   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1164   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1165   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1166   if (LHSSigned == RHSSigned) {
1167     // Same signedness; use the higher-ranked type
1168     if (order >= 0) {
1169       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1170       return LHSType;
1171     } else if (!IsCompAssign)
1172       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1173     return RHSType;
1174   } else if (order != (LHSSigned ? 1 : -1)) {
1175     // The unsigned type has greater than or equal rank to the
1176     // signed type, so use the unsigned type
1177     if (RHSSigned) {
1178       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1179       return LHSType;
1180     } else if (!IsCompAssign)
1181       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1182     return RHSType;
1183   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1184     // The two types are different widths; if we are here, that
1185     // means the signed type is larger than the unsigned type, so
1186     // use the signed type.
1187     if (LHSSigned) {
1188       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1189       return LHSType;
1190     } else if (!IsCompAssign)
1191       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1192     return RHSType;
1193   } else {
1194     // The signed type is higher-ranked than the unsigned type,
1195     // but isn't actually any bigger (like unsigned int and long
1196     // on most 32-bit systems).  Use the unsigned type corresponding
1197     // to the signed type.
1198     QualType result =
1199       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1200     RHS = (*doRHSCast)(S, RHS.get(), result);
1201     if (!IsCompAssign)
1202       LHS = (*doLHSCast)(S, LHS.get(), result);
1203     return result;
1204   }
1205 }
1206 
1207 /// Handle conversions with GCC complex int extension.  Helper function
1208 /// of UsualArithmeticConversions()
1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1210                                            ExprResult &RHS, QualType LHSType,
1211                                            QualType RHSType,
1212                                            bool IsCompAssign) {
1213   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1214   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1215 
1216   if (LHSComplexInt && RHSComplexInt) {
1217     QualType LHSEltType = LHSComplexInt->getElementType();
1218     QualType RHSEltType = RHSComplexInt->getElementType();
1219     QualType ScalarType =
1220       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1221         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1222 
1223     return S.Context.getComplexType(ScalarType);
1224   }
1225 
1226   if (LHSComplexInt) {
1227     QualType LHSEltType = LHSComplexInt->getElementType();
1228     QualType ScalarType =
1229       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1230         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1231     QualType ComplexType = S.Context.getComplexType(ScalarType);
1232     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1233                               CK_IntegralRealToComplex);
1234 
1235     return ComplexType;
1236   }
1237 
1238   assert(RHSComplexInt);
1239 
1240   QualType RHSEltType = RHSComplexInt->getElementType();
1241   QualType ScalarType =
1242     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1243       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1244   QualType ComplexType = S.Context.getComplexType(ScalarType);
1245 
1246   if (!IsCompAssign)
1247     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1248                               CK_IntegralRealToComplex);
1249   return ComplexType;
1250 }
1251 
1252 /// Return the rank of a given fixed point or integer type. The value itself
1253 /// doesn't matter, but the values must be increasing with proper increasing
1254 /// rank as described in N1169 4.1.1.
1255 static unsigned GetFixedPointRank(QualType Ty) {
1256   const auto *BTy = Ty->getAs<BuiltinType>();
1257   assert(BTy && "Expected a builtin type.");
1258 
1259   switch (BTy->getKind()) {
1260   case BuiltinType::ShortFract:
1261   case BuiltinType::UShortFract:
1262   case BuiltinType::SatShortFract:
1263   case BuiltinType::SatUShortFract:
1264     return 1;
1265   case BuiltinType::Fract:
1266   case BuiltinType::UFract:
1267   case BuiltinType::SatFract:
1268   case BuiltinType::SatUFract:
1269     return 2;
1270   case BuiltinType::LongFract:
1271   case BuiltinType::ULongFract:
1272   case BuiltinType::SatLongFract:
1273   case BuiltinType::SatULongFract:
1274     return 3;
1275   case BuiltinType::ShortAccum:
1276   case BuiltinType::UShortAccum:
1277   case BuiltinType::SatShortAccum:
1278   case BuiltinType::SatUShortAccum:
1279     return 4;
1280   case BuiltinType::Accum:
1281   case BuiltinType::UAccum:
1282   case BuiltinType::SatAccum:
1283   case BuiltinType::SatUAccum:
1284     return 5;
1285   case BuiltinType::LongAccum:
1286   case BuiltinType::ULongAccum:
1287   case BuiltinType::SatLongAccum:
1288   case BuiltinType::SatULongAccum:
1289     return 6;
1290   default:
1291     if (BTy->isInteger())
1292       return 0;
1293     llvm_unreachable("Unexpected fixed point or integer type");
1294   }
1295 }
1296 
1297 /// handleFixedPointConversion - Fixed point operations between fixed
1298 /// point types and integers or other fixed point types do not fall under
1299 /// usual arithmetic conversion since these conversions could result in loss
1300 /// of precsision (N1169 4.1.4). These operations should be calculated with
1301 /// the full precision of their result type (N1169 4.1.6.2.1).
1302 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1303                                            QualType RHSTy) {
1304   assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1305          "Expected at least one of the operands to be a fixed point type");
1306   assert((LHSTy->isFixedPointOrIntegerType() ||
1307           RHSTy->isFixedPointOrIntegerType()) &&
1308          "Special fixed point arithmetic operation conversions are only "
1309          "applied to ints or other fixed point types");
1310 
1311   // If one operand has signed fixed-point type and the other operand has
1312   // unsigned fixed-point type, then the unsigned fixed-point operand is
1313   // converted to its corresponding signed fixed-point type and the resulting
1314   // type is the type of the converted operand.
1315   if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1316     LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1317   else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1318     RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1319 
1320   // The result type is the type with the highest rank, whereby a fixed-point
1321   // conversion rank is always greater than an integer conversion rank; if the
1322   // type of either of the operands is a saturating fixedpoint type, the result
1323   // type shall be the saturating fixed-point type corresponding to the type
1324   // with the highest rank; the resulting value is converted (taking into
1325   // account rounding and overflow) to the precision of the resulting type.
1326   // Same ranks between signed and unsigned types are resolved earlier, so both
1327   // types are either signed or both unsigned at this point.
1328   unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1329   unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1330 
1331   QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1332 
1333   if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1334     ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1335 
1336   return ResultTy;
1337 }
1338 
1339 /// UsualArithmeticConversions - Performs various conversions that are common to
1340 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1341 /// routine returns the first non-arithmetic type found. The client is
1342 /// responsible for emitting appropriate error diagnostics.
1343 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1344                                           bool IsCompAssign) {
1345   if (!IsCompAssign) {
1346     LHS = UsualUnaryConversions(LHS.get());
1347     if (LHS.isInvalid())
1348       return QualType();
1349   }
1350 
1351   RHS = UsualUnaryConversions(RHS.get());
1352   if (RHS.isInvalid())
1353     return QualType();
1354 
1355   // For conversion purposes, we ignore any qualifiers.
1356   // For example, "const float" and "float" are equivalent.
1357   QualType LHSType =
1358     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1359   QualType RHSType =
1360     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1361 
1362   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1363   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1364     LHSType = AtomicLHS->getValueType();
1365 
1366   // If both types are identical, no conversion is needed.
1367   if (LHSType == RHSType)
1368     return LHSType;
1369 
1370   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1371   // The caller can deal with this (e.g. pointer + int).
1372   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1373     return QualType();
1374 
1375   // Apply unary and bitfield promotions to the LHS's type.
1376   QualType LHSUnpromotedType = LHSType;
1377   if (LHSType->isPromotableIntegerType())
1378     LHSType = Context.getPromotedIntegerType(LHSType);
1379   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1380   if (!LHSBitfieldPromoteTy.isNull())
1381     LHSType = LHSBitfieldPromoteTy;
1382   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1383     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1384 
1385   // If both types are identical, no conversion is needed.
1386   if (LHSType == RHSType)
1387     return LHSType;
1388 
1389   // At this point, we have two different arithmetic types.
1390 
1391   // Diagnose attempts to convert between __float128 and long double where
1392   // such conversions currently can't be handled.
1393   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1394     return QualType();
1395 
1396   // Handle complex types first (C99 6.3.1.8p1).
1397   if (LHSType->isComplexType() || RHSType->isComplexType())
1398     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1399                                         IsCompAssign);
1400 
1401   // Now handle "real" floating types (i.e. float, double, long double).
1402   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1403     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1404                                  IsCompAssign);
1405 
1406   // Handle GCC complex int extension.
1407   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1408     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1409                                       IsCompAssign);
1410 
1411   if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1412     return handleFixedPointConversion(*this, LHSType, RHSType);
1413 
1414   // Finally, we have two differing integer types.
1415   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1416            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1417 }
1418 
1419 //===----------------------------------------------------------------------===//
1420 //  Semantic Analysis for various Expression Types
1421 //===----------------------------------------------------------------------===//
1422 
1423 
1424 ExprResult
1425 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1426                                 SourceLocation DefaultLoc,
1427                                 SourceLocation RParenLoc,
1428                                 Expr *ControllingExpr,
1429                                 ArrayRef<ParsedType> ArgTypes,
1430                                 ArrayRef<Expr *> ArgExprs) {
1431   unsigned NumAssocs = ArgTypes.size();
1432   assert(NumAssocs == ArgExprs.size());
1433 
1434   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1435   for (unsigned i = 0; i < NumAssocs; ++i) {
1436     if (ArgTypes[i])
1437       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1438     else
1439       Types[i] = nullptr;
1440   }
1441 
1442   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1443                                              ControllingExpr,
1444                                              llvm::makeArrayRef(Types, NumAssocs),
1445                                              ArgExprs);
1446   delete [] Types;
1447   return ER;
1448 }
1449 
1450 ExprResult
1451 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1452                                  SourceLocation DefaultLoc,
1453                                  SourceLocation RParenLoc,
1454                                  Expr *ControllingExpr,
1455                                  ArrayRef<TypeSourceInfo *> Types,
1456                                  ArrayRef<Expr *> Exprs) {
1457   unsigned NumAssocs = Types.size();
1458   assert(NumAssocs == Exprs.size());
1459 
1460   // Decay and strip qualifiers for the controlling expression type, and handle
1461   // placeholder type replacement. See committee discussion from WG14 DR423.
1462   {
1463     EnterExpressionEvaluationContext Unevaluated(
1464         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1465     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1466     if (R.isInvalid())
1467       return ExprError();
1468     ControllingExpr = R.get();
1469   }
1470 
1471   // The controlling expression is an unevaluated operand, so side effects are
1472   // likely unintended.
1473   if (!inTemplateInstantiation() &&
1474       ControllingExpr->HasSideEffects(Context, false))
1475     Diag(ControllingExpr->getExprLoc(),
1476          diag::warn_side_effects_unevaluated_context);
1477 
1478   bool TypeErrorFound = false,
1479        IsResultDependent = ControllingExpr->isTypeDependent(),
1480        ContainsUnexpandedParameterPack
1481          = ControllingExpr->containsUnexpandedParameterPack();
1482 
1483   for (unsigned i = 0; i < NumAssocs; ++i) {
1484     if (Exprs[i]->containsUnexpandedParameterPack())
1485       ContainsUnexpandedParameterPack = true;
1486 
1487     if (Types[i]) {
1488       if (Types[i]->getType()->containsUnexpandedParameterPack())
1489         ContainsUnexpandedParameterPack = true;
1490 
1491       if (Types[i]->getType()->isDependentType()) {
1492         IsResultDependent = true;
1493       } else {
1494         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1495         // complete object type other than a variably modified type."
1496         unsigned D = 0;
1497         if (Types[i]->getType()->isIncompleteType())
1498           D = diag::err_assoc_type_incomplete;
1499         else if (!Types[i]->getType()->isObjectType())
1500           D = diag::err_assoc_type_nonobject;
1501         else if (Types[i]->getType()->isVariablyModifiedType())
1502           D = diag::err_assoc_type_variably_modified;
1503 
1504         if (D != 0) {
1505           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1506             << Types[i]->getTypeLoc().getSourceRange()
1507             << Types[i]->getType();
1508           TypeErrorFound = true;
1509         }
1510 
1511         // C11 6.5.1.1p2 "No two generic associations in the same generic
1512         // selection shall specify compatible types."
1513         for (unsigned j = i+1; j < NumAssocs; ++j)
1514           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1515               Context.typesAreCompatible(Types[i]->getType(),
1516                                          Types[j]->getType())) {
1517             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1518                  diag::err_assoc_compatible_types)
1519               << Types[j]->getTypeLoc().getSourceRange()
1520               << Types[j]->getType()
1521               << Types[i]->getType();
1522             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1523                  diag::note_compat_assoc)
1524               << Types[i]->getTypeLoc().getSourceRange()
1525               << Types[i]->getType();
1526             TypeErrorFound = true;
1527           }
1528       }
1529     }
1530   }
1531   if (TypeErrorFound)
1532     return ExprError();
1533 
1534   // If we determined that the generic selection is result-dependent, don't
1535   // try to compute the result expression.
1536   if (IsResultDependent)
1537     return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1538                                         Exprs, DefaultLoc, RParenLoc,
1539                                         ContainsUnexpandedParameterPack);
1540 
1541   SmallVector<unsigned, 1> CompatIndices;
1542   unsigned DefaultIndex = -1U;
1543   for (unsigned i = 0; i < NumAssocs; ++i) {
1544     if (!Types[i])
1545       DefaultIndex = i;
1546     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1547                                         Types[i]->getType()))
1548       CompatIndices.push_back(i);
1549   }
1550 
1551   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1552   // type compatible with at most one of the types named in its generic
1553   // association list."
1554   if (CompatIndices.size() > 1) {
1555     // We strip parens here because the controlling expression is typically
1556     // parenthesized in macro definitions.
1557     ControllingExpr = ControllingExpr->IgnoreParens();
1558     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1559         << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1560         << (unsigned)CompatIndices.size();
1561     for (unsigned I : CompatIndices) {
1562       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1563            diag::note_compat_assoc)
1564         << Types[I]->getTypeLoc().getSourceRange()
1565         << Types[I]->getType();
1566     }
1567     return ExprError();
1568   }
1569 
1570   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1571   // its controlling expression shall have type compatible with exactly one of
1572   // the types named in its generic association list."
1573   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1574     // We strip parens here because the controlling expression is typically
1575     // parenthesized in macro definitions.
1576     ControllingExpr = ControllingExpr->IgnoreParens();
1577     Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1578         << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1579     return ExprError();
1580   }
1581 
1582   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1583   // type name that is compatible with the type of the controlling expression,
1584   // then the result expression of the generic selection is the expression
1585   // in that generic association. Otherwise, the result expression of the
1586   // generic selection is the expression in the default generic association."
1587   unsigned ResultIndex =
1588     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1589 
1590   return GenericSelectionExpr::Create(
1591       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1592       ContainsUnexpandedParameterPack, ResultIndex);
1593 }
1594 
1595 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1596 /// location of the token and the offset of the ud-suffix within it.
1597 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1598                                      unsigned Offset) {
1599   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1600                                         S.getLangOpts());
1601 }
1602 
1603 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1604 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1605 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1606                                                  IdentifierInfo *UDSuffix,
1607                                                  SourceLocation UDSuffixLoc,
1608                                                  ArrayRef<Expr*> Args,
1609                                                  SourceLocation LitEndLoc) {
1610   assert(Args.size() <= 2 && "too many arguments for literal operator");
1611 
1612   QualType ArgTy[2];
1613   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1614     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1615     if (ArgTy[ArgIdx]->isArrayType())
1616       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1617   }
1618 
1619   DeclarationName OpName =
1620     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1621   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1622   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1623 
1624   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1625   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1626                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1627                               /*AllowStringTemplate*/ false,
1628                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1629     return ExprError();
1630 
1631   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1632 }
1633 
1634 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1635 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1636 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1637 /// multiple tokens.  However, the common case is that StringToks points to one
1638 /// string.
1639 ///
1640 ExprResult
1641 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1642   assert(!StringToks.empty() && "Must have at least one string!");
1643 
1644   StringLiteralParser Literal(StringToks, PP);
1645   if (Literal.hadError)
1646     return ExprError();
1647 
1648   SmallVector<SourceLocation, 4> StringTokLocs;
1649   for (const Token &Tok : StringToks)
1650     StringTokLocs.push_back(Tok.getLocation());
1651 
1652   QualType CharTy = Context.CharTy;
1653   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1654   if (Literal.isWide()) {
1655     CharTy = Context.getWideCharType();
1656     Kind = StringLiteral::Wide;
1657   } else if (Literal.isUTF8()) {
1658     if (getLangOpts().Char8)
1659       CharTy = Context.Char8Ty;
1660     Kind = StringLiteral::UTF8;
1661   } else if (Literal.isUTF16()) {
1662     CharTy = Context.Char16Ty;
1663     Kind = StringLiteral::UTF16;
1664   } else if (Literal.isUTF32()) {
1665     CharTy = Context.Char32Ty;
1666     Kind = StringLiteral::UTF32;
1667   } else if (Literal.isPascal()) {
1668     CharTy = Context.UnsignedCharTy;
1669   }
1670 
1671   // Warn on initializing an array of char from a u8 string literal; this
1672   // becomes ill-formed in C++2a.
1673   if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1674       !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1675     Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1676 
1677     // Create removals for all 'u8' prefixes in the string literal(s). This
1678     // ensures C++2a compatibility (but may change the program behavior when
1679     // built by non-Clang compilers for which the execution character set is
1680     // not always UTF-8).
1681     auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1682     SourceLocation RemovalDiagLoc;
1683     for (const Token &Tok : StringToks) {
1684       if (Tok.getKind() == tok::utf8_string_literal) {
1685         if (RemovalDiagLoc.isInvalid())
1686           RemovalDiagLoc = Tok.getLocation();
1687         RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1688             Tok.getLocation(),
1689             Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1690                                            getSourceManager(), getLangOpts())));
1691       }
1692     }
1693     Diag(RemovalDiagLoc, RemovalDiag);
1694   }
1695 
1696 
1697   QualType CharTyConst = CharTy;
1698   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1699   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1700     CharTyConst.addConst();
1701 
1702   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1703 
1704   // Get an array type for the string, according to C99 6.4.5.  This includes
1705   // the nul terminator character as well as the string length for pascal
1706   // strings.
1707   QualType StrTy = Context.getConstantArrayType(
1708       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1709       ArrayType::Normal, 0);
1710 
1711   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1712   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1713                                              Kind, Literal.Pascal, StrTy,
1714                                              &StringTokLocs[0],
1715                                              StringTokLocs.size());
1716   if (Literal.getUDSuffix().empty())
1717     return Lit;
1718 
1719   // We're building a user-defined literal.
1720   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1721   SourceLocation UDSuffixLoc =
1722     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1723                    Literal.getUDSuffixOffset());
1724 
1725   // Make sure we're allowed user-defined literals here.
1726   if (!UDLScope)
1727     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1728 
1729   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1730   //   operator "" X (str, len)
1731   QualType SizeType = Context.getSizeType();
1732 
1733   DeclarationName OpName =
1734     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1735   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1736   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1737 
1738   QualType ArgTy[] = {
1739     Context.getArrayDecayedType(StrTy), SizeType
1740   };
1741 
1742   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1743   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1744                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1745                                 /*AllowStringTemplate*/ true,
1746                                 /*DiagnoseMissing*/ true)) {
1747 
1748   case LOLR_Cooked: {
1749     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1750     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1751                                                     StringTokLocs[0]);
1752     Expr *Args[] = { Lit, LenArg };
1753 
1754     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1755   }
1756 
1757   case LOLR_StringTemplate: {
1758     TemplateArgumentListInfo ExplicitArgs;
1759 
1760     unsigned CharBits = Context.getIntWidth(CharTy);
1761     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1762     llvm::APSInt Value(CharBits, CharIsUnsigned);
1763 
1764     TemplateArgument TypeArg(CharTy);
1765     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1766     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1767 
1768     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1769       Value = Lit->getCodeUnit(I);
1770       TemplateArgument Arg(Context, Value, CharTy);
1771       TemplateArgumentLocInfo ArgInfo;
1772       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1773     }
1774     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1775                                     &ExplicitArgs);
1776   }
1777   case LOLR_Raw:
1778   case LOLR_Template:
1779   case LOLR_ErrorNoDiagnostic:
1780     llvm_unreachable("unexpected literal operator lookup result");
1781   case LOLR_Error:
1782     return ExprError();
1783   }
1784   llvm_unreachable("unexpected literal operator lookup result");
1785 }
1786 
1787 ExprResult
1788 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1789                        SourceLocation Loc,
1790                        const CXXScopeSpec *SS) {
1791   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1792   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1793 }
1794 
1795 /// BuildDeclRefExpr - Build an expression that references a
1796 /// declaration that does not require a closure capture.
1797 ExprResult
1798 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1799                        const DeclarationNameInfo &NameInfo,
1800                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1801                        const TemplateArgumentListInfo *TemplateArgs) {
1802   bool RefersToCapturedVariable =
1803       isa<VarDecl>(D) &&
1804       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1805 
1806   DeclRefExpr *E;
1807   if (isa<VarTemplateSpecializationDecl>(D)) {
1808     VarTemplateSpecializationDecl *VarSpec =
1809         cast<VarTemplateSpecializationDecl>(D);
1810 
1811     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1812                                         : NestedNameSpecifierLoc(),
1813                             VarSpec->getTemplateKeywordLoc(), D,
1814                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1815                             FoundD, TemplateArgs);
1816   } else {
1817     assert(!TemplateArgs && "No template arguments for non-variable"
1818                             " template specialization references");
1819     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1820                                         : NestedNameSpecifierLoc(),
1821                             SourceLocation(), D, RefersToCapturedVariable,
1822                             NameInfo, Ty, VK, FoundD);
1823   }
1824 
1825   MarkDeclRefReferenced(E);
1826 
1827   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1828       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1829       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1830     getCurFunction()->recordUseOfWeak(E);
1831 
1832   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1833   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1834     FD = IFD->getAnonField();
1835   if (FD) {
1836     UnusedPrivateFields.remove(FD);
1837     // Just in case we're building an illegal pointer-to-member.
1838     if (FD->isBitField())
1839       E->setObjectKind(OK_BitField);
1840   }
1841 
1842   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1843   // designates a bit-field.
1844   if (auto *BD = dyn_cast<BindingDecl>(D))
1845     if (auto *BE = BD->getBinding())
1846       E->setObjectKind(BE->getObjectKind());
1847 
1848   return E;
1849 }
1850 
1851 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1852 /// possibly a list of template arguments.
1853 ///
1854 /// If this produces template arguments, it is permitted to call
1855 /// DecomposeTemplateName.
1856 ///
1857 /// This actually loses a lot of source location information for
1858 /// non-standard name kinds; we should consider preserving that in
1859 /// some way.
1860 void
1861 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1862                              TemplateArgumentListInfo &Buffer,
1863                              DeclarationNameInfo &NameInfo,
1864                              const TemplateArgumentListInfo *&TemplateArgs) {
1865   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1866     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1867     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1868 
1869     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1870                                        Id.TemplateId->NumArgs);
1871     translateTemplateArguments(TemplateArgsPtr, Buffer);
1872 
1873     TemplateName TName = Id.TemplateId->Template.get();
1874     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1875     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1876     TemplateArgs = &Buffer;
1877   } else {
1878     NameInfo = GetNameFromUnqualifiedId(Id);
1879     TemplateArgs = nullptr;
1880   }
1881 }
1882 
1883 static void emitEmptyLookupTypoDiagnostic(
1884     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1885     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1886     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1887   DeclContext *Ctx =
1888       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1889   if (!TC) {
1890     // Emit a special diagnostic for failed member lookups.
1891     // FIXME: computing the declaration context might fail here (?)
1892     if (Ctx)
1893       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1894                                                  << SS.getRange();
1895     else
1896       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1897     return;
1898   }
1899 
1900   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1901   bool DroppedSpecifier =
1902       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1903   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1904                         ? diag::note_implicit_param_decl
1905                         : diag::note_previous_decl;
1906   if (!Ctx)
1907     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1908                          SemaRef.PDiag(NoteID));
1909   else
1910     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1911                                  << Typo << Ctx << DroppedSpecifier
1912                                  << SS.getRange(),
1913                          SemaRef.PDiag(NoteID));
1914 }
1915 
1916 /// Diagnose an empty lookup.
1917 ///
1918 /// \return false if new lookup candidates were found
1919 bool
1920 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1921                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1922                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1923                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1924   DeclarationName Name = R.getLookupName();
1925 
1926   unsigned diagnostic = diag::err_undeclared_var_use;
1927   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1928   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1929       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1930       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1931     diagnostic = diag::err_undeclared_use;
1932     diagnostic_suggest = diag::err_undeclared_use_suggest;
1933   }
1934 
1935   // If the original lookup was an unqualified lookup, fake an
1936   // unqualified lookup.  This is useful when (for example) the
1937   // original lookup would not have found something because it was a
1938   // dependent name.
1939   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1940   while (DC) {
1941     if (isa<CXXRecordDecl>(DC)) {
1942       LookupQualifiedName(R, DC);
1943 
1944       if (!R.empty()) {
1945         // Don't give errors about ambiguities in this lookup.
1946         R.suppressDiagnostics();
1947 
1948         // During a default argument instantiation the CurContext points
1949         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1950         // function parameter list, hence add an explicit check.
1951         bool isDefaultArgument =
1952             !CodeSynthesisContexts.empty() &&
1953             CodeSynthesisContexts.back().Kind ==
1954                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1955         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1956         bool isInstance = CurMethod &&
1957                           CurMethod->isInstance() &&
1958                           DC == CurMethod->getParent() && !isDefaultArgument;
1959 
1960         // Give a code modification hint to insert 'this->'.
1961         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1962         // Actually quite difficult!
1963         if (getLangOpts().MSVCCompat)
1964           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1965         if (isInstance) {
1966           Diag(R.getNameLoc(), diagnostic) << Name
1967             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1968           CheckCXXThisCapture(R.getNameLoc());
1969         } else {
1970           Diag(R.getNameLoc(), diagnostic) << Name;
1971         }
1972 
1973         // Do we really want to note all of these?
1974         for (NamedDecl *D : R)
1975           Diag(D->getLocation(), diag::note_dependent_var_use);
1976 
1977         // Return true if we are inside a default argument instantiation
1978         // and the found name refers to an instance member function, otherwise
1979         // the function calling DiagnoseEmptyLookup will try to create an
1980         // implicit member call and this is wrong for default argument.
1981         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1982           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1983           return true;
1984         }
1985 
1986         // Tell the callee to try to recover.
1987         return false;
1988       }
1989 
1990       R.clear();
1991     }
1992 
1993     // In Microsoft mode, if we are performing lookup from within a friend
1994     // function definition declared at class scope then we must set
1995     // DC to the lexical parent to be able to search into the parent
1996     // class.
1997     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1998         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1999         DC->getLexicalParent()->isRecord())
2000       DC = DC->getLexicalParent();
2001     else
2002       DC = DC->getParent();
2003   }
2004 
2005   // We didn't find anything, so try to correct for a typo.
2006   TypoCorrection Corrected;
2007   if (S && Out) {
2008     SourceLocation TypoLoc = R.getNameLoc();
2009     assert(!ExplicitTemplateArgs &&
2010            "Diagnosing an empty lookup with explicit template args!");
2011     *Out = CorrectTypoDelayed(
2012         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
2013         [=](const TypoCorrection &TC) {
2014           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2015                                         diagnostic, diagnostic_suggest);
2016         },
2017         nullptr, CTK_ErrorRecovery);
2018     if (*Out)
2019       return true;
2020   } else if (S && (Corrected =
2021                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
2022                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
2023     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2024     bool DroppedSpecifier =
2025         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2026     R.setLookupName(Corrected.getCorrection());
2027 
2028     bool AcceptableWithRecovery = false;
2029     bool AcceptableWithoutRecovery = false;
2030     NamedDecl *ND = Corrected.getFoundDecl();
2031     if (ND) {
2032       if (Corrected.isOverloaded()) {
2033         OverloadCandidateSet OCS(R.getNameLoc(),
2034                                  OverloadCandidateSet::CSK_Normal);
2035         OverloadCandidateSet::iterator Best;
2036         for (NamedDecl *CD : Corrected) {
2037           if (FunctionTemplateDecl *FTD =
2038                    dyn_cast<FunctionTemplateDecl>(CD))
2039             AddTemplateOverloadCandidate(
2040                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2041                 Args, OCS);
2042           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2043             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2044               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2045                                    Args, OCS);
2046         }
2047         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2048         case OR_Success:
2049           ND = Best->FoundDecl;
2050           Corrected.setCorrectionDecl(ND);
2051           break;
2052         default:
2053           // FIXME: Arbitrarily pick the first declaration for the note.
2054           Corrected.setCorrectionDecl(ND);
2055           break;
2056         }
2057       }
2058       R.addDecl(ND);
2059       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2060         CXXRecordDecl *Record = nullptr;
2061         if (Corrected.getCorrectionSpecifier()) {
2062           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2063           Record = Ty->getAsCXXRecordDecl();
2064         }
2065         if (!Record)
2066           Record = cast<CXXRecordDecl>(
2067               ND->getDeclContext()->getRedeclContext());
2068         R.setNamingClass(Record);
2069       }
2070 
2071       auto *UnderlyingND = ND->getUnderlyingDecl();
2072       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2073                                isa<FunctionTemplateDecl>(UnderlyingND);
2074       // FIXME: If we ended up with a typo for a type name or
2075       // Objective-C class name, we're in trouble because the parser
2076       // is in the wrong place to recover. Suggest the typo
2077       // correction, but don't make it a fix-it since we're not going
2078       // to recover well anyway.
2079       AcceptableWithoutRecovery =
2080           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2081     } else {
2082       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2083       // because we aren't able to recover.
2084       AcceptableWithoutRecovery = true;
2085     }
2086 
2087     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2088       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2089                             ? diag::note_implicit_param_decl
2090                             : diag::note_previous_decl;
2091       if (SS.isEmpty())
2092         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2093                      PDiag(NoteID), AcceptableWithRecovery);
2094       else
2095         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2096                                   << Name << computeDeclContext(SS, false)
2097                                   << DroppedSpecifier << SS.getRange(),
2098                      PDiag(NoteID), AcceptableWithRecovery);
2099 
2100       // Tell the callee whether to try to recover.
2101       return !AcceptableWithRecovery;
2102     }
2103   }
2104   R.clear();
2105 
2106   // Emit a special diagnostic for failed member lookups.
2107   // FIXME: computing the declaration context might fail here (?)
2108   if (!SS.isEmpty()) {
2109     Diag(R.getNameLoc(), diag::err_no_member)
2110       << Name << computeDeclContext(SS, false)
2111       << SS.getRange();
2112     return true;
2113   }
2114 
2115   // Give up, we can't recover.
2116   Diag(R.getNameLoc(), diagnostic) << Name;
2117   return true;
2118 }
2119 
2120 /// In Microsoft mode, if we are inside a template class whose parent class has
2121 /// dependent base classes, and we can't resolve an unqualified identifier, then
2122 /// assume the identifier is a member of a dependent base class.  We can only
2123 /// recover successfully in static methods, instance methods, and other contexts
2124 /// where 'this' is available.  This doesn't precisely match MSVC's
2125 /// instantiation model, but it's close enough.
2126 static Expr *
2127 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2128                                DeclarationNameInfo &NameInfo,
2129                                SourceLocation TemplateKWLoc,
2130                                const TemplateArgumentListInfo *TemplateArgs) {
2131   // Only try to recover from lookup into dependent bases in static methods or
2132   // contexts where 'this' is available.
2133   QualType ThisType = S.getCurrentThisType();
2134   const CXXRecordDecl *RD = nullptr;
2135   if (!ThisType.isNull())
2136     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2137   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2138     RD = MD->getParent();
2139   if (!RD || !RD->hasAnyDependentBases())
2140     return nullptr;
2141 
2142   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2143   // is available, suggest inserting 'this->' as a fixit.
2144   SourceLocation Loc = NameInfo.getLoc();
2145   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2146   DB << NameInfo.getName() << RD;
2147 
2148   if (!ThisType.isNull()) {
2149     DB << FixItHint::CreateInsertion(Loc, "this->");
2150     return CXXDependentScopeMemberExpr::Create(
2151         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2152         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2153         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2154   }
2155 
2156   // Synthesize a fake NNS that points to the derived class.  This will
2157   // perform name lookup during template instantiation.
2158   CXXScopeSpec SS;
2159   auto *NNS =
2160       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2161   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2162   return DependentScopeDeclRefExpr::Create(
2163       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2164       TemplateArgs);
2165 }
2166 
2167 ExprResult
2168 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2169                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2170                         bool HasTrailingLParen, bool IsAddressOfOperand,
2171                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2172                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2173   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2174          "cannot be direct & operand and have a trailing lparen");
2175   if (SS.isInvalid())
2176     return ExprError();
2177 
2178   TemplateArgumentListInfo TemplateArgsBuffer;
2179 
2180   // Decompose the UnqualifiedId into the following data.
2181   DeclarationNameInfo NameInfo;
2182   const TemplateArgumentListInfo *TemplateArgs;
2183   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2184 
2185   DeclarationName Name = NameInfo.getName();
2186   IdentifierInfo *II = Name.getAsIdentifierInfo();
2187   SourceLocation NameLoc = NameInfo.getLoc();
2188 
2189   if (II && II->isEditorPlaceholder()) {
2190     // FIXME: When typed placeholders are supported we can create a typed
2191     // placeholder expression node.
2192     return ExprError();
2193   }
2194 
2195   // C++ [temp.dep.expr]p3:
2196   //   An id-expression is type-dependent if it contains:
2197   //     -- an identifier that was declared with a dependent type,
2198   //        (note: handled after lookup)
2199   //     -- a template-id that is dependent,
2200   //        (note: handled in BuildTemplateIdExpr)
2201   //     -- a conversion-function-id that specifies a dependent type,
2202   //     -- a nested-name-specifier that contains a class-name that
2203   //        names a dependent type.
2204   // Determine whether this is a member of an unknown specialization;
2205   // we need to handle these differently.
2206   bool DependentID = false;
2207   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2208       Name.getCXXNameType()->isDependentType()) {
2209     DependentID = true;
2210   } else if (SS.isSet()) {
2211     if (DeclContext *DC = computeDeclContext(SS, false)) {
2212       if (RequireCompleteDeclContext(SS, DC))
2213         return ExprError();
2214     } else {
2215       DependentID = true;
2216     }
2217   }
2218 
2219   if (DependentID)
2220     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2221                                       IsAddressOfOperand, TemplateArgs);
2222 
2223   // Perform the required lookup.
2224   LookupResult R(*this, NameInfo,
2225                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2226                      ? LookupObjCImplicitSelfParam
2227                      : LookupOrdinaryName);
2228   if (TemplateKWLoc.isValid() || TemplateArgs) {
2229     // Lookup the template name again to correctly establish the context in
2230     // which it was found. This is really unfortunate as we already did the
2231     // lookup to determine that it was a template name in the first place. If
2232     // this becomes a performance hit, we can work harder to preserve those
2233     // results until we get here but it's likely not worth it.
2234     bool MemberOfUnknownSpecialization;
2235     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2236                            MemberOfUnknownSpecialization, TemplateKWLoc))
2237       return ExprError();
2238 
2239     if (MemberOfUnknownSpecialization ||
2240         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2241       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2242                                         IsAddressOfOperand, TemplateArgs);
2243   } else {
2244     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2245     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2246 
2247     // If the result might be in a dependent base class, this is a dependent
2248     // id-expression.
2249     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2250       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2251                                         IsAddressOfOperand, TemplateArgs);
2252 
2253     // If this reference is in an Objective-C method, then we need to do
2254     // some special Objective-C lookup, too.
2255     if (IvarLookupFollowUp) {
2256       ExprResult E(LookupInObjCMethod(R, S, II, true));
2257       if (E.isInvalid())
2258         return ExprError();
2259 
2260       if (Expr *Ex = E.getAs<Expr>())
2261         return Ex;
2262     }
2263   }
2264 
2265   if (R.isAmbiguous())
2266     return ExprError();
2267 
2268   // This could be an implicitly declared function reference (legal in C90,
2269   // extension in C99, forbidden in C++).
2270   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2271     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2272     if (D) R.addDecl(D);
2273   }
2274 
2275   // Determine whether this name might be a candidate for
2276   // argument-dependent lookup.
2277   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2278 
2279   if (R.empty() && !ADL) {
2280     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2281       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2282                                                    TemplateKWLoc, TemplateArgs))
2283         return E;
2284     }
2285 
2286     // Don't diagnose an empty lookup for inline assembly.
2287     if (IsInlineAsmIdentifier)
2288       return ExprError();
2289 
2290     // If this name wasn't predeclared and if this is not a function
2291     // call, diagnose the problem.
2292     TypoExpr *TE = nullptr;
2293     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2294         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2295     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2296     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2297            "Typo correction callback misconfigured");
2298     if (CCC) {
2299       // Make sure the callback knows what the typo being diagnosed is.
2300       CCC->setTypoName(II);
2301       if (SS.isValid())
2302         CCC->setTypoNNS(SS.getScopeRep());
2303     }
2304     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2305     // a template name, but we happen to have always already looked up the name
2306     // before we get here if it must be a template name.
2307     if (DiagnoseEmptyLookup(S, SS, R,
2308                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2309                             nullptr, None, &TE)) {
2310       if (TE && KeywordReplacement) {
2311         auto &State = getTypoExprState(TE);
2312         auto BestTC = State.Consumer->getNextCorrection();
2313         if (BestTC.isKeyword()) {
2314           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2315           if (State.DiagHandler)
2316             State.DiagHandler(BestTC);
2317           KeywordReplacement->startToken();
2318           KeywordReplacement->setKind(II->getTokenID());
2319           KeywordReplacement->setIdentifierInfo(II);
2320           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2321           // Clean up the state associated with the TypoExpr, since it has
2322           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2323           clearDelayedTypo(TE);
2324           // Signal that a correction to a keyword was performed by returning a
2325           // valid-but-null ExprResult.
2326           return (Expr*)nullptr;
2327         }
2328         State.Consumer->resetCorrectionStream();
2329       }
2330       return TE ? TE : ExprError();
2331     }
2332 
2333     assert(!R.empty() &&
2334            "DiagnoseEmptyLookup returned false but added no results");
2335 
2336     // If we found an Objective-C instance variable, let
2337     // LookupInObjCMethod build the appropriate expression to
2338     // reference the ivar.
2339     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2340       R.clear();
2341       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2342       // In a hopelessly buggy code, Objective-C instance variable
2343       // lookup fails and no expression will be built to reference it.
2344       if (!E.isInvalid() && !E.get())
2345         return ExprError();
2346       return E;
2347     }
2348   }
2349 
2350   // This is guaranteed from this point on.
2351   assert(!R.empty() || ADL);
2352 
2353   // Check whether this might be a C++ implicit instance member access.
2354   // C++ [class.mfct.non-static]p3:
2355   //   When an id-expression that is not part of a class member access
2356   //   syntax and not used to form a pointer to member is used in the
2357   //   body of a non-static member function of class X, if name lookup
2358   //   resolves the name in the id-expression to a non-static non-type
2359   //   member of some class C, the id-expression is transformed into a
2360   //   class member access expression using (*this) as the
2361   //   postfix-expression to the left of the . operator.
2362   //
2363   // But we don't actually need to do this for '&' operands if R
2364   // resolved to a function or overloaded function set, because the
2365   // expression is ill-formed if it actually works out to be a
2366   // non-static member function:
2367   //
2368   // C++ [expr.ref]p4:
2369   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2370   //   [t]he expression can be used only as the left-hand operand of a
2371   //   member function call.
2372   //
2373   // There are other safeguards against such uses, but it's important
2374   // to get this right here so that we don't end up making a
2375   // spuriously dependent expression if we're inside a dependent
2376   // instance method.
2377   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2378     bool MightBeImplicitMember;
2379     if (!IsAddressOfOperand)
2380       MightBeImplicitMember = true;
2381     else if (!SS.isEmpty())
2382       MightBeImplicitMember = false;
2383     else if (R.isOverloadedResult())
2384       MightBeImplicitMember = false;
2385     else if (R.isUnresolvableResult())
2386       MightBeImplicitMember = true;
2387     else
2388       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2389                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2390                               isa<MSPropertyDecl>(R.getFoundDecl());
2391 
2392     if (MightBeImplicitMember)
2393       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2394                                              R, TemplateArgs, S);
2395   }
2396 
2397   if (TemplateArgs || TemplateKWLoc.isValid()) {
2398 
2399     // In C++1y, if this is a variable template id, then check it
2400     // in BuildTemplateIdExpr().
2401     // The single lookup result must be a variable template declaration.
2402     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2403         Id.TemplateId->Kind == TNK_Var_template) {
2404       assert(R.getAsSingle<VarTemplateDecl>() &&
2405              "There should only be one declaration found.");
2406     }
2407 
2408     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2409   }
2410 
2411   return BuildDeclarationNameExpr(SS, R, ADL);
2412 }
2413 
2414 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2415 /// declaration name, generally during template instantiation.
2416 /// There's a large number of things which don't need to be done along
2417 /// this path.
2418 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2419     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2420     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2421   DeclContext *DC = computeDeclContext(SS, false);
2422   if (!DC)
2423     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2424                                      NameInfo, /*TemplateArgs=*/nullptr);
2425 
2426   if (RequireCompleteDeclContext(SS, DC))
2427     return ExprError();
2428 
2429   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2430   LookupQualifiedName(R, DC);
2431 
2432   if (R.isAmbiguous())
2433     return ExprError();
2434 
2435   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2436     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2437                                      NameInfo, /*TemplateArgs=*/nullptr);
2438 
2439   if (R.empty()) {
2440     Diag(NameInfo.getLoc(), diag::err_no_member)
2441       << NameInfo.getName() << DC << SS.getRange();
2442     return ExprError();
2443   }
2444 
2445   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2446     // Diagnose a missing typename if this resolved unambiguously to a type in
2447     // a dependent context.  If we can recover with a type, downgrade this to
2448     // a warning in Microsoft compatibility mode.
2449     unsigned DiagID = diag::err_typename_missing;
2450     if (RecoveryTSI && getLangOpts().MSVCCompat)
2451       DiagID = diag::ext_typename_missing;
2452     SourceLocation Loc = SS.getBeginLoc();
2453     auto D = Diag(Loc, DiagID);
2454     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2455       << SourceRange(Loc, NameInfo.getEndLoc());
2456 
2457     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2458     // context.
2459     if (!RecoveryTSI)
2460       return ExprError();
2461 
2462     // Only issue the fixit if we're prepared to recover.
2463     D << FixItHint::CreateInsertion(Loc, "typename ");
2464 
2465     // Recover by pretending this was an elaborated type.
2466     QualType Ty = Context.getTypeDeclType(TD);
2467     TypeLocBuilder TLB;
2468     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2469 
2470     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2471     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2472     QTL.setElaboratedKeywordLoc(SourceLocation());
2473     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2474 
2475     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2476 
2477     return ExprEmpty();
2478   }
2479 
2480   // Defend against this resolving to an implicit member access. We usually
2481   // won't get here if this might be a legitimate a class member (we end up in
2482   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2483   // a pointer-to-member or in an unevaluated context in C++11.
2484   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2485     return BuildPossibleImplicitMemberExpr(SS,
2486                                            /*TemplateKWLoc=*/SourceLocation(),
2487                                            R, /*TemplateArgs=*/nullptr, S);
2488 
2489   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2490 }
2491 
2492 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2493 /// detected that we're currently inside an ObjC method.  Perform some
2494 /// additional lookup.
2495 ///
2496 /// Ideally, most of this would be done by lookup, but there's
2497 /// actually quite a lot of extra work involved.
2498 ///
2499 /// Returns a null sentinel to indicate trivial success.
2500 ExprResult
2501 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2502                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2503   SourceLocation Loc = Lookup.getNameLoc();
2504   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2505 
2506   // Check for error condition which is already reported.
2507   if (!CurMethod)
2508     return ExprError();
2509 
2510   // There are two cases to handle here.  1) scoped lookup could have failed,
2511   // in which case we should look for an ivar.  2) scoped lookup could have
2512   // found a decl, but that decl is outside the current instance method (i.e.
2513   // a global variable).  In these two cases, we do a lookup for an ivar with
2514   // this name, if the lookup sucedes, we replace it our current decl.
2515 
2516   // If we're in a class method, we don't normally want to look for
2517   // ivars.  But if we don't find anything else, and there's an
2518   // ivar, that's an error.
2519   bool IsClassMethod = CurMethod->isClassMethod();
2520 
2521   bool LookForIvars;
2522   if (Lookup.empty())
2523     LookForIvars = true;
2524   else if (IsClassMethod)
2525     LookForIvars = false;
2526   else
2527     LookForIvars = (Lookup.isSingleResult() &&
2528                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2529   ObjCInterfaceDecl *IFace = nullptr;
2530   if (LookForIvars) {
2531     IFace = CurMethod->getClassInterface();
2532     ObjCInterfaceDecl *ClassDeclared;
2533     ObjCIvarDecl *IV = nullptr;
2534     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2535       // Diagnose using an ivar in a class method.
2536       if (IsClassMethod)
2537         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2538                          << IV->getDeclName());
2539 
2540       // If we're referencing an invalid decl, just return this as a silent
2541       // error node.  The error diagnostic was already emitted on the decl.
2542       if (IV->isInvalidDecl())
2543         return ExprError();
2544 
2545       // Check if referencing a field with __attribute__((deprecated)).
2546       if (DiagnoseUseOfDecl(IV, Loc))
2547         return ExprError();
2548 
2549       // Diagnose the use of an ivar outside of the declaring class.
2550       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2551           !declaresSameEntity(ClassDeclared, IFace) &&
2552           !getLangOpts().DebuggerSupport)
2553         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2554 
2555       // FIXME: This should use a new expr for a direct reference, don't
2556       // turn this into Self->ivar, just return a BareIVarExpr or something.
2557       IdentifierInfo &II = Context.Idents.get("self");
2558       UnqualifiedId SelfName;
2559       SelfName.setIdentifier(&II, SourceLocation());
2560       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2561       CXXScopeSpec SelfScopeSpec;
2562       SourceLocation TemplateKWLoc;
2563       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2564                                               SelfName, false, false);
2565       if (SelfExpr.isInvalid())
2566         return ExprError();
2567 
2568       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2569       if (SelfExpr.isInvalid())
2570         return ExprError();
2571 
2572       MarkAnyDeclReferenced(Loc, IV, true);
2573 
2574       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2575       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2576           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2577         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2578 
2579       ObjCIvarRefExpr *Result = new (Context)
2580           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2581                           IV->getLocation(), SelfExpr.get(), true, true);
2582 
2583       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2584         if (!isUnevaluatedContext() &&
2585             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2586           getCurFunction()->recordUseOfWeak(Result);
2587       }
2588       if (getLangOpts().ObjCAutoRefCount) {
2589         if (CurContext->isClosure())
2590           Diag(Loc, diag::warn_implicitly_retains_self)
2591             << FixItHint::CreateInsertion(Loc, "self->");
2592       }
2593 
2594       return Result;
2595     }
2596   } else if (CurMethod->isInstanceMethod()) {
2597     // We should warn if a local variable hides an ivar.
2598     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2599       ObjCInterfaceDecl *ClassDeclared;
2600       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2601         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2602             declaresSameEntity(IFace, ClassDeclared))
2603           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2604       }
2605     }
2606   } else if (Lookup.isSingleResult() &&
2607              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2608     // If accessing a stand-alone ivar in a class method, this is an error.
2609     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2610       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2611                        << IV->getDeclName());
2612   }
2613 
2614   if (Lookup.empty() && II && AllowBuiltinCreation) {
2615     // FIXME. Consolidate this with similar code in LookupName.
2616     if (unsigned BuiltinID = II->getBuiltinID()) {
2617       if (!(getLangOpts().CPlusPlus &&
2618             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2619         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2620                                            S, Lookup.isForRedeclaration(),
2621                                            Lookup.getNameLoc());
2622         if (D) Lookup.addDecl(D);
2623       }
2624     }
2625   }
2626   // Sentinel value saying that we didn't do anything special.
2627   return ExprResult((Expr *)nullptr);
2628 }
2629 
2630 /// Cast a base object to a member's actual type.
2631 ///
2632 /// Logically this happens in three phases:
2633 ///
2634 /// * First we cast from the base type to the naming class.
2635 ///   The naming class is the class into which we were looking
2636 ///   when we found the member;  it's the qualifier type if a
2637 ///   qualifier was provided, and otherwise it's the base type.
2638 ///
2639 /// * Next we cast from the naming class to the declaring class.
2640 ///   If the member we found was brought into a class's scope by
2641 ///   a using declaration, this is that class;  otherwise it's
2642 ///   the class declaring the member.
2643 ///
2644 /// * Finally we cast from the declaring class to the "true"
2645 ///   declaring class of the member.  This conversion does not
2646 ///   obey access control.
2647 ExprResult
2648 Sema::PerformObjectMemberConversion(Expr *From,
2649                                     NestedNameSpecifier *Qualifier,
2650                                     NamedDecl *FoundDecl,
2651                                     NamedDecl *Member) {
2652   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2653   if (!RD)
2654     return From;
2655 
2656   QualType DestRecordType;
2657   QualType DestType;
2658   QualType FromRecordType;
2659   QualType FromType = From->getType();
2660   bool PointerConversions = false;
2661   if (isa<FieldDecl>(Member)) {
2662     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2663 
2664     if (FromType->getAs<PointerType>()) {
2665       DestType = Context.getPointerType(DestRecordType);
2666       FromRecordType = FromType->getPointeeType();
2667       PointerConversions = true;
2668     } else {
2669       DestType = DestRecordType;
2670       FromRecordType = FromType;
2671     }
2672   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2673     if (Method->isStatic())
2674       return From;
2675 
2676     DestType = Method->getThisType();
2677     DestRecordType = DestType->getPointeeType();
2678 
2679     if (FromType->getAs<PointerType>()) {
2680       FromRecordType = FromType->getPointeeType();
2681       PointerConversions = true;
2682     } else {
2683       FromRecordType = FromType;
2684       DestType = DestRecordType;
2685     }
2686   } else {
2687     // No conversion necessary.
2688     return From;
2689   }
2690 
2691   if (DestType->isDependentType() || FromType->isDependentType())
2692     return From;
2693 
2694   // If the unqualified types are the same, no conversion is necessary.
2695   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2696     return From;
2697 
2698   SourceRange FromRange = From->getSourceRange();
2699   SourceLocation FromLoc = FromRange.getBegin();
2700 
2701   ExprValueKind VK = From->getValueKind();
2702 
2703   // C++ [class.member.lookup]p8:
2704   //   [...] Ambiguities can often be resolved by qualifying a name with its
2705   //   class name.
2706   //
2707   // If the member was a qualified name and the qualified referred to a
2708   // specific base subobject type, we'll cast to that intermediate type
2709   // first and then to the object in which the member is declared. That allows
2710   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2711   //
2712   //   class Base { public: int x; };
2713   //   class Derived1 : public Base { };
2714   //   class Derived2 : public Base { };
2715   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2716   //
2717   //   void VeryDerived::f() {
2718   //     x = 17; // error: ambiguous base subobjects
2719   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2720   //   }
2721   if (Qualifier && Qualifier->getAsType()) {
2722     QualType QType = QualType(Qualifier->getAsType(), 0);
2723     assert(QType->isRecordType() && "lookup done with non-record type");
2724 
2725     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2726 
2727     // In C++98, the qualifier type doesn't actually have to be a base
2728     // type of the object type, in which case we just ignore it.
2729     // Otherwise build the appropriate casts.
2730     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2731       CXXCastPath BasePath;
2732       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2733                                        FromLoc, FromRange, &BasePath))
2734         return ExprError();
2735 
2736       if (PointerConversions)
2737         QType = Context.getPointerType(QType);
2738       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2739                                VK, &BasePath).get();
2740 
2741       FromType = QType;
2742       FromRecordType = QRecordType;
2743 
2744       // If the qualifier type was the same as the destination type,
2745       // we're done.
2746       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2747         return From;
2748     }
2749   }
2750 
2751   bool IgnoreAccess = false;
2752 
2753   // If we actually found the member through a using declaration, cast
2754   // down to the using declaration's type.
2755   //
2756   // Pointer equality is fine here because only one declaration of a
2757   // class ever has member declarations.
2758   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2759     assert(isa<UsingShadowDecl>(FoundDecl));
2760     QualType URecordType = Context.getTypeDeclType(
2761                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2762 
2763     // We only need to do this if the naming-class to declaring-class
2764     // conversion is non-trivial.
2765     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2766       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2767       CXXCastPath BasePath;
2768       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2769                                        FromLoc, FromRange, &BasePath))
2770         return ExprError();
2771 
2772       QualType UType = URecordType;
2773       if (PointerConversions)
2774         UType = Context.getPointerType(UType);
2775       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2776                                VK, &BasePath).get();
2777       FromType = UType;
2778       FromRecordType = URecordType;
2779     }
2780 
2781     // We don't do access control for the conversion from the
2782     // declaring class to the true declaring class.
2783     IgnoreAccess = true;
2784   }
2785 
2786   CXXCastPath BasePath;
2787   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2788                                    FromLoc, FromRange, &BasePath,
2789                                    IgnoreAccess))
2790     return ExprError();
2791 
2792   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2793                            VK, &BasePath);
2794 }
2795 
2796 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2797                                       const LookupResult &R,
2798                                       bool HasTrailingLParen) {
2799   // Only when used directly as the postfix-expression of a call.
2800   if (!HasTrailingLParen)
2801     return false;
2802 
2803   // Never if a scope specifier was provided.
2804   if (SS.isSet())
2805     return false;
2806 
2807   // Only in C++ or ObjC++.
2808   if (!getLangOpts().CPlusPlus)
2809     return false;
2810 
2811   // Turn off ADL when we find certain kinds of declarations during
2812   // normal lookup:
2813   for (NamedDecl *D : R) {
2814     // C++0x [basic.lookup.argdep]p3:
2815     //     -- a declaration of a class member
2816     // Since using decls preserve this property, we check this on the
2817     // original decl.
2818     if (D->isCXXClassMember())
2819       return false;
2820 
2821     // C++0x [basic.lookup.argdep]p3:
2822     //     -- a block-scope function declaration that is not a
2823     //        using-declaration
2824     // NOTE: we also trigger this for function templates (in fact, we
2825     // don't check the decl type at all, since all other decl types
2826     // turn off ADL anyway).
2827     if (isa<UsingShadowDecl>(D))
2828       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2829     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2830       return false;
2831 
2832     // C++0x [basic.lookup.argdep]p3:
2833     //     -- a declaration that is neither a function or a function
2834     //        template
2835     // And also for builtin functions.
2836     if (isa<FunctionDecl>(D)) {
2837       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2838 
2839       // But also builtin functions.
2840       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2841         return false;
2842     } else if (!isa<FunctionTemplateDecl>(D))
2843       return false;
2844   }
2845 
2846   return true;
2847 }
2848 
2849 
2850 /// Diagnoses obvious problems with the use of the given declaration
2851 /// as an expression.  This is only actually called for lookups that
2852 /// were not overloaded, and it doesn't promise that the declaration
2853 /// will in fact be used.
2854 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2855   if (D->isInvalidDecl())
2856     return true;
2857 
2858   if (isa<TypedefNameDecl>(D)) {
2859     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2860     return true;
2861   }
2862 
2863   if (isa<ObjCInterfaceDecl>(D)) {
2864     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2865     return true;
2866   }
2867 
2868   if (isa<NamespaceDecl>(D)) {
2869     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2870     return true;
2871   }
2872 
2873   return false;
2874 }
2875 
2876 // Certain multiversion types should be treated as overloaded even when there is
2877 // only one result.
2878 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2879   assert(R.isSingleResult() && "Expected only a single result");
2880   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2881   return FD &&
2882          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2883 }
2884 
2885 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2886                                           LookupResult &R, bool NeedsADL,
2887                                           bool AcceptInvalidDecl) {
2888   // If this is a single, fully-resolved result and we don't need ADL,
2889   // just build an ordinary singleton decl ref.
2890   if (!NeedsADL && R.isSingleResult() &&
2891       !R.getAsSingle<FunctionTemplateDecl>() &&
2892       !ShouldLookupResultBeMultiVersionOverload(R))
2893     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2894                                     R.getRepresentativeDecl(), nullptr,
2895                                     AcceptInvalidDecl);
2896 
2897   // We only need to check the declaration if there's exactly one
2898   // result, because in the overloaded case the results can only be
2899   // functions and function templates.
2900   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2901       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2902     return ExprError();
2903 
2904   // Otherwise, just build an unresolved lookup expression.  Suppress
2905   // any lookup-related diagnostics; we'll hash these out later, when
2906   // we've picked a target.
2907   R.suppressDiagnostics();
2908 
2909   UnresolvedLookupExpr *ULE
2910     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2911                                    SS.getWithLocInContext(Context),
2912                                    R.getLookupNameInfo(),
2913                                    NeedsADL, R.isOverloadedResult(),
2914                                    R.begin(), R.end());
2915 
2916   return ULE;
2917 }
2918 
2919 static void
2920 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2921                                    ValueDecl *var, DeclContext *DC);
2922 
2923 /// Complete semantic analysis for a reference to the given declaration.
2924 ExprResult Sema::BuildDeclarationNameExpr(
2925     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2926     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2927     bool AcceptInvalidDecl) {
2928   assert(D && "Cannot refer to a NULL declaration");
2929   assert(!isa<FunctionTemplateDecl>(D) &&
2930          "Cannot refer unambiguously to a function template");
2931 
2932   SourceLocation Loc = NameInfo.getLoc();
2933   if (CheckDeclInExpr(*this, Loc, D))
2934     return ExprError();
2935 
2936   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2937     // Specifically diagnose references to class templates that are missing
2938     // a template argument list.
2939     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2940     return ExprError();
2941   }
2942 
2943   // Make sure that we're referring to a value.
2944   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2945   if (!VD) {
2946     Diag(Loc, diag::err_ref_non_value)
2947       << D << SS.getRange();
2948     Diag(D->getLocation(), diag::note_declared_at);
2949     return ExprError();
2950   }
2951 
2952   // Check whether this declaration can be used. Note that we suppress
2953   // this check when we're going to perform argument-dependent lookup
2954   // on this function name, because this might not be the function
2955   // that overload resolution actually selects.
2956   if (DiagnoseUseOfDecl(VD, Loc))
2957     return ExprError();
2958 
2959   // Only create DeclRefExpr's for valid Decl's.
2960   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2961     return ExprError();
2962 
2963   // Handle members of anonymous structs and unions.  If we got here,
2964   // and the reference is to a class member indirect field, then this
2965   // must be the subject of a pointer-to-member expression.
2966   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2967     if (!indirectField->isCXXClassMember())
2968       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2969                                                       indirectField);
2970 
2971   {
2972     QualType type = VD->getType();
2973     if (type.isNull())
2974       return ExprError();
2975     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2976       // C++ [except.spec]p17:
2977       //   An exception-specification is considered to be needed when:
2978       //   - in an expression, the function is the unique lookup result or
2979       //     the selected member of a set of overloaded functions.
2980       ResolveExceptionSpec(Loc, FPT);
2981       type = VD->getType();
2982     }
2983     ExprValueKind valueKind = VK_RValue;
2984 
2985     switch (D->getKind()) {
2986     // Ignore all the non-ValueDecl kinds.
2987 #define ABSTRACT_DECL(kind)
2988 #define VALUE(type, base)
2989 #define DECL(type, base) \
2990     case Decl::type:
2991 #include "clang/AST/DeclNodes.inc"
2992       llvm_unreachable("invalid value decl kind");
2993 
2994     // These shouldn't make it here.
2995     case Decl::ObjCAtDefsField:
2996     case Decl::ObjCIvar:
2997       llvm_unreachable("forming non-member reference to ivar?");
2998 
2999     // Enum constants are always r-values and never references.
3000     // Unresolved using declarations are dependent.
3001     case Decl::EnumConstant:
3002     case Decl::UnresolvedUsingValue:
3003     case Decl::OMPDeclareReduction:
3004     case Decl::OMPDeclareMapper:
3005       valueKind = VK_RValue;
3006       break;
3007 
3008     // Fields and indirect fields that got here must be for
3009     // pointer-to-member expressions; we just call them l-values for
3010     // internal consistency, because this subexpression doesn't really
3011     // exist in the high-level semantics.
3012     case Decl::Field:
3013     case Decl::IndirectField:
3014       assert(getLangOpts().CPlusPlus &&
3015              "building reference to field in C?");
3016 
3017       // These can't have reference type in well-formed programs, but
3018       // for internal consistency we do this anyway.
3019       type = type.getNonReferenceType();
3020       valueKind = VK_LValue;
3021       break;
3022 
3023     // Non-type template parameters are either l-values or r-values
3024     // depending on the type.
3025     case Decl::NonTypeTemplateParm: {
3026       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3027         type = reftype->getPointeeType();
3028         valueKind = VK_LValue; // even if the parameter is an r-value reference
3029         break;
3030       }
3031 
3032       // For non-references, we need to strip qualifiers just in case
3033       // the template parameter was declared as 'const int' or whatever.
3034       valueKind = VK_RValue;
3035       type = type.getUnqualifiedType();
3036       break;
3037     }
3038 
3039     case Decl::Var:
3040     case Decl::VarTemplateSpecialization:
3041     case Decl::VarTemplatePartialSpecialization:
3042     case Decl::Decomposition:
3043     case Decl::OMPCapturedExpr:
3044       // In C, "extern void blah;" is valid and is an r-value.
3045       if (!getLangOpts().CPlusPlus &&
3046           !type.hasQualifiers() &&
3047           type->isVoidType()) {
3048         valueKind = VK_RValue;
3049         break;
3050       }
3051       LLVM_FALLTHROUGH;
3052 
3053     case Decl::ImplicitParam:
3054     case Decl::ParmVar: {
3055       // These are always l-values.
3056       valueKind = VK_LValue;
3057       type = type.getNonReferenceType();
3058 
3059       // FIXME: Does the addition of const really only apply in
3060       // potentially-evaluated contexts? Since the variable isn't actually
3061       // captured in an unevaluated context, it seems that the answer is no.
3062       if (!isUnevaluatedContext()) {
3063         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3064         if (!CapturedType.isNull())
3065           type = CapturedType;
3066       }
3067 
3068       break;
3069     }
3070 
3071     case Decl::Binding: {
3072       // These are always lvalues.
3073       valueKind = VK_LValue;
3074       type = type.getNonReferenceType();
3075       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3076       // decides how that's supposed to work.
3077       auto *BD = cast<BindingDecl>(VD);
3078       if (BD->getDeclContext()->isFunctionOrMethod() &&
3079           BD->getDeclContext() != CurContext)
3080         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3081       break;
3082     }
3083 
3084     case Decl::Function: {
3085       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3086         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3087           type = Context.BuiltinFnTy;
3088           valueKind = VK_RValue;
3089           break;
3090         }
3091       }
3092 
3093       const FunctionType *fty = type->castAs<FunctionType>();
3094 
3095       // If we're referring to a function with an __unknown_anytype
3096       // result type, make the entire expression __unknown_anytype.
3097       if (fty->getReturnType() == Context.UnknownAnyTy) {
3098         type = Context.UnknownAnyTy;
3099         valueKind = VK_RValue;
3100         break;
3101       }
3102 
3103       // Functions are l-values in C++.
3104       if (getLangOpts().CPlusPlus) {
3105         valueKind = VK_LValue;
3106         break;
3107       }
3108 
3109       // C99 DR 316 says that, if a function type comes from a
3110       // function definition (without a prototype), that type is only
3111       // used for checking compatibility. Therefore, when referencing
3112       // the function, we pretend that we don't have the full function
3113       // type.
3114       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3115           isa<FunctionProtoType>(fty))
3116         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3117                                               fty->getExtInfo());
3118 
3119       // Functions are r-values in C.
3120       valueKind = VK_RValue;
3121       break;
3122     }
3123 
3124     case Decl::CXXDeductionGuide:
3125       llvm_unreachable("building reference to deduction guide");
3126 
3127     case Decl::MSProperty:
3128       valueKind = VK_LValue;
3129       break;
3130 
3131     case Decl::CXXMethod:
3132       // If we're referring to a method with an __unknown_anytype
3133       // result type, make the entire expression __unknown_anytype.
3134       // This should only be possible with a type written directly.
3135       if (const FunctionProtoType *proto
3136             = dyn_cast<FunctionProtoType>(VD->getType()))
3137         if (proto->getReturnType() == Context.UnknownAnyTy) {
3138           type = Context.UnknownAnyTy;
3139           valueKind = VK_RValue;
3140           break;
3141         }
3142 
3143       // C++ methods are l-values if static, r-values if non-static.
3144       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3145         valueKind = VK_LValue;
3146         break;
3147       }
3148       LLVM_FALLTHROUGH;
3149 
3150     case Decl::CXXConversion:
3151     case Decl::CXXDestructor:
3152     case Decl::CXXConstructor:
3153       valueKind = VK_RValue;
3154       break;
3155     }
3156 
3157     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3158                             TemplateArgs);
3159   }
3160 }
3161 
3162 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3163                                     SmallString<32> &Target) {
3164   Target.resize(CharByteWidth * (Source.size() + 1));
3165   char *ResultPtr = &Target[0];
3166   const llvm::UTF8 *ErrorPtr;
3167   bool success =
3168       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3169   (void)success;
3170   assert(success);
3171   Target.resize(ResultPtr - &Target[0]);
3172 }
3173 
3174 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3175                                      PredefinedExpr::IdentKind IK) {
3176   // Pick the current block, lambda, captured statement or function.
3177   Decl *currentDecl = nullptr;
3178   if (const BlockScopeInfo *BSI = getCurBlock())
3179     currentDecl = BSI->TheDecl;
3180   else if (const LambdaScopeInfo *LSI = getCurLambda())
3181     currentDecl = LSI->CallOperator;
3182   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3183     currentDecl = CSI->TheCapturedDecl;
3184   else
3185     currentDecl = getCurFunctionOrMethodDecl();
3186 
3187   if (!currentDecl) {
3188     Diag(Loc, diag::ext_predef_outside_function);
3189     currentDecl = Context.getTranslationUnitDecl();
3190   }
3191 
3192   QualType ResTy;
3193   StringLiteral *SL = nullptr;
3194   if (cast<DeclContext>(currentDecl)->isDependentContext())
3195     ResTy = Context.DependentTy;
3196   else {
3197     // Pre-defined identifiers are of type char[x], where x is the length of
3198     // the string.
3199     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3200     unsigned Length = Str.length();
3201 
3202     llvm::APInt LengthI(32, Length + 1);
3203     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3204       ResTy =
3205           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3206       SmallString<32> RawChars;
3207       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3208                               Str, RawChars);
3209       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3210                                            /*IndexTypeQuals*/ 0);
3211       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3212                                  /*Pascal*/ false, ResTy, Loc);
3213     } else {
3214       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3215       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3216                                            /*IndexTypeQuals*/ 0);
3217       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3218                                  /*Pascal*/ false, ResTy, Loc);
3219     }
3220   }
3221 
3222   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3223 }
3224 
3225 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3226   PredefinedExpr::IdentKind IK;
3227 
3228   switch (Kind) {
3229   default: llvm_unreachable("Unknown simple primary expr!");
3230   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3231   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3232   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3233   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3234   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3235   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3236   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3237   }
3238 
3239   return BuildPredefinedExpr(Loc, IK);
3240 }
3241 
3242 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3243   SmallString<16> CharBuffer;
3244   bool Invalid = false;
3245   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3246   if (Invalid)
3247     return ExprError();
3248 
3249   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3250                             PP, Tok.getKind());
3251   if (Literal.hadError())
3252     return ExprError();
3253 
3254   QualType Ty;
3255   if (Literal.isWide())
3256     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3257   else if (Literal.isUTF8() && getLangOpts().Char8)
3258     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3259   else if (Literal.isUTF16())
3260     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3261   else if (Literal.isUTF32())
3262     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3263   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3264     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3265   else
3266     Ty = Context.CharTy;  // 'x' -> char in C++
3267 
3268   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3269   if (Literal.isWide())
3270     Kind = CharacterLiteral::Wide;
3271   else if (Literal.isUTF16())
3272     Kind = CharacterLiteral::UTF16;
3273   else if (Literal.isUTF32())
3274     Kind = CharacterLiteral::UTF32;
3275   else if (Literal.isUTF8())
3276     Kind = CharacterLiteral::UTF8;
3277 
3278   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3279                                              Tok.getLocation());
3280 
3281   if (Literal.getUDSuffix().empty())
3282     return Lit;
3283 
3284   // We're building a user-defined literal.
3285   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3286   SourceLocation UDSuffixLoc =
3287     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3288 
3289   // Make sure we're allowed user-defined literals here.
3290   if (!UDLScope)
3291     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3292 
3293   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3294   //   operator "" X (ch)
3295   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3296                                         Lit, Tok.getLocation());
3297 }
3298 
3299 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3300   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3301   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3302                                 Context.IntTy, Loc);
3303 }
3304 
3305 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3306                                   QualType Ty, SourceLocation Loc) {
3307   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3308 
3309   using llvm::APFloat;
3310   APFloat Val(Format);
3311 
3312   APFloat::opStatus result = Literal.GetFloatValue(Val);
3313 
3314   // Overflow is always an error, but underflow is only an error if
3315   // we underflowed to zero (APFloat reports denormals as underflow).
3316   if ((result & APFloat::opOverflow) ||
3317       ((result & APFloat::opUnderflow) && Val.isZero())) {
3318     unsigned diagnostic;
3319     SmallString<20> buffer;
3320     if (result & APFloat::opOverflow) {
3321       diagnostic = diag::warn_float_overflow;
3322       APFloat::getLargest(Format).toString(buffer);
3323     } else {
3324       diagnostic = diag::warn_float_underflow;
3325       APFloat::getSmallest(Format).toString(buffer);
3326     }
3327 
3328     S.Diag(Loc, diagnostic)
3329       << Ty
3330       << StringRef(buffer.data(), buffer.size());
3331   }
3332 
3333   bool isExact = (result == APFloat::opOK);
3334   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3335 }
3336 
3337 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3338   assert(E && "Invalid expression");
3339 
3340   if (E->isValueDependent())
3341     return false;
3342 
3343   QualType QT = E->getType();
3344   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3345     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3346     return true;
3347   }
3348 
3349   llvm::APSInt ValueAPS;
3350   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3351 
3352   if (R.isInvalid())
3353     return true;
3354 
3355   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3356   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3357     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3358         << ValueAPS.toString(10) << ValueIsPositive;
3359     return true;
3360   }
3361 
3362   return false;
3363 }
3364 
3365 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3366   // Fast path for a single digit (which is quite common).  A single digit
3367   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3368   if (Tok.getLength() == 1) {
3369     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3370     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3371   }
3372 
3373   SmallString<128> SpellingBuffer;
3374   // NumericLiteralParser wants to overread by one character.  Add padding to
3375   // the buffer in case the token is copied to the buffer.  If getSpelling()
3376   // returns a StringRef to the memory buffer, it should have a null char at
3377   // the EOF, so it is also safe.
3378   SpellingBuffer.resize(Tok.getLength() + 1);
3379 
3380   // Get the spelling of the token, which eliminates trigraphs, etc.
3381   bool Invalid = false;
3382   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3383   if (Invalid)
3384     return ExprError();
3385 
3386   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3387   if (Literal.hadError)
3388     return ExprError();
3389 
3390   if (Literal.hasUDSuffix()) {
3391     // We're building a user-defined literal.
3392     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3393     SourceLocation UDSuffixLoc =
3394       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3395 
3396     // Make sure we're allowed user-defined literals here.
3397     if (!UDLScope)
3398       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3399 
3400     QualType CookedTy;
3401     if (Literal.isFloatingLiteral()) {
3402       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3403       // long double, the literal is treated as a call of the form
3404       //   operator "" X (f L)
3405       CookedTy = Context.LongDoubleTy;
3406     } else {
3407       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3408       // unsigned long long, the literal is treated as a call of the form
3409       //   operator "" X (n ULL)
3410       CookedTy = Context.UnsignedLongLongTy;
3411     }
3412 
3413     DeclarationName OpName =
3414       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3415     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3416     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3417 
3418     SourceLocation TokLoc = Tok.getLocation();
3419 
3420     // Perform literal operator lookup to determine if we're building a raw
3421     // literal or a cooked one.
3422     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3423     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3424                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3425                                   /*AllowStringTemplate*/ false,
3426                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3427     case LOLR_ErrorNoDiagnostic:
3428       // Lookup failure for imaginary constants isn't fatal, there's still the
3429       // GNU extension producing _Complex types.
3430       break;
3431     case LOLR_Error:
3432       return ExprError();
3433     case LOLR_Cooked: {
3434       Expr *Lit;
3435       if (Literal.isFloatingLiteral()) {
3436         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3437       } else {
3438         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3439         if (Literal.GetIntegerValue(ResultVal))
3440           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3441               << /* Unsigned */ 1;
3442         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3443                                      Tok.getLocation());
3444       }
3445       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3446     }
3447 
3448     case LOLR_Raw: {
3449       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3450       // literal is treated as a call of the form
3451       //   operator "" X ("n")
3452       unsigned Length = Literal.getUDSuffixOffset();
3453       QualType StrTy = Context.getConstantArrayType(
3454           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3455           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3456       Expr *Lit = StringLiteral::Create(
3457           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3458           /*Pascal*/false, StrTy, &TokLoc, 1);
3459       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3460     }
3461 
3462     case LOLR_Template: {
3463       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3464       // template), L is treated as a call fo the form
3465       //   operator "" X <'c1', 'c2', ... 'ck'>()
3466       // where n is the source character sequence c1 c2 ... ck.
3467       TemplateArgumentListInfo ExplicitArgs;
3468       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3469       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3470       llvm::APSInt Value(CharBits, CharIsUnsigned);
3471       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3472         Value = TokSpelling[I];
3473         TemplateArgument Arg(Context, Value, Context.CharTy);
3474         TemplateArgumentLocInfo ArgInfo;
3475         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3476       }
3477       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3478                                       &ExplicitArgs);
3479     }
3480     case LOLR_StringTemplate:
3481       llvm_unreachable("unexpected literal operator lookup result");
3482     }
3483   }
3484 
3485   Expr *Res;
3486 
3487   if (Literal.isFixedPointLiteral()) {
3488     QualType Ty;
3489 
3490     if (Literal.isAccum) {
3491       if (Literal.isHalf) {
3492         Ty = Context.ShortAccumTy;
3493       } else if (Literal.isLong) {
3494         Ty = Context.LongAccumTy;
3495       } else {
3496         Ty = Context.AccumTy;
3497       }
3498     } else if (Literal.isFract) {
3499       if (Literal.isHalf) {
3500         Ty = Context.ShortFractTy;
3501       } else if (Literal.isLong) {
3502         Ty = Context.LongFractTy;
3503       } else {
3504         Ty = Context.FractTy;
3505       }
3506     }
3507 
3508     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3509 
3510     bool isSigned = !Literal.isUnsigned;
3511     unsigned scale = Context.getFixedPointScale(Ty);
3512     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3513 
3514     llvm::APInt Val(bit_width, 0, isSigned);
3515     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3516     bool ValIsZero = Val.isNullValue() && !Overflowed;
3517 
3518     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3519     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3520       // Clause 6.4.4 - The value of a constant shall be in the range of
3521       // representable values for its type, with exception for constants of a
3522       // fract type with a value of exactly 1; such a constant shall denote
3523       // the maximal value for the type.
3524       --Val;
3525     else if (Val.ugt(MaxVal) || Overflowed)
3526       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3527 
3528     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3529                                               Tok.getLocation(), scale);
3530   } else if (Literal.isFloatingLiteral()) {
3531     QualType Ty;
3532     if (Literal.isHalf){
3533       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3534         Ty = Context.HalfTy;
3535       else {
3536         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3537         return ExprError();
3538       }
3539     } else if (Literal.isFloat)
3540       Ty = Context.FloatTy;
3541     else if (Literal.isLong)
3542       Ty = Context.LongDoubleTy;
3543     else if (Literal.isFloat16)
3544       Ty = Context.Float16Ty;
3545     else if (Literal.isFloat128)
3546       Ty = Context.Float128Ty;
3547     else
3548       Ty = Context.DoubleTy;
3549 
3550     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3551 
3552     if (Ty == Context.DoubleTy) {
3553       if (getLangOpts().SinglePrecisionConstants) {
3554         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3555         if (BTy->getKind() != BuiltinType::Float) {
3556           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3557         }
3558       } else if (getLangOpts().OpenCL &&
3559                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3560         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3561         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3562         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3563       }
3564     }
3565   } else if (!Literal.isIntegerLiteral()) {
3566     return ExprError();
3567   } else {
3568     QualType Ty;
3569 
3570     // 'long long' is a C99 or C++11 feature.
3571     if (!getLangOpts().C99 && Literal.isLongLong) {
3572       if (getLangOpts().CPlusPlus)
3573         Diag(Tok.getLocation(),
3574              getLangOpts().CPlusPlus11 ?
3575              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3576       else
3577         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3578     }
3579 
3580     // Get the value in the widest-possible width.
3581     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3582     llvm::APInt ResultVal(MaxWidth, 0);
3583 
3584     if (Literal.GetIntegerValue(ResultVal)) {
3585       // If this value didn't fit into uintmax_t, error and force to ull.
3586       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3587           << /* Unsigned */ 1;
3588       Ty = Context.UnsignedLongLongTy;
3589       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3590              "long long is not intmax_t?");
3591     } else {
3592       // If this value fits into a ULL, try to figure out what else it fits into
3593       // according to the rules of C99 6.4.4.1p5.
3594 
3595       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3596       // be an unsigned int.
3597       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3598 
3599       // Check from smallest to largest, picking the smallest type we can.
3600       unsigned Width = 0;
3601 
3602       // Microsoft specific integer suffixes are explicitly sized.
3603       if (Literal.MicrosoftInteger) {
3604         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3605           Width = 8;
3606           Ty = Context.CharTy;
3607         } else {
3608           Width = Literal.MicrosoftInteger;
3609           Ty = Context.getIntTypeForBitwidth(Width,
3610                                              /*Signed=*/!Literal.isUnsigned);
3611         }
3612       }
3613 
3614       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3615         // Are int/unsigned possibilities?
3616         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3617 
3618         // Does it fit in a unsigned int?
3619         if (ResultVal.isIntN(IntSize)) {
3620           // Does it fit in a signed int?
3621           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3622             Ty = Context.IntTy;
3623           else if (AllowUnsigned)
3624             Ty = Context.UnsignedIntTy;
3625           Width = IntSize;
3626         }
3627       }
3628 
3629       // Are long/unsigned long possibilities?
3630       if (Ty.isNull() && !Literal.isLongLong) {
3631         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3632 
3633         // Does it fit in a unsigned long?
3634         if (ResultVal.isIntN(LongSize)) {
3635           // Does it fit in a signed long?
3636           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3637             Ty = Context.LongTy;
3638           else if (AllowUnsigned)
3639             Ty = Context.UnsignedLongTy;
3640           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3641           // is compatible.
3642           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3643             const unsigned LongLongSize =
3644                 Context.getTargetInfo().getLongLongWidth();
3645             Diag(Tok.getLocation(),
3646                  getLangOpts().CPlusPlus
3647                      ? Literal.isLong
3648                            ? diag::warn_old_implicitly_unsigned_long_cxx
3649                            : /*C++98 UB*/ diag::
3650                                  ext_old_implicitly_unsigned_long_cxx
3651                      : diag::warn_old_implicitly_unsigned_long)
3652                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3653                                             : /*will be ill-formed*/ 1);
3654             Ty = Context.UnsignedLongTy;
3655           }
3656           Width = LongSize;
3657         }
3658       }
3659 
3660       // Check long long if needed.
3661       if (Ty.isNull()) {
3662         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3663 
3664         // Does it fit in a unsigned long long?
3665         if (ResultVal.isIntN(LongLongSize)) {
3666           // Does it fit in a signed long long?
3667           // To be compatible with MSVC, hex integer literals ending with the
3668           // LL or i64 suffix are always signed in Microsoft mode.
3669           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3670               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3671             Ty = Context.LongLongTy;
3672           else if (AllowUnsigned)
3673             Ty = Context.UnsignedLongLongTy;
3674           Width = LongLongSize;
3675         }
3676       }
3677 
3678       // If we still couldn't decide a type, we probably have something that
3679       // does not fit in a signed long long, but has no U suffix.
3680       if (Ty.isNull()) {
3681         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3682         Ty = Context.UnsignedLongLongTy;
3683         Width = Context.getTargetInfo().getLongLongWidth();
3684       }
3685 
3686       if (ResultVal.getBitWidth() != Width)
3687         ResultVal = ResultVal.trunc(Width);
3688     }
3689     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3690   }
3691 
3692   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3693   if (Literal.isImaginary) {
3694     Res = new (Context) ImaginaryLiteral(Res,
3695                                         Context.getComplexType(Res->getType()));
3696 
3697     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3698   }
3699   return Res;
3700 }
3701 
3702 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3703   assert(E && "ActOnParenExpr() missing expr");
3704   return new (Context) ParenExpr(L, R, E);
3705 }
3706 
3707 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3708                                          SourceLocation Loc,
3709                                          SourceRange ArgRange) {
3710   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3711   // scalar or vector data type argument..."
3712   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3713   // type (C99 6.2.5p18) or void.
3714   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3715     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3716       << T << ArgRange;
3717     return true;
3718   }
3719 
3720   assert((T->isVoidType() || !T->isIncompleteType()) &&
3721          "Scalar types should always be complete");
3722   return false;
3723 }
3724 
3725 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3726                                            SourceLocation Loc,
3727                                            SourceRange ArgRange,
3728                                            UnaryExprOrTypeTrait TraitKind) {
3729   // Invalid types must be hard errors for SFINAE in C++.
3730   if (S.LangOpts.CPlusPlus)
3731     return true;
3732 
3733   // C99 6.5.3.4p1:
3734   if (T->isFunctionType() &&
3735       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3736        TraitKind == UETT_PreferredAlignOf)) {
3737     // sizeof(function)/alignof(function) is allowed as an extension.
3738     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3739       << TraitKind << ArgRange;
3740     return false;
3741   }
3742 
3743   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3744   // this is an error (OpenCL v1.1 s6.3.k)
3745   if (T->isVoidType()) {
3746     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3747                                         : diag::ext_sizeof_alignof_void_type;
3748     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3749     return false;
3750   }
3751 
3752   return true;
3753 }
3754 
3755 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3756                                              SourceLocation Loc,
3757                                              SourceRange ArgRange,
3758                                              UnaryExprOrTypeTrait TraitKind) {
3759   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3760   // runtime doesn't allow it.
3761   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3762     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3763       << T << (TraitKind == UETT_SizeOf)
3764       << ArgRange;
3765     return true;
3766   }
3767 
3768   return false;
3769 }
3770 
3771 /// Check whether E is a pointer from a decayed array type (the decayed
3772 /// pointer type is equal to T) and emit a warning if it is.
3773 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3774                                      Expr *E) {
3775   // Don't warn if the operation changed the type.
3776   if (T != E->getType())
3777     return;
3778 
3779   // Now look for array decays.
3780   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3781   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3782     return;
3783 
3784   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3785                                              << ICE->getType()
3786                                              << ICE->getSubExpr()->getType();
3787 }
3788 
3789 /// Check the constraints on expression operands to unary type expression
3790 /// and type traits.
3791 ///
3792 /// Completes any types necessary and validates the constraints on the operand
3793 /// expression. The logic mostly mirrors the type-based overload, but may modify
3794 /// the expression as it completes the type for that expression through template
3795 /// instantiation, etc.
3796 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3797                                             UnaryExprOrTypeTrait ExprKind) {
3798   QualType ExprTy = E->getType();
3799   assert(!ExprTy->isReferenceType());
3800 
3801   if (ExprKind == UETT_VecStep)
3802     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3803                                         E->getSourceRange());
3804 
3805   // Whitelist some types as extensions
3806   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3807                                       E->getSourceRange(), ExprKind))
3808     return false;
3809 
3810   // 'alignof' applied to an expression only requires the base element type of
3811   // the expression to be complete. 'sizeof' requires the expression's type to
3812   // be complete (and will attempt to complete it if it's an array of unknown
3813   // bound).
3814   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3815     if (RequireCompleteType(E->getExprLoc(),
3816                             Context.getBaseElementType(E->getType()),
3817                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3818                             E->getSourceRange()))
3819       return true;
3820   } else {
3821     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3822                                 ExprKind, E->getSourceRange()))
3823       return true;
3824   }
3825 
3826   // Completing the expression's type may have changed it.
3827   ExprTy = E->getType();
3828   assert(!ExprTy->isReferenceType());
3829 
3830   if (ExprTy->isFunctionType()) {
3831     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3832       << ExprKind << E->getSourceRange();
3833     return true;
3834   }
3835 
3836   // The operand for sizeof and alignof is in an unevaluated expression context,
3837   // so side effects could result in unintended consequences.
3838   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3839        ExprKind == UETT_PreferredAlignOf) &&
3840       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3841     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3842 
3843   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3844                                        E->getSourceRange(), ExprKind))
3845     return true;
3846 
3847   if (ExprKind == UETT_SizeOf) {
3848     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3849       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3850         QualType OType = PVD->getOriginalType();
3851         QualType Type = PVD->getType();
3852         if (Type->isPointerType() && OType->isArrayType()) {
3853           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3854             << Type << OType;
3855           Diag(PVD->getLocation(), diag::note_declared_at);
3856         }
3857       }
3858     }
3859 
3860     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3861     // decays into a pointer and returns an unintended result. This is most
3862     // likely a typo for "sizeof(array) op x".
3863     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3864       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3865                                BO->getLHS());
3866       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3867                                BO->getRHS());
3868     }
3869   }
3870 
3871   return false;
3872 }
3873 
3874 /// Check the constraints on operands to unary expression and type
3875 /// traits.
3876 ///
3877 /// This will complete any types necessary, and validate the various constraints
3878 /// on those operands.
3879 ///
3880 /// The UsualUnaryConversions() function is *not* called by this routine.
3881 /// C99 6.3.2.1p[2-4] all state:
3882 ///   Except when it is the operand of the sizeof operator ...
3883 ///
3884 /// C++ [expr.sizeof]p4
3885 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3886 ///   standard conversions are not applied to the operand of sizeof.
3887 ///
3888 /// This policy is followed for all of the unary trait expressions.
3889 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3890                                             SourceLocation OpLoc,
3891                                             SourceRange ExprRange,
3892                                             UnaryExprOrTypeTrait ExprKind) {
3893   if (ExprType->isDependentType())
3894     return false;
3895 
3896   // C++ [expr.sizeof]p2:
3897   //     When applied to a reference or a reference type, the result
3898   //     is the size of the referenced type.
3899   // C++11 [expr.alignof]p3:
3900   //     When alignof is applied to a reference type, the result
3901   //     shall be the alignment of the referenced type.
3902   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3903     ExprType = Ref->getPointeeType();
3904 
3905   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3906   //   When alignof or _Alignof is applied to an array type, the result
3907   //   is the alignment of the element type.
3908   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3909       ExprKind == UETT_OpenMPRequiredSimdAlign)
3910     ExprType = Context.getBaseElementType(ExprType);
3911 
3912   if (ExprKind == UETT_VecStep)
3913     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3914 
3915   // Whitelist some types as extensions
3916   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3917                                       ExprKind))
3918     return false;
3919 
3920   if (RequireCompleteType(OpLoc, ExprType,
3921                           diag::err_sizeof_alignof_incomplete_type,
3922                           ExprKind, ExprRange))
3923     return true;
3924 
3925   if (ExprType->isFunctionType()) {
3926     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3927       << ExprKind << ExprRange;
3928     return true;
3929   }
3930 
3931   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3932                                        ExprKind))
3933     return true;
3934 
3935   return false;
3936 }
3937 
3938 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3939   E = E->IgnoreParens();
3940 
3941   // Cannot know anything else if the expression is dependent.
3942   if (E->isTypeDependent())
3943     return false;
3944 
3945   if (E->getObjectKind() == OK_BitField) {
3946     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3947        << 1 << E->getSourceRange();
3948     return true;
3949   }
3950 
3951   ValueDecl *D = nullptr;
3952   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3953     D = DRE->getDecl();
3954   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3955     D = ME->getMemberDecl();
3956   }
3957 
3958   // If it's a field, require the containing struct to have a
3959   // complete definition so that we can compute the layout.
3960   //
3961   // This can happen in C++11 onwards, either by naming the member
3962   // in a way that is not transformed into a member access expression
3963   // (in an unevaluated operand, for instance), or by naming the member
3964   // in a trailing-return-type.
3965   //
3966   // For the record, since __alignof__ on expressions is a GCC
3967   // extension, GCC seems to permit this but always gives the
3968   // nonsensical answer 0.
3969   //
3970   // We don't really need the layout here --- we could instead just
3971   // directly check for all the appropriate alignment-lowing
3972   // attributes --- but that would require duplicating a lot of
3973   // logic that just isn't worth duplicating for such a marginal
3974   // use-case.
3975   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3976     // Fast path this check, since we at least know the record has a
3977     // definition if we can find a member of it.
3978     if (!FD->getParent()->isCompleteDefinition()) {
3979       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3980         << E->getSourceRange();
3981       return true;
3982     }
3983 
3984     // Otherwise, if it's a field, and the field doesn't have
3985     // reference type, then it must have a complete type (or be a
3986     // flexible array member, which we explicitly want to
3987     // white-list anyway), which makes the following checks trivial.
3988     if (!FD->getType()->isReferenceType())
3989       return false;
3990   }
3991 
3992   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3993 }
3994 
3995 bool Sema::CheckVecStepExpr(Expr *E) {
3996   E = E->IgnoreParens();
3997 
3998   // Cannot know anything else if the expression is dependent.
3999   if (E->isTypeDependent())
4000     return false;
4001 
4002   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4003 }
4004 
4005 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4006                                         CapturingScopeInfo *CSI) {
4007   assert(T->isVariablyModifiedType());
4008   assert(CSI != nullptr);
4009 
4010   // We're going to walk down into the type and look for VLA expressions.
4011   do {
4012     const Type *Ty = T.getTypePtr();
4013     switch (Ty->getTypeClass()) {
4014 #define TYPE(Class, Base)
4015 #define ABSTRACT_TYPE(Class, Base)
4016 #define NON_CANONICAL_TYPE(Class, Base)
4017 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4018 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4019 #include "clang/AST/TypeNodes.def"
4020       T = QualType();
4021       break;
4022     // These types are never variably-modified.
4023     case Type::Builtin:
4024     case Type::Complex:
4025     case Type::Vector:
4026     case Type::ExtVector:
4027     case Type::Record:
4028     case Type::Enum:
4029     case Type::Elaborated:
4030     case Type::TemplateSpecialization:
4031     case Type::ObjCObject:
4032     case Type::ObjCInterface:
4033     case Type::ObjCObjectPointer:
4034     case Type::ObjCTypeParam:
4035     case Type::Pipe:
4036       llvm_unreachable("type class is never variably-modified!");
4037     case Type::Adjusted:
4038       T = cast<AdjustedType>(Ty)->getOriginalType();
4039       break;
4040     case Type::Decayed:
4041       T = cast<DecayedType>(Ty)->getPointeeType();
4042       break;
4043     case Type::Pointer:
4044       T = cast<PointerType>(Ty)->getPointeeType();
4045       break;
4046     case Type::BlockPointer:
4047       T = cast<BlockPointerType>(Ty)->getPointeeType();
4048       break;
4049     case Type::LValueReference:
4050     case Type::RValueReference:
4051       T = cast<ReferenceType>(Ty)->getPointeeType();
4052       break;
4053     case Type::MemberPointer:
4054       T = cast<MemberPointerType>(Ty)->getPointeeType();
4055       break;
4056     case Type::ConstantArray:
4057     case Type::IncompleteArray:
4058       // Losing element qualification here is fine.
4059       T = cast<ArrayType>(Ty)->getElementType();
4060       break;
4061     case Type::VariableArray: {
4062       // Losing element qualification here is fine.
4063       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4064 
4065       // Unknown size indication requires no size computation.
4066       // Otherwise, evaluate and record it.
4067       if (auto Size = VAT->getSizeExpr()) {
4068         if (!CSI->isVLATypeCaptured(VAT)) {
4069           RecordDecl *CapRecord = nullptr;
4070           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
4071             CapRecord = LSI->Lambda;
4072           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
4073             CapRecord = CRSI->TheRecordDecl;
4074           }
4075           if (CapRecord) {
4076             auto ExprLoc = Size->getExprLoc();
4077             auto SizeType = Context.getSizeType();
4078             // Build the non-static data member.
4079             auto Field =
4080                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
4081                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
4082                                   /*BW*/ nullptr, /*Mutable*/ false,
4083                                   /*InitStyle*/ ICIS_NoInit);
4084             Field->setImplicit(true);
4085             Field->setAccess(AS_private);
4086             Field->setCapturedVLAType(VAT);
4087             CapRecord->addDecl(Field);
4088 
4089             CSI->addVLATypeCapture(ExprLoc, SizeType);
4090           }
4091         }
4092       }
4093       T = VAT->getElementType();
4094       break;
4095     }
4096     case Type::FunctionProto:
4097     case Type::FunctionNoProto:
4098       T = cast<FunctionType>(Ty)->getReturnType();
4099       break;
4100     case Type::Paren:
4101     case Type::TypeOf:
4102     case Type::UnaryTransform:
4103     case Type::Attributed:
4104     case Type::SubstTemplateTypeParm:
4105     case Type::PackExpansion:
4106       // Keep walking after single level desugaring.
4107       T = T.getSingleStepDesugaredType(Context);
4108       break;
4109     case Type::Typedef:
4110       T = cast<TypedefType>(Ty)->desugar();
4111       break;
4112     case Type::Decltype:
4113       T = cast<DecltypeType>(Ty)->desugar();
4114       break;
4115     case Type::Auto:
4116     case Type::DeducedTemplateSpecialization:
4117       T = cast<DeducedType>(Ty)->getDeducedType();
4118       break;
4119     case Type::TypeOfExpr:
4120       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4121       break;
4122     case Type::Atomic:
4123       T = cast<AtomicType>(Ty)->getValueType();
4124       break;
4125     }
4126   } while (!T.isNull() && T->isVariablyModifiedType());
4127 }
4128 
4129 /// Build a sizeof or alignof expression given a type operand.
4130 ExprResult
4131 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4132                                      SourceLocation OpLoc,
4133                                      UnaryExprOrTypeTrait ExprKind,
4134                                      SourceRange R) {
4135   if (!TInfo)
4136     return ExprError();
4137 
4138   QualType T = TInfo->getType();
4139 
4140   if (!T->isDependentType() &&
4141       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4142     return ExprError();
4143 
4144   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4145     if (auto *TT = T->getAs<TypedefType>()) {
4146       for (auto I = FunctionScopes.rbegin(),
4147                 E = std::prev(FunctionScopes.rend());
4148            I != E; ++I) {
4149         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4150         if (CSI == nullptr)
4151           break;
4152         DeclContext *DC = nullptr;
4153         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4154           DC = LSI->CallOperator;
4155         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4156           DC = CRSI->TheCapturedDecl;
4157         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4158           DC = BSI->TheDecl;
4159         if (DC) {
4160           if (DC->containsDecl(TT->getDecl()))
4161             break;
4162           captureVariablyModifiedType(Context, T, CSI);
4163         }
4164       }
4165     }
4166   }
4167 
4168   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4169   return new (Context) UnaryExprOrTypeTraitExpr(
4170       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4171 }
4172 
4173 /// Build a sizeof or alignof expression given an expression
4174 /// operand.
4175 ExprResult
4176 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4177                                      UnaryExprOrTypeTrait ExprKind) {
4178   ExprResult PE = CheckPlaceholderExpr(E);
4179   if (PE.isInvalid())
4180     return ExprError();
4181 
4182   E = PE.get();
4183 
4184   // Verify that the operand is valid.
4185   bool isInvalid = false;
4186   if (E->isTypeDependent()) {
4187     // Delay type-checking for type-dependent expressions.
4188   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4189     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4190   } else if (ExprKind == UETT_VecStep) {
4191     isInvalid = CheckVecStepExpr(E);
4192   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4193       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4194       isInvalid = true;
4195   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4196     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4197     isInvalid = true;
4198   } else {
4199     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4200   }
4201 
4202   if (isInvalid)
4203     return ExprError();
4204 
4205   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4206     PE = TransformToPotentiallyEvaluated(E);
4207     if (PE.isInvalid()) return ExprError();
4208     E = PE.get();
4209   }
4210 
4211   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4212   return new (Context) UnaryExprOrTypeTraitExpr(
4213       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4214 }
4215 
4216 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4217 /// expr and the same for @c alignof and @c __alignof
4218 /// Note that the ArgRange is invalid if isType is false.
4219 ExprResult
4220 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4221                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4222                                     void *TyOrEx, SourceRange ArgRange) {
4223   // If error parsing type, ignore.
4224   if (!TyOrEx) return ExprError();
4225 
4226   if (IsType) {
4227     TypeSourceInfo *TInfo;
4228     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4229     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4230   }
4231 
4232   Expr *ArgEx = (Expr *)TyOrEx;
4233   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4234   return Result;
4235 }
4236 
4237 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4238                                      bool IsReal) {
4239   if (V.get()->isTypeDependent())
4240     return S.Context.DependentTy;
4241 
4242   // _Real and _Imag are only l-values for normal l-values.
4243   if (V.get()->getObjectKind() != OK_Ordinary) {
4244     V = S.DefaultLvalueConversion(V.get());
4245     if (V.isInvalid())
4246       return QualType();
4247   }
4248 
4249   // These operators return the element type of a complex type.
4250   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4251     return CT->getElementType();
4252 
4253   // Otherwise they pass through real integer and floating point types here.
4254   if (V.get()->getType()->isArithmeticType())
4255     return V.get()->getType();
4256 
4257   // Test for placeholders.
4258   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4259   if (PR.isInvalid()) return QualType();
4260   if (PR.get() != V.get()) {
4261     V = PR;
4262     return CheckRealImagOperand(S, V, Loc, IsReal);
4263   }
4264 
4265   // Reject anything else.
4266   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4267     << (IsReal ? "__real" : "__imag");
4268   return QualType();
4269 }
4270 
4271 
4272 
4273 ExprResult
4274 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4275                           tok::TokenKind Kind, Expr *Input) {
4276   UnaryOperatorKind Opc;
4277   switch (Kind) {
4278   default: llvm_unreachable("Unknown unary op!");
4279   case tok::plusplus:   Opc = UO_PostInc; break;
4280   case tok::minusminus: Opc = UO_PostDec; break;
4281   }
4282 
4283   // Since this might is a postfix expression, get rid of ParenListExprs.
4284   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4285   if (Result.isInvalid()) return ExprError();
4286   Input = Result.get();
4287 
4288   return BuildUnaryOp(S, OpLoc, Opc, Input);
4289 }
4290 
4291 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4292 ///
4293 /// \return true on error
4294 static bool checkArithmeticOnObjCPointer(Sema &S,
4295                                          SourceLocation opLoc,
4296                                          Expr *op) {
4297   assert(op->getType()->isObjCObjectPointerType());
4298   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4299       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4300     return false;
4301 
4302   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4303     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4304     << op->getSourceRange();
4305   return true;
4306 }
4307 
4308 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4309   auto *BaseNoParens = Base->IgnoreParens();
4310   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4311     return MSProp->getPropertyDecl()->getType()->isArrayType();
4312   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4313 }
4314 
4315 ExprResult
4316 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4317                               Expr *idx, SourceLocation rbLoc) {
4318   if (base && !base->getType().isNull() &&
4319       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4320     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4321                                     /*Length=*/nullptr, rbLoc);
4322 
4323   // Since this might be a postfix expression, get rid of ParenListExprs.
4324   if (isa<ParenListExpr>(base)) {
4325     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4326     if (result.isInvalid()) return ExprError();
4327     base = result.get();
4328   }
4329 
4330   // Handle any non-overload placeholder types in the base and index
4331   // expressions.  We can't handle overloads here because the other
4332   // operand might be an overloadable type, in which case the overload
4333   // resolution for the operator overload should get the first crack
4334   // at the overload.
4335   bool IsMSPropertySubscript = false;
4336   if (base->getType()->isNonOverloadPlaceholderType()) {
4337     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4338     if (!IsMSPropertySubscript) {
4339       ExprResult result = CheckPlaceholderExpr(base);
4340       if (result.isInvalid())
4341         return ExprError();
4342       base = result.get();
4343     }
4344   }
4345   if (idx->getType()->isNonOverloadPlaceholderType()) {
4346     ExprResult result = CheckPlaceholderExpr(idx);
4347     if (result.isInvalid()) return ExprError();
4348     idx = result.get();
4349   }
4350 
4351   // Build an unanalyzed expression if either operand is type-dependent.
4352   if (getLangOpts().CPlusPlus &&
4353       (base->isTypeDependent() || idx->isTypeDependent())) {
4354     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4355                                             VK_LValue, OK_Ordinary, rbLoc);
4356   }
4357 
4358   // MSDN, property (C++)
4359   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4360   // This attribute can also be used in the declaration of an empty array in a
4361   // class or structure definition. For example:
4362   // __declspec(property(get=GetX, put=PutX)) int x[];
4363   // The above statement indicates that x[] can be used with one or more array
4364   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4365   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4366   if (IsMSPropertySubscript) {
4367     // Build MS property subscript expression if base is MS property reference
4368     // or MS property subscript.
4369     return new (Context) MSPropertySubscriptExpr(
4370         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4371   }
4372 
4373   // Use C++ overloaded-operator rules if either operand has record
4374   // type.  The spec says to do this if either type is *overloadable*,
4375   // but enum types can't declare subscript operators or conversion
4376   // operators, so there's nothing interesting for overload resolution
4377   // to do if there aren't any record types involved.
4378   //
4379   // ObjC pointers have their own subscripting logic that is not tied
4380   // to overload resolution and so should not take this path.
4381   if (getLangOpts().CPlusPlus &&
4382       (base->getType()->isRecordType() ||
4383        (!base->getType()->isObjCObjectPointerType() &&
4384         idx->getType()->isRecordType()))) {
4385     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4386   }
4387 
4388   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4389 
4390   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4391     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4392 
4393   return Res;
4394 }
4395 
4396 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4397   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4398   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4399 
4400   // For expressions like `&(*s).b`, the base is recorded and what should be
4401   // checked.
4402   const MemberExpr *Member = nullptr;
4403   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4404     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4405 
4406   LastRecord.PossibleDerefs.erase(StrippedExpr);
4407 }
4408 
4409 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4410   QualType ResultTy = E->getType();
4411   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4412 
4413   // Bail if the element is an array since it is not memory access.
4414   if (isa<ArrayType>(ResultTy))
4415     return;
4416 
4417   if (ResultTy->hasAttr(attr::NoDeref)) {
4418     LastRecord.PossibleDerefs.insert(E);
4419     return;
4420   }
4421 
4422   // Check if the base type is a pointer to a member access of a struct
4423   // marked with noderef.
4424   const Expr *Base = E->getBase();
4425   QualType BaseTy = Base->getType();
4426   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4427     // Not a pointer access
4428     return;
4429 
4430   const MemberExpr *Member = nullptr;
4431   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4432          Member->isArrow())
4433     Base = Member->getBase();
4434 
4435   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4436     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4437       LastRecord.PossibleDerefs.insert(E);
4438   }
4439 }
4440 
4441 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4442                                           Expr *LowerBound,
4443                                           SourceLocation ColonLoc, Expr *Length,
4444                                           SourceLocation RBLoc) {
4445   if (Base->getType()->isPlaceholderType() &&
4446       !Base->getType()->isSpecificPlaceholderType(
4447           BuiltinType::OMPArraySection)) {
4448     ExprResult Result = CheckPlaceholderExpr(Base);
4449     if (Result.isInvalid())
4450       return ExprError();
4451     Base = Result.get();
4452   }
4453   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4454     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4455     if (Result.isInvalid())
4456       return ExprError();
4457     Result = DefaultLvalueConversion(Result.get());
4458     if (Result.isInvalid())
4459       return ExprError();
4460     LowerBound = Result.get();
4461   }
4462   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4463     ExprResult Result = CheckPlaceholderExpr(Length);
4464     if (Result.isInvalid())
4465       return ExprError();
4466     Result = DefaultLvalueConversion(Result.get());
4467     if (Result.isInvalid())
4468       return ExprError();
4469     Length = Result.get();
4470   }
4471 
4472   // Build an unanalyzed expression if either operand is type-dependent.
4473   if (Base->isTypeDependent() ||
4474       (LowerBound &&
4475        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4476       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4477     return new (Context)
4478         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4479                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4480   }
4481 
4482   // Perform default conversions.
4483   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4484   QualType ResultTy;
4485   if (OriginalTy->isAnyPointerType()) {
4486     ResultTy = OriginalTy->getPointeeType();
4487   } else if (OriginalTy->isArrayType()) {
4488     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4489   } else {
4490     return ExprError(
4491         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4492         << Base->getSourceRange());
4493   }
4494   // C99 6.5.2.1p1
4495   if (LowerBound) {
4496     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4497                                                       LowerBound);
4498     if (Res.isInvalid())
4499       return ExprError(Diag(LowerBound->getExprLoc(),
4500                             diag::err_omp_typecheck_section_not_integer)
4501                        << 0 << LowerBound->getSourceRange());
4502     LowerBound = Res.get();
4503 
4504     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4505         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4506       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4507           << 0 << LowerBound->getSourceRange();
4508   }
4509   if (Length) {
4510     auto Res =
4511         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4512     if (Res.isInvalid())
4513       return ExprError(Diag(Length->getExprLoc(),
4514                             diag::err_omp_typecheck_section_not_integer)
4515                        << 1 << Length->getSourceRange());
4516     Length = Res.get();
4517 
4518     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4519         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4520       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4521           << 1 << Length->getSourceRange();
4522   }
4523 
4524   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4525   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4526   // type. Note that functions are not objects, and that (in C99 parlance)
4527   // incomplete types are not object types.
4528   if (ResultTy->isFunctionType()) {
4529     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4530         << ResultTy << Base->getSourceRange();
4531     return ExprError();
4532   }
4533 
4534   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4535                           diag::err_omp_section_incomplete_type, Base))
4536     return ExprError();
4537 
4538   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4539     Expr::EvalResult Result;
4540     if (LowerBound->EvaluateAsInt(Result, Context)) {
4541       // OpenMP 4.5, [2.4 Array Sections]
4542       // The array section must be a subset of the original array.
4543       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4544       if (LowerBoundValue.isNegative()) {
4545         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4546             << LowerBound->getSourceRange();
4547         return ExprError();
4548       }
4549     }
4550   }
4551 
4552   if (Length) {
4553     Expr::EvalResult Result;
4554     if (Length->EvaluateAsInt(Result, Context)) {
4555       // OpenMP 4.5, [2.4 Array Sections]
4556       // The length must evaluate to non-negative integers.
4557       llvm::APSInt LengthValue = Result.Val.getInt();
4558       if (LengthValue.isNegative()) {
4559         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4560             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4561             << Length->getSourceRange();
4562         return ExprError();
4563       }
4564     }
4565   } else if (ColonLoc.isValid() &&
4566              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4567                                       !OriginalTy->isVariableArrayType()))) {
4568     // OpenMP 4.5, [2.4 Array Sections]
4569     // When the size of the array dimension is not known, the length must be
4570     // specified explicitly.
4571     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4572         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4573     return ExprError();
4574   }
4575 
4576   if (!Base->getType()->isSpecificPlaceholderType(
4577           BuiltinType::OMPArraySection)) {
4578     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4579     if (Result.isInvalid())
4580       return ExprError();
4581     Base = Result.get();
4582   }
4583   return new (Context)
4584       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4585                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4586 }
4587 
4588 ExprResult
4589 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4590                                       Expr *Idx, SourceLocation RLoc) {
4591   Expr *LHSExp = Base;
4592   Expr *RHSExp = Idx;
4593 
4594   ExprValueKind VK = VK_LValue;
4595   ExprObjectKind OK = OK_Ordinary;
4596 
4597   // Per C++ core issue 1213, the result is an xvalue if either operand is
4598   // a non-lvalue array, and an lvalue otherwise.
4599   if (getLangOpts().CPlusPlus11) {
4600     for (auto *Op : {LHSExp, RHSExp}) {
4601       Op = Op->IgnoreImplicit();
4602       if (Op->getType()->isArrayType() && !Op->isLValue())
4603         VK = VK_XValue;
4604     }
4605   }
4606 
4607   // Perform default conversions.
4608   if (!LHSExp->getType()->getAs<VectorType>()) {
4609     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4610     if (Result.isInvalid())
4611       return ExprError();
4612     LHSExp = Result.get();
4613   }
4614   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4615   if (Result.isInvalid())
4616     return ExprError();
4617   RHSExp = Result.get();
4618 
4619   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4620 
4621   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4622   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4623   // in the subscript position. As a result, we need to derive the array base
4624   // and index from the expression types.
4625   Expr *BaseExpr, *IndexExpr;
4626   QualType ResultType;
4627   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4628     BaseExpr = LHSExp;
4629     IndexExpr = RHSExp;
4630     ResultType = Context.DependentTy;
4631   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4632     BaseExpr = LHSExp;
4633     IndexExpr = RHSExp;
4634     ResultType = PTy->getPointeeType();
4635   } else if (const ObjCObjectPointerType *PTy =
4636                LHSTy->getAs<ObjCObjectPointerType>()) {
4637     BaseExpr = LHSExp;
4638     IndexExpr = RHSExp;
4639 
4640     // Use custom logic if this should be the pseudo-object subscript
4641     // expression.
4642     if (!LangOpts.isSubscriptPointerArithmetic())
4643       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4644                                           nullptr);
4645 
4646     ResultType = PTy->getPointeeType();
4647   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4648      // Handle the uncommon case of "123[Ptr]".
4649     BaseExpr = RHSExp;
4650     IndexExpr = LHSExp;
4651     ResultType = PTy->getPointeeType();
4652   } else if (const ObjCObjectPointerType *PTy =
4653                RHSTy->getAs<ObjCObjectPointerType>()) {
4654      // Handle the uncommon case of "123[Ptr]".
4655     BaseExpr = RHSExp;
4656     IndexExpr = LHSExp;
4657     ResultType = PTy->getPointeeType();
4658     if (!LangOpts.isSubscriptPointerArithmetic()) {
4659       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4660         << ResultType << BaseExpr->getSourceRange();
4661       return ExprError();
4662     }
4663   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4664     BaseExpr = LHSExp;    // vectors: V[123]
4665     IndexExpr = RHSExp;
4666     // We apply C++ DR1213 to vector subscripting too.
4667     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4668       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4669       if (Materialized.isInvalid())
4670         return ExprError();
4671       LHSExp = Materialized.get();
4672     }
4673     VK = LHSExp->getValueKind();
4674     if (VK != VK_RValue)
4675       OK = OK_VectorComponent;
4676 
4677     ResultType = VTy->getElementType();
4678     QualType BaseType = BaseExpr->getType();
4679     Qualifiers BaseQuals = BaseType.getQualifiers();
4680     Qualifiers MemberQuals = ResultType.getQualifiers();
4681     Qualifiers Combined = BaseQuals + MemberQuals;
4682     if (Combined != MemberQuals)
4683       ResultType = Context.getQualifiedType(ResultType, Combined);
4684   } else if (LHSTy->isArrayType()) {
4685     // If we see an array that wasn't promoted by
4686     // DefaultFunctionArrayLvalueConversion, it must be an array that
4687     // wasn't promoted because of the C90 rule that doesn't
4688     // allow promoting non-lvalue arrays.  Warn, then
4689     // force the promotion here.
4690     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4691         << LHSExp->getSourceRange();
4692     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4693                                CK_ArrayToPointerDecay).get();
4694     LHSTy = LHSExp->getType();
4695 
4696     BaseExpr = LHSExp;
4697     IndexExpr = RHSExp;
4698     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4699   } else if (RHSTy->isArrayType()) {
4700     // Same as previous, except for 123[f().a] case
4701     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4702         << RHSExp->getSourceRange();
4703     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4704                                CK_ArrayToPointerDecay).get();
4705     RHSTy = RHSExp->getType();
4706 
4707     BaseExpr = RHSExp;
4708     IndexExpr = LHSExp;
4709     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4710   } else {
4711     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4712        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4713   }
4714   // C99 6.5.2.1p1
4715   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4716     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4717                      << IndexExpr->getSourceRange());
4718 
4719   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4720        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4721          && !IndexExpr->isTypeDependent())
4722     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4723 
4724   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4725   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4726   // type. Note that Functions are not objects, and that (in C99 parlance)
4727   // incomplete types are not object types.
4728   if (ResultType->isFunctionType()) {
4729     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4730         << ResultType << BaseExpr->getSourceRange();
4731     return ExprError();
4732   }
4733 
4734   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4735     // GNU extension: subscripting on pointer to void
4736     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4737       << BaseExpr->getSourceRange();
4738 
4739     // C forbids expressions of unqualified void type from being l-values.
4740     // See IsCForbiddenLValueType.
4741     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4742   } else if (!ResultType->isDependentType() &&
4743       RequireCompleteType(LLoc, ResultType,
4744                           diag::err_subscript_incomplete_type, BaseExpr))
4745     return ExprError();
4746 
4747   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4748          !ResultType.isCForbiddenLValueType());
4749 
4750   return new (Context)
4751       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4752 }
4753 
4754 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4755                                   ParmVarDecl *Param) {
4756   if (Param->hasUnparsedDefaultArg()) {
4757     Diag(CallLoc,
4758          diag::err_use_of_default_argument_to_function_declared_later) <<
4759       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4760     Diag(UnparsedDefaultArgLocs[Param],
4761          diag::note_default_argument_declared_here);
4762     return true;
4763   }
4764 
4765   if (Param->hasUninstantiatedDefaultArg()) {
4766     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4767 
4768     EnterExpressionEvaluationContext EvalContext(
4769         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4770 
4771     // Instantiate the expression.
4772     //
4773     // FIXME: Pass in a correct Pattern argument, otherwise
4774     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4775     //
4776     // template<typename T>
4777     // struct A {
4778     //   static int FooImpl();
4779     //
4780     //   template<typename Tp>
4781     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4782     //   // template argument list [[T], [Tp]], should be [[Tp]].
4783     //   friend A<Tp> Foo(int a);
4784     // };
4785     //
4786     // template<typename T>
4787     // A<T> Foo(int a = A<T>::FooImpl());
4788     MultiLevelTemplateArgumentList MutiLevelArgList
4789       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4790 
4791     InstantiatingTemplate Inst(*this, CallLoc, Param,
4792                                MutiLevelArgList.getInnermost());
4793     if (Inst.isInvalid())
4794       return true;
4795     if (Inst.isAlreadyInstantiating()) {
4796       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4797       Param->setInvalidDecl();
4798       return true;
4799     }
4800 
4801     ExprResult Result;
4802     {
4803       // C++ [dcl.fct.default]p5:
4804       //   The names in the [default argument] expression are bound, and
4805       //   the semantic constraints are checked, at the point where the
4806       //   default argument expression appears.
4807       ContextRAII SavedContext(*this, FD);
4808       LocalInstantiationScope Local(*this);
4809       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4810                                 /*DirectInit*/false);
4811     }
4812     if (Result.isInvalid())
4813       return true;
4814 
4815     // Check the expression as an initializer for the parameter.
4816     InitializedEntity Entity
4817       = InitializedEntity::InitializeParameter(Context, Param);
4818     InitializationKind Kind = InitializationKind::CreateCopy(
4819         Param->getLocation(),
4820         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4821     Expr *ResultE = Result.getAs<Expr>();
4822 
4823     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4824     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4825     if (Result.isInvalid())
4826       return true;
4827 
4828     Result =
4829         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4830                             /*DiscardedValue*/ false);
4831     if (Result.isInvalid())
4832       return true;
4833 
4834     // Remember the instantiated default argument.
4835     Param->setDefaultArg(Result.getAs<Expr>());
4836     if (ASTMutationListener *L = getASTMutationListener()) {
4837       L->DefaultArgumentInstantiated(Param);
4838     }
4839   }
4840 
4841   // If the default argument expression is not set yet, we are building it now.
4842   if (!Param->hasInit()) {
4843     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4844     Param->setInvalidDecl();
4845     return true;
4846   }
4847 
4848   // If the default expression creates temporaries, we need to
4849   // push them to the current stack of expression temporaries so they'll
4850   // be properly destroyed.
4851   // FIXME: We should really be rebuilding the default argument with new
4852   // bound temporaries; see the comment in PR5810.
4853   // We don't need to do that with block decls, though, because
4854   // blocks in default argument expression can never capture anything.
4855   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4856     // Set the "needs cleanups" bit regardless of whether there are
4857     // any explicit objects.
4858     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4859 
4860     // Append all the objects to the cleanup list.  Right now, this
4861     // should always be a no-op, because blocks in default argument
4862     // expressions should never be able to capture anything.
4863     assert(!Init->getNumObjects() &&
4864            "default argument expression has capturing blocks?");
4865   }
4866 
4867   // We already type-checked the argument, so we know it works.
4868   // Just mark all of the declarations in this potentially-evaluated expression
4869   // as being "referenced".
4870   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4871                                    /*SkipLocalVariables=*/true);
4872   return false;
4873 }
4874 
4875 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4876                                         FunctionDecl *FD, ParmVarDecl *Param) {
4877   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4878     return ExprError();
4879   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4880 }
4881 
4882 Sema::VariadicCallType
4883 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4884                           Expr *Fn) {
4885   if (Proto && Proto->isVariadic()) {
4886     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4887       return VariadicConstructor;
4888     else if (Fn && Fn->getType()->isBlockPointerType())
4889       return VariadicBlock;
4890     else if (FDecl) {
4891       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4892         if (Method->isInstance())
4893           return VariadicMethod;
4894     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4895       return VariadicMethod;
4896     return VariadicFunction;
4897   }
4898   return VariadicDoesNotApply;
4899 }
4900 
4901 namespace {
4902 class FunctionCallCCC : public FunctionCallFilterCCC {
4903 public:
4904   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4905                   unsigned NumArgs, MemberExpr *ME)
4906       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4907         FunctionName(FuncName) {}
4908 
4909   bool ValidateCandidate(const TypoCorrection &candidate) override {
4910     if (!candidate.getCorrectionSpecifier() ||
4911         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4912       return false;
4913     }
4914 
4915     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4916   }
4917 
4918 private:
4919   const IdentifierInfo *const FunctionName;
4920 };
4921 }
4922 
4923 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4924                                                FunctionDecl *FDecl,
4925                                                ArrayRef<Expr *> Args) {
4926   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4927   DeclarationName FuncName = FDecl->getDeclName();
4928   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4929 
4930   if (TypoCorrection Corrected = S.CorrectTypo(
4931           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4932           S.getScopeForContext(S.CurContext), nullptr,
4933           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4934                                              Args.size(), ME),
4935           Sema::CTK_ErrorRecovery)) {
4936     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4937       if (Corrected.isOverloaded()) {
4938         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4939         OverloadCandidateSet::iterator Best;
4940         for (NamedDecl *CD : Corrected) {
4941           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4942             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4943                                    OCS);
4944         }
4945         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4946         case OR_Success:
4947           ND = Best->FoundDecl;
4948           Corrected.setCorrectionDecl(ND);
4949           break;
4950         default:
4951           break;
4952         }
4953       }
4954       ND = ND->getUnderlyingDecl();
4955       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4956         return Corrected;
4957     }
4958   }
4959   return TypoCorrection();
4960 }
4961 
4962 /// ConvertArgumentsForCall - Converts the arguments specified in
4963 /// Args/NumArgs to the parameter types of the function FDecl with
4964 /// function prototype Proto. Call is the call expression itself, and
4965 /// Fn is the function expression. For a C++ member function, this
4966 /// routine does not attempt to convert the object argument. Returns
4967 /// true if the call is ill-formed.
4968 bool
4969 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4970                               FunctionDecl *FDecl,
4971                               const FunctionProtoType *Proto,
4972                               ArrayRef<Expr *> Args,
4973                               SourceLocation RParenLoc,
4974                               bool IsExecConfig) {
4975   // Bail out early if calling a builtin with custom typechecking.
4976   if (FDecl)
4977     if (unsigned ID = FDecl->getBuiltinID())
4978       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4979         return false;
4980 
4981   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4982   // assignment, to the types of the corresponding parameter, ...
4983   unsigned NumParams = Proto->getNumParams();
4984   bool Invalid = false;
4985   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4986   unsigned FnKind = Fn->getType()->isBlockPointerType()
4987                        ? 1 /* block */
4988                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4989                                        : 0 /* function */);
4990 
4991   // If too few arguments are available (and we don't have default
4992   // arguments for the remaining parameters), don't make the call.
4993   if (Args.size() < NumParams) {
4994     if (Args.size() < MinArgs) {
4995       TypoCorrection TC;
4996       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4997         unsigned diag_id =
4998             MinArgs == NumParams && !Proto->isVariadic()
4999                 ? diag::err_typecheck_call_too_few_args_suggest
5000                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5001         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5002                                         << static_cast<unsigned>(Args.size())
5003                                         << TC.getCorrectionRange());
5004       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5005         Diag(RParenLoc,
5006              MinArgs == NumParams && !Proto->isVariadic()
5007                  ? diag::err_typecheck_call_too_few_args_one
5008                  : diag::err_typecheck_call_too_few_args_at_least_one)
5009             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5010       else
5011         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5012                             ? diag::err_typecheck_call_too_few_args
5013                             : diag::err_typecheck_call_too_few_args_at_least)
5014             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5015             << Fn->getSourceRange();
5016 
5017       // Emit the location of the prototype.
5018       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5019         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5020 
5021       return true;
5022     }
5023     // We reserve space for the default arguments when we create
5024     // the call expression, before calling ConvertArgumentsForCall.
5025     assert((Call->getNumArgs() == NumParams) &&
5026            "We should have reserved space for the default arguments before!");
5027   }
5028 
5029   // If too many are passed and not variadic, error on the extras and drop
5030   // them.
5031   if (Args.size() > NumParams) {
5032     if (!Proto->isVariadic()) {
5033       TypoCorrection TC;
5034       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5035         unsigned diag_id =
5036             MinArgs == NumParams && !Proto->isVariadic()
5037                 ? diag::err_typecheck_call_too_many_args_suggest
5038                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5039         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5040                                         << static_cast<unsigned>(Args.size())
5041                                         << TC.getCorrectionRange());
5042       } else if (NumParams == 1 && FDecl &&
5043                  FDecl->getParamDecl(0)->getDeclName())
5044         Diag(Args[NumParams]->getBeginLoc(),
5045              MinArgs == NumParams
5046                  ? diag::err_typecheck_call_too_many_args_one
5047                  : diag::err_typecheck_call_too_many_args_at_most_one)
5048             << FnKind << FDecl->getParamDecl(0)
5049             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5050             << SourceRange(Args[NumParams]->getBeginLoc(),
5051                            Args.back()->getEndLoc());
5052       else
5053         Diag(Args[NumParams]->getBeginLoc(),
5054              MinArgs == NumParams
5055                  ? diag::err_typecheck_call_too_many_args
5056                  : diag::err_typecheck_call_too_many_args_at_most)
5057             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5058             << Fn->getSourceRange()
5059             << SourceRange(Args[NumParams]->getBeginLoc(),
5060                            Args.back()->getEndLoc());
5061 
5062       // Emit the location of the prototype.
5063       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5064         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5065 
5066       // This deletes the extra arguments.
5067       Call->shrinkNumArgs(NumParams);
5068       return true;
5069     }
5070   }
5071   SmallVector<Expr *, 8> AllArgs;
5072   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5073 
5074   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5075                                    AllArgs, CallType);
5076   if (Invalid)
5077     return true;
5078   unsigned TotalNumArgs = AllArgs.size();
5079   for (unsigned i = 0; i < TotalNumArgs; ++i)
5080     Call->setArg(i, AllArgs[i]);
5081 
5082   return false;
5083 }
5084 
5085 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5086                                   const FunctionProtoType *Proto,
5087                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5088                                   SmallVectorImpl<Expr *> &AllArgs,
5089                                   VariadicCallType CallType, bool AllowExplicit,
5090                                   bool IsListInitialization) {
5091   unsigned NumParams = Proto->getNumParams();
5092   bool Invalid = false;
5093   size_t ArgIx = 0;
5094   // Continue to check argument types (even if we have too few/many args).
5095   for (unsigned i = FirstParam; i < NumParams; i++) {
5096     QualType ProtoArgType = Proto->getParamType(i);
5097 
5098     Expr *Arg;
5099     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5100     if (ArgIx < Args.size()) {
5101       Arg = Args[ArgIx++];
5102 
5103       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5104                               diag::err_call_incomplete_argument, Arg))
5105         return true;
5106 
5107       // Strip the unbridged-cast placeholder expression off, if applicable.
5108       bool CFAudited = false;
5109       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5110           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5111           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5112         Arg = stripARCUnbridgedCast(Arg);
5113       else if (getLangOpts().ObjCAutoRefCount &&
5114                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5115                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5116         CFAudited = true;
5117 
5118       if (Proto->getExtParameterInfo(i).isNoEscape())
5119         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5120           BE->getBlockDecl()->setDoesNotEscape();
5121 
5122       InitializedEntity Entity =
5123           Param ? InitializedEntity::InitializeParameter(Context, Param,
5124                                                          ProtoArgType)
5125                 : InitializedEntity::InitializeParameter(
5126                       Context, ProtoArgType, Proto->isParamConsumed(i));
5127 
5128       // Remember that parameter belongs to a CF audited API.
5129       if (CFAudited)
5130         Entity.setParameterCFAudited();
5131 
5132       ExprResult ArgE = PerformCopyInitialization(
5133           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5134       if (ArgE.isInvalid())
5135         return true;
5136 
5137       Arg = ArgE.getAs<Expr>();
5138     } else {
5139       assert(Param && "can't use default arguments without a known callee");
5140 
5141       ExprResult ArgExpr =
5142         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5143       if (ArgExpr.isInvalid())
5144         return true;
5145 
5146       Arg = ArgExpr.getAs<Expr>();
5147     }
5148 
5149     // Check for array bounds violations for each argument to the call. This
5150     // check only triggers warnings when the argument isn't a more complex Expr
5151     // with its own checking, such as a BinaryOperator.
5152     CheckArrayAccess(Arg);
5153 
5154     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5155     CheckStaticArrayArgument(CallLoc, Param, Arg);
5156 
5157     AllArgs.push_back(Arg);
5158   }
5159 
5160   // If this is a variadic call, handle args passed through "...".
5161   if (CallType != VariadicDoesNotApply) {
5162     // Assume that extern "C" functions with variadic arguments that
5163     // return __unknown_anytype aren't *really* variadic.
5164     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5165         FDecl->isExternC()) {
5166       for (Expr *A : Args.slice(ArgIx)) {
5167         QualType paramType; // ignored
5168         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5169         Invalid |= arg.isInvalid();
5170         AllArgs.push_back(arg.get());
5171       }
5172 
5173     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5174     } else {
5175       for (Expr *A : Args.slice(ArgIx)) {
5176         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5177         Invalid |= Arg.isInvalid();
5178         AllArgs.push_back(Arg.get());
5179       }
5180     }
5181 
5182     // Check for array bounds violations.
5183     for (Expr *A : Args.slice(ArgIx))
5184       CheckArrayAccess(A);
5185   }
5186   return Invalid;
5187 }
5188 
5189 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5190   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5191   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5192     TL = DTL.getOriginalLoc();
5193   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5194     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5195       << ATL.getLocalSourceRange();
5196 }
5197 
5198 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5199 /// array parameter, check that it is non-null, and that if it is formed by
5200 /// array-to-pointer decay, the underlying array is sufficiently large.
5201 ///
5202 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5203 /// array type derivation, then for each call to the function, the value of the
5204 /// corresponding actual argument shall provide access to the first element of
5205 /// an array with at least as many elements as specified by the size expression.
5206 void
5207 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5208                                ParmVarDecl *Param,
5209                                const Expr *ArgExpr) {
5210   // Static array parameters are not supported in C++.
5211   if (!Param || getLangOpts().CPlusPlus)
5212     return;
5213 
5214   QualType OrigTy = Param->getOriginalType();
5215 
5216   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5217   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5218     return;
5219 
5220   if (ArgExpr->isNullPointerConstant(Context,
5221                                      Expr::NPC_NeverValueDependent)) {
5222     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5223     DiagnoseCalleeStaticArrayParam(*this, Param);
5224     return;
5225   }
5226 
5227   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5228   if (!CAT)
5229     return;
5230 
5231   const ConstantArrayType *ArgCAT =
5232     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5233   if (!ArgCAT)
5234     return;
5235 
5236   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5237                                              ArgCAT->getElementType())) {
5238     if (ArgCAT->getSize().ult(CAT->getSize())) {
5239       Diag(CallLoc, diag::warn_static_array_too_small)
5240           << ArgExpr->getSourceRange()
5241           << (unsigned)ArgCAT->getSize().getZExtValue()
5242           << (unsigned)CAT->getSize().getZExtValue() << 0;
5243       DiagnoseCalleeStaticArrayParam(*this, Param);
5244     }
5245     return;
5246   }
5247 
5248   Optional<CharUnits> ArgSize =
5249       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5250   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5251   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5252     Diag(CallLoc, diag::warn_static_array_too_small)
5253         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5254         << (unsigned)ParmSize->getQuantity() << 1;
5255     DiagnoseCalleeStaticArrayParam(*this, Param);
5256   }
5257 }
5258 
5259 /// Given a function expression of unknown-any type, try to rebuild it
5260 /// to have a function type.
5261 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5262 
5263 /// Is the given type a placeholder that we need to lower out
5264 /// immediately during argument processing?
5265 static bool isPlaceholderToRemoveAsArg(QualType type) {
5266   // Placeholders are never sugared.
5267   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5268   if (!placeholder) return false;
5269 
5270   switch (placeholder->getKind()) {
5271   // Ignore all the non-placeholder types.
5272 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5273   case BuiltinType::Id:
5274 #include "clang/Basic/OpenCLImageTypes.def"
5275 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5276   case BuiltinType::Id:
5277 #include "clang/Basic/OpenCLExtensionTypes.def"
5278 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5279 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5280 #include "clang/AST/BuiltinTypes.def"
5281     return false;
5282 
5283   // We cannot lower out overload sets; they might validly be resolved
5284   // by the call machinery.
5285   case BuiltinType::Overload:
5286     return false;
5287 
5288   // Unbridged casts in ARC can be handled in some call positions and
5289   // should be left in place.
5290   case BuiltinType::ARCUnbridgedCast:
5291     return false;
5292 
5293   // Pseudo-objects should be converted as soon as possible.
5294   case BuiltinType::PseudoObject:
5295     return true;
5296 
5297   // The debugger mode could theoretically but currently does not try
5298   // to resolve unknown-typed arguments based on known parameter types.
5299   case BuiltinType::UnknownAny:
5300     return true;
5301 
5302   // These are always invalid as call arguments and should be reported.
5303   case BuiltinType::BoundMember:
5304   case BuiltinType::BuiltinFn:
5305   case BuiltinType::OMPArraySection:
5306     return true;
5307 
5308   }
5309   llvm_unreachable("bad builtin type kind");
5310 }
5311 
5312 /// Check an argument list for placeholders that we won't try to
5313 /// handle later.
5314 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5315   // Apply this processing to all the arguments at once instead of
5316   // dying at the first failure.
5317   bool hasInvalid = false;
5318   for (size_t i = 0, e = args.size(); i != e; i++) {
5319     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5320       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5321       if (result.isInvalid()) hasInvalid = true;
5322       else args[i] = result.get();
5323     } else if (hasInvalid) {
5324       (void)S.CorrectDelayedTyposInExpr(args[i]);
5325     }
5326   }
5327   return hasInvalid;
5328 }
5329 
5330 /// If a builtin function has a pointer argument with no explicit address
5331 /// space, then it should be able to accept a pointer to any address
5332 /// space as input.  In order to do this, we need to replace the
5333 /// standard builtin declaration with one that uses the same address space
5334 /// as the call.
5335 ///
5336 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5337 ///                  it does not contain any pointer arguments without
5338 ///                  an address space qualifer.  Otherwise the rewritten
5339 ///                  FunctionDecl is returned.
5340 /// TODO: Handle pointer return types.
5341 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5342                                                 const FunctionDecl *FDecl,
5343                                                 MultiExprArg ArgExprs) {
5344 
5345   QualType DeclType = FDecl->getType();
5346   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5347 
5348   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5349       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5350     return nullptr;
5351 
5352   bool NeedsNewDecl = false;
5353   unsigned i = 0;
5354   SmallVector<QualType, 8> OverloadParams;
5355 
5356   for (QualType ParamType : FT->param_types()) {
5357 
5358     // Convert array arguments to pointer to simplify type lookup.
5359     ExprResult ArgRes =
5360         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5361     if (ArgRes.isInvalid())
5362       return nullptr;
5363     Expr *Arg = ArgRes.get();
5364     QualType ArgType = Arg->getType();
5365     if (!ParamType->isPointerType() ||
5366         ParamType.getQualifiers().hasAddressSpace() ||
5367         !ArgType->isPointerType() ||
5368         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5369       OverloadParams.push_back(ParamType);
5370       continue;
5371     }
5372 
5373     QualType PointeeType = ParamType->getPointeeType();
5374     if (PointeeType.getQualifiers().hasAddressSpace())
5375       continue;
5376 
5377     NeedsNewDecl = true;
5378     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5379 
5380     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5381     OverloadParams.push_back(Context.getPointerType(PointeeType));
5382   }
5383 
5384   if (!NeedsNewDecl)
5385     return nullptr;
5386 
5387   FunctionProtoType::ExtProtoInfo EPI;
5388   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5389                                                 OverloadParams, EPI);
5390   DeclContext *Parent = Context.getTranslationUnitDecl();
5391   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5392                                                     FDecl->getLocation(),
5393                                                     FDecl->getLocation(),
5394                                                     FDecl->getIdentifier(),
5395                                                     OverloadTy,
5396                                                     /*TInfo=*/nullptr,
5397                                                     SC_Extern, false,
5398                                                     /*hasPrototype=*/true);
5399   SmallVector<ParmVarDecl*, 16> Params;
5400   FT = cast<FunctionProtoType>(OverloadTy);
5401   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5402     QualType ParamType = FT->getParamType(i);
5403     ParmVarDecl *Parm =
5404         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5405                                 SourceLocation(), nullptr, ParamType,
5406                                 /*TInfo=*/nullptr, SC_None, nullptr);
5407     Parm->setScopeInfo(0, i);
5408     Params.push_back(Parm);
5409   }
5410   OverloadDecl->setParams(Params);
5411   return OverloadDecl;
5412 }
5413 
5414 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5415                                     FunctionDecl *Callee,
5416                                     MultiExprArg ArgExprs) {
5417   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5418   // similar attributes) really don't like it when functions are called with an
5419   // invalid number of args.
5420   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5421                          /*PartialOverloading=*/false) &&
5422       !Callee->isVariadic())
5423     return;
5424   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5425     return;
5426 
5427   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5428     S.Diag(Fn->getBeginLoc(),
5429            isa<CXXMethodDecl>(Callee)
5430                ? diag::err_ovl_no_viable_member_function_in_call
5431                : diag::err_ovl_no_viable_function_in_call)
5432         << Callee << Callee->getSourceRange();
5433     S.Diag(Callee->getLocation(),
5434            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5435         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5436     return;
5437   }
5438 }
5439 
5440 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5441     const UnresolvedMemberExpr *const UME, Sema &S) {
5442 
5443   const auto GetFunctionLevelDCIfCXXClass =
5444       [](Sema &S) -> const CXXRecordDecl * {
5445     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5446     if (!DC || !DC->getParent())
5447       return nullptr;
5448 
5449     // If the call to some member function was made from within a member
5450     // function body 'M' return return 'M's parent.
5451     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5452       return MD->getParent()->getCanonicalDecl();
5453     // else the call was made from within a default member initializer of a
5454     // class, so return the class.
5455     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5456       return RD->getCanonicalDecl();
5457     return nullptr;
5458   };
5459   // If our DeclContext is neither a member function nor a class (in the
5460   // case of a lambda in a default member initializer), we can't have an
5461   // enclosing 'this'.
5462 
5463   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5464   if (!CurParentClass)
5465     return false;
5466 
5467   // The naming class for implicit member functions call is the class in which
5468   // name lookup starts.
5469   const CXXRecordDecl *const NamingClass =
5470       UME->getNamingClass()->getCanonicalDecl();
5471   assert(NamingClass && "Must have naming class even for implicit access");
5472 
5473   // If the unresolved member functions were found in a 'naming class' that is
5474   // related (either the same or derived from) to the class that contains the
5475   // member function that itself contained the implicit member access.
5476 
5477   return CurParentClass == NamingClass ||
5478          CurParentClass->isDerivedFrom(NamingClass);
5479 }
5480 
5481 static void
5482 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5483     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5484 
5485   if (!UME)
5486     return;
5487 
5488   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5489   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5490   // already been captured, or if this is an implicit member function call (if
5491   // it isn't, an attempt to capture 'this' should already have been made).
5492   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5493       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5494     return;
5495 
5496   // Check if the naming class in which the unresolved members were found is
5497   // related (same as or is a base of) to the enclosing class.
5498 
5499   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5500     return;
5501 
5502 
5503   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5504   // If the enclosing function is not dependent, then this lambda is
5505   // capture ready, so if we can capture this, do so.
5506   if (!EnclosingFunctionCtx->isDependentContext()) {
5507     // If the current lambda and all enclosing lambdas can capture 'this' -
5508     // then go ahead and capture 'this' (since our unresolved overload set
5509     // contains at least one non-static member function).
5510     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5511       S.CheckCXXThisCapture(CallLoc);
5512   } else if (S.CurContext->isDependentContext()) {
5513     // ... since this is an implicit member reference, that might potentially
5514     // involve a 'this' capture, mark 'this' for potential capture in
5515     // enclosing lambdas.
5516     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5517       CurLSI->addPotentialThisCapture(CallLoc);
5518   }
5519 }
5520 
5521 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5522 /// This provides the location of the left/right parens and a list of comma
5523 /// locations.
5524 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5525                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5526                                Expr *ExecConfig, bool IsExecConfig) {
5527   // Since this might be a postfix expression, get rid of ParenListExprs.
5528   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5529   if (Result.isInvalid()) return ExprError();
5530   Fn = Result.get();
5531 
5532   if (checkArgsForPlaceholders(*this, ArgExprs))
5533     return ExprError();
5534 
5535   if (getLangOpts().CPlusPlus) {
5536     // If this is a pseudo-destructor expression, build the call immediately.
5537     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5538       if (!ArgExprs.empty()) {
5539         // Pseudo-destructor calls should not have any arguments.
5540         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5541             << FixItHint::CreateRemoval(
5542                    SourceRange(ArgExprs.front()->getBeginLoc(),
5543                                ArgExprs.back()->getEndLoc()));
5544       }
5545 
5546       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5547                               VK_RValue, RParenLoc);
5548     }
5549     if (Fn->getType() == Context.PseudoObjectTy) {
5550       ExprResult result = CheckPlaceholderExpr(Fn);
5551       if (result.isInvalid()) return ExprError();
5552       Fn = result.get();
5553     }
5554 
5555     // Determine whether this is a dependent call inside a C++ template,
5556     // in which case we won't do any semantic analysis now.
5557     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5558       if (ExecConfig) {
5559         return CUDAKernelCallExpr::Create(
5560             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5561             Context.DependentTy, VK_RValue, RParenLoc);
5562       } else {
5563 
5564         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5565             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5566             Fn->getBeginLoc());
5567 
5568         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5569                                 VK_RValue, RParenLoc);
5570       }
5571     }
5572 
5573     // Determine whether this is a call to an object (C++ [over.call.object]).
5574     if (Fn->getType()->isRecordType())
5575       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5576                                           RParenLoc);
5577 
5578     if (Fn->getType() == Context.UnknownAnyTy) {
5579       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5580       if (result.isInvalid()) return ExprError();
5581       Fn = result.get();
5582     }
5583 
5584     if (Fn->getType() == Context.BoundMemberTy) {
5585       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5586                                        RParenLoc);
5587     }
5588   }
5589 
5590   // Check for overloaded calls.  This can happen even in C due to extensions.
5591   if (Fn->getType() == Context.OverloadTy) {
5592     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5593 
5594     // We aren't supposed to apply this logic if there's an '&' involved.
5595     if (!find.HasFormOfMemberPointer) {
5596       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5597         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5598                                 VK_RValue, RParenLoc);
5599       OverloadExpr *ovl = find.Expression;
5600       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5601         return BuildOverloadedCallExpr(
5602             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5603             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5604       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5605                                        RParenLoc);
5606     }
5607   }
5608 
5609   // If we're directly calling a function, get the appropriate declaration.
5610   if (Fn->getType() == Context.UnknownAnyTy) {
5611     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5612     if (result.isInvalid()) return ExprError();
5613     Fn = result.get();
5614   }
5615 
5616   Expr *NakedFn = Fn->IgnoreParens();
5617 
5618   bool CallingNDeclIndirectly = false;
5619   NamedDecl *NDecl = nullptr;
5620   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5621     if (UnOp->getOpcode() == UO_AddrOf) {
5622       CallingNDeclIndirectly = true;
5623       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5624     }
5625   }
5626 
5627   if (isa<DeclRefExpr>(NakedFn)) {
5628     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5629 
5630     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5631     if (FDecl && FDecl->getBuiltinID()) {
5632       // Rewrite the function decl for this builtin by replacing parameters
5633       // with no explicit address space with the address space of the arguments
5634       // in ArgExprs.
5635       if ((FDecl =
5636                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5637         NDecl = FDecl;
5638         Fn = DeclRefExpr::Create(
5639             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5640             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5641       }
5642     }
5643   } else if (isa<MemberExpr>(NakedFn))
5644     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5645 
5646   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5647     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5648                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5649       return ExprError();
5650 
5651     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5652       return ExprError();
5653 
5654     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5655   }
5656 
5657   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5658                                ExecConfig, IsExecConfig);
5659 }
5660 
5661 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5662 ///
5663 /// __builtin_astype( value, dst type )
5664 ///
5665 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5666                                  SourceLocation BuiltinLoc,
5667                                  SourceLocation RParenLoc) {
5668   ExprValueKind VK = VK_RValue;
5669   ExprObjectKind OK = OK_Ordinary;
5670   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5671   QualType SrcTy = E->getType();
5672   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5673     return ExprError(Diag(BuiltinLoc,
5674                           diag::err_invalid_astype_of_different_size)
5675                      << DstTy
5676                      << SrcTy
5677                      << E->getSourceRange());
5678   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5679 }
5680 
5681 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5682 /// provided arguments.
5683 ///
5684 /// __builtin_convertvector( value, dst type )
5685 ///
5686 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5687                                         SourceLocation BuiltinLoc,
5688                                         SourceLocation RParenLoc) {
5689   TypeSourceInfo *TInfo;
5690   GetTypeFromParser(ParsedDestTy, &TInfo);
5691   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5692 }
5693 
5694 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5695 /// i.e. an expression not of \p OverloadTy.  The expression should
5696 /// unary-convert to an expression of function-pointer or
5697 /// block-pointer type.
5698 ///
5699 /// \param NDecl the declaration being called, if available
5700 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5701                                        SourceLocation LParenLoc,
5702                                        ArrayRef<Expr *> Args,
5703                                        SourceLocation RParenLoc, Expr *Config,
5704                                        bool IsExecConfig, ADLCallKind UsesADL) {
5705   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5706   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5707 
5708   // Functions with 'interrupt' attribute cannot be called directly.
5709   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5710     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5711     return ExprError();
5712   }
5713 
5714   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5715   // so there's some risk when calling out to non-interrupt handler functions
5716   // that the callee might not preserve them. This is easy to diagnose here,
5717   // but can be very challenging to debug.
5718   if (auto *Caller = getCurFunctionDecl())
5719     if (Caller->hasAttr<ARMInterruptAttr>()) {
5720       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5721       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5722         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5723     }
5724 
5725   // Promote the function operand.
5726   // We special-case function promotion here because we only allow promoting
5727   // builtin functions to function pointers in the callee of a call.
5728   ExprResult Result;
5729   QualType ResultTy;
5730   if (BuiltinID &&
5731       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5732     // Extract the return type from the (builtin) function pointer type.
5733     // FIXME Several builtins still have setType in
5734     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5735     // Builtins.def to ensure they are correct before removing setType calls.
5736     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5737     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5738     ResultTy = FDecl->getCallResultType();
5739   } else {
5740     Result = CallExprUnaryConversions(Fn);
5741     ResultTy = Context.BoolTy;
5742   }
5743   if (Result.isInvalid())
5744     return ExprError();
5745   Fn = Result.get();
5746 
5747   // Check for a valid function type, but only if it is not a builtin which
5748   // requires custom type checking. These will be handled by
5749   // CheckBuiltinFunctionCall below just after creation of the call expression.
5750   const FunctionType *FuncT = nullptr;
5751   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5752    retry:
5753     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5754       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5755       // have type pointer to function".
5756       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5757       if (!FuncT)
5758         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5759                            << Fn->getType() << Fn->getSourceRange());
5760     } else if (const BlockPointerType *BPT =
5761                  Fn->getType()->getAs<BlockPointerType>()) {
5762       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5763     } else {
5764       // Handle calls to expressions of unknown-any type.
5765       if (Fn->getType() == Context.UnknownAnyTy) {
5766         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5767         if (rewrite.isInvalid()) return ExprError();
5768         Fn = rewrite.get();
5769         goto retry;
5770       }
5771 
5772     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5773       << Fn->getType() << Fn->getSourceRange());
5774     }
5775   }
5776 
5777   // Get the number of parameters in the function prototype, if any.
5778   // We will allocate space for max(Args.size(), NumParams) arguments
5779   // in the call expression.
5780   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5781   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5782 
5783   CallExpr *TheCall;
5784   if (Config) {
5785     assert(UsesADL == ADLCallKind::NotADL &&
5786            "CUDAKernelCallExpr should not use ADL");
5787     TheCall =
5788         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5789                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5790   } else {
5791     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5792                                RParenLoc, NumParams, UsesADL);
5793   }
5794 
5795   if (!getLangOpts().CPlusPlus) {
5796     // C cannot always handle TypoExpr nodes in builtin calls and direct
5797     // function calls as their argument checking don't necessarily handle
5798     // dependent types properly, so make sure any TypoExprs have been
5799     // dealt with.
5800     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5801     if (!Result.isUsable()) return ExprError();
5802     TheCall = dyn_cast<CallExpr>(Result.get());
5803     if (!TheCall) return Result;
5804     // TheCall at this point has max(Args.size(), NumParams) arguments,
5805     // with extra arguments nulled. We don't want to introduce nulled
5806     // arguments in Args and so we only take the first Args.size() arguments.
5807     Args = llvm::makeArrayRef(TheCall->getArgs(), Args.size());
5808   }
5809 
5810   // Bail out early if calling a builtin with custom type checking.
5811   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5812     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5813 
5814   if (getLangOpts().CUDA) {
5815     if (Config) {
5816       // CUDA: Kernel calls must be to global functions
5817       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5818         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5819             << FDecl << Fn->getSourceRange());
5820 
5821       // CUDA: Kernel function must have 'void' return type
5822       if (!FuncT->getReturnType()->isVoidType())
5823         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5824             << Fn->getType() << Fn->getSourceRange());
5825     } else {
5826       // CUDA: Calls to global functions must be configured
5827       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5828         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5829             << FDecl << Fn->getSourceRange());
5830     }
5831   }
5832 
5833   // Check for a valid return type
5834   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5835                           FDecl))
5836     return ExprError();
5837 
5838   // We know the result type of the call, set it.
5839   TheCall->setType(FuncT->getCallResultType(Context));
5840   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5841 
5842   if (Proto) {
5843     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5844                                 IsExecConfig))
5845       return ExprError();
5846   } else {
5847     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5848 
5849     if (FDecl) {
5850       // Check if we have too few/too many template arguments, based
5851       // on our knowledge of the function definition.
5852       const FunctionDecl *Def = nullptr;
5853       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5854         Proto = Def->getType()->getAs<FunctionProtoType>();
5855        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5856           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5857           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5858       }
5859 
5860       // If the function we're calling isn't a function prototype, but we have
5861       // a function prototype from a prior declaratiom, use that prototype.
5862       if (!FDecl->hasPrototype())
5863         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5864     }
5865 
5866     // Promote the arguments (C99 6.5.2.2p6).
5867     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5868       Expr *Arg = Args[i];
5869 
5870       if (Proto && i < Proto->getNumParams()) {
5871         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5872             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5873         ExprResult ArgE =
5874             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5875         if (ArgE.isInvalid())
5876           return true;
5877 
5878         Arg = ArgE.getAs<Expr>();
5879 
5880       } else {
5881         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5882 
5883         if (ArgE.isInvalid())
5884           return true;
5885 
5886         Arg = ArgE.getAs<Expr>();
5887       }
5888 
5889       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5890                               diag::err_call_incomplete_argument, Arg))
5891         return ExprError();
5892 
5893       TheCall->setArg(i, Arg);
5894     }
5895   }
5896 
5897   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5898     if (!Method->isStatic())
5899       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5900         << Fn->getSourceRange());
5901 
5902   // Check for sentinels
5903   if (NDecl)
5904     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5905 
5906   // Do special checking on direct calls to functions.
5907   if (FDecl) {
5908     if (CheckFunctionCall(FDecl, TheCall, Proto))
5909       return ExprError();
5910 
5911     if (BuiltinID)
5912       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5913   } else if (NDecl) {
5914     if (CheckPointerCall(NDecl, TheCall, Proto))
5915       return ExprError();
5916   } else {
5917     if (CheckOtherCall(TheCall, Proto))
5918       return ExprError();
5919   }
5920 
5921   return MaybeBindToTemporary(TheCall);
5922 }
5923 
5924 ExprResult
5925 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5926                            SourceLocation RParenLoc, Expr *InitExpr) {
5927   assert(Ty && "ActOnCompoundLiteral(): missing type");
5928   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5929 
5930   TypeSourceInfo *TInfo;
5931   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5932   if (!TInfo)
5933     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5934 
5935   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5936 }
5937 
5938 ExprResult
5939 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5940                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5941   QualType literalType = TInfo->getType();
5942 
5943   if (literalType->isArrayType()) {
5944     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5945           diag::err_illegal_decl_array_incomplete_type,
5946           SourceRange(LParenLoc,
5947                       LiteralExpr->getSourceRange().getEnd())))
5948       return ExprError();
5949     if (literalType->isVariableArrayType())
5950       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5951         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5952   } else if (!literalType->isDependentType() &&
5953              RequireCompleteType(LParenLoc, literalType,
5954                diag::err_typecheck_decl_incomplete_type,
5955                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5956     return ExprError();
5957 
5958   InitializedEntity Entity
5959     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5960   InitializationKind Kind
5961     = InitializationKind::CreateCStyleCast(LParenLoc,
5962                                            SourceRange(LParenLoc, RParenLoc),
5963                                            /*InitList=*/true);
5964   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5965   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5966                                       &literalType);
5967   if (Result.isInvalid())
5968     return ExprError();
5969   LiteralExpr = Result.get();
5970 
5971   bool isFileScope = !CurContext->isFunctionOrMethod();
5972 
5973   // In C, compound literals are l-values for some reason.
5974   // For GCC compatibility, in C++, file-scope array compound literals with
5975   // constant initializers are also l-values, and compound literals are
5976   // otherwise prvalues.
5977   //
5978   // (GCC also treats C++ list-initialized file-scope array prvalues with
5979   // constant initializers as l-values, but that's non-conforming, so we don't
5980   // follow it there.)
5981   //
5982   // FIXME: It would be better to handle the lvalue cases as materializing and
5983   // lifetime-extending a temporary object, but our materialized temporaries
5984   // representation only supports lifetime extension from a variable, not "out
5985   // of thin air".
5986   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5987   // is bound to the result of applying array-to-pointer decay to the compound
5988   // literal.
5989   // FIXME: GCC supports compound literals of reference type, which should
5990   // obviously have a value kind derived from the kind of reference involved.
5991   ExprValueKind VK =
5992       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5993           ? VK_RValue
5994           : VK_LValue;
5995 
5996   if (isFileScope)
5997     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
5998       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
5999         Expr *Init = ILE->getInit(i);
6000         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6001       }
6002 
6003   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6004                                               VK, LiteralExpr, isFileScope);
6005   if (isFileScope) {
6006     if (!LiteralExpr->isTypeDependent() &&
6007         !LiteralExpr->isValueDependent() &&
6008         !literalType->isDependentType()) // C99 6.5.2.5p3
6009       if (CheckForConstantInitializer(LiteralExpr, literalType))
6010         return ExprError();
6011   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6012              literalType.getAddressSpace() != LangAS::Default) {
6013     // Embedded-C extensions to C99 6.5.2.5:
6014     //   "If the compound literal occurs inside the body of a function, the
6015     //   type name shall not be qualified by an address-space qualifier."
6016     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6017       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6018     return ExprError();
6019   }
6020 
6021   return MaybeBindToTemporary(E);
6022 }
6023 
6024 ExprResult
6025 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6026                     SourceLocation RBraceLoc) {
6027   // Immediately handle non-overload placeholders.  Overloads can be
6028   // resolved contextually, but everything else here can't.
6029   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6030     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6031       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6032 
6033       // Ignore failures; dropping the entire initializer list because
6034       // of one failure would be terrible for indexing/etc.
6035       if (result.isInvalid()) continue;
6036 
6037       InitArgList[I] = result.get();
6038     }
6039   }
6040 
6041   // Semantic analysis for initializers is done by ActOnDeclarator() and
6042   // CheckInitializer() - it requires knowledge of the object being initialized.
6043 
6044   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6045                                                RBraceLoc);
6046   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6047   return E;
6048 }
6049 
6050 /// Do an explicit extend of the given block pointer if we're in ARC.
6051 void Sema::maybeExtendBlockObject(ExprResult &E) {
6052   assert(E.get()->getType()->isBlockPointerType());
6053   assert(E.get()->isRValue());
6054 
6055   // Only do this in an r-value context.
6056   if (!getLangOpts().ObjCAutoRefCount) return;
6057 
6058   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6059                                CK_ARCExtendBlockObject, E.get(),
6060                                /*base path*/ nullptr, VK_RValue);
6061   Cleanup.setExprNeedsCleanups(true);
6062 }
6063 
6064 /// Prepare a conversion of the given expression to an ObjC object
6065 /// pointer type.
6066 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6067   QualType type = E.get()->getType();
6068   if (type->isObjCObjectPointerType()) {
6069     return CK_BitCast;
6070   } else if (type->isBlockPointerType()) {
6071     maybeExtendBlockObject(E);
6072     return CK_BlockPointerToObjCPointerCast;
6073   } else {
6074     assert(type->isPointerType());
6075     return CK_CPointerToObjCPointerCast;
6076   }
6077 }
6078 
6079 /// Prepares for a scalar cast, performing all the necessary stages
6080 /// except the final cast and returning the kind required.
6081 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6082   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6083   // Also, callers should have filtered out the invalid cases with
6084   // pointers.  Everything else should be possible.
6085 
6086   QualType SrcTy = Src.get()->getType();
6087   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6088     return CK_NoOp;
6089 
6090   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6091   case Type::STK_MemberPointer:
6092     llvm_unreachable("member pointer type in C");
6093 
6094   case Type::STK_CPointer:
6095   case Type::STK_BlockPointer:
6096   case Type::STK_ObjCObjectPointer:
6097     switch (DestTy->getScalarTypeKind()) {
6098     case Type::STK_CPointer: {
6099       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6100       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6101       if (SrcAS != DestAS)
6102         return CK_AddressSpaceConversion;
6103       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6104         return CK_NoOp;
6105       return CK_BitCast;
6106     }
6107     case Type::STK_BlockPointer:
6108       return (SrcKind == Type::STK_BlockPointer
6109                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6110     case Type::STK_ObjCObjectPointer:
6111       if (SrcKind == Type::STK_ObjCObjectPointer)
6112         return CK_BitCast;
6113       if (SrcKind == Type::STK_CPointer)
6114         return CK_CPointerToObjCPointerCast;
6115       maybeExtendBlockObject(Src);
6116       return CK_BlockPointerToObjCPointerCast;
6117     case Type::STK_Bool:
6118       return CK_PointerToBoolean;
6119     case Type::STK_Integral:
6120       return CK_PointerToIntegral;
6121     case Type::STK_Floating:
6122     case Type::STK_FloatingComplex:
6123     case Type::STK_IntegralComplex:
6124     case Type::STK_MemberPointer:
6125     case Type::STK_FixedPoint:
6126       llvm_unreachable("illegal cast from pointer");
6127     }
6128     llvm_unreachable("Should have returned before this");
6129 
6130   case Type::STK_FixedPoint:
6131     switch (DestTy->getScalarTypeKind()) {
6132     case Type::STK_FixedPoint:
6133       return CK_FixedPointCast;
6134     case Type::STK_Bool:
6135       return CK_FixedPointToBoolean;
6136     case Type::STK_Integral:
6137     case Type::STK_Floating:
6138     case Type::STK_IntegralComplex:
6139     case Type::STK_FloatingComplex:
6140       Diag(Src.get()->getExprLoc(),
6141            diag::err_unimplemented_conversion_with_fixed_point_type)
6142           << DestTy;
6143       return CK_IntegralCast;
6144     case Type::STK_CPointer:
6145     case Type::STK_ObjCObjectPointer:
6146     case Type::STK_BlockPointer:
6147     case Type::STK_MemberPointer:
6148       llvm_unreachable("illegal cast to pointer type");
6149     }
6150     llvm_unreachable("Should have returned before this");
6151 
6152   case Type::STK_Bool: // casting from bool is like casting from an integer
6153   case Type::STK_Integral:
6154     switch (DestTy->getScalarTypeKind()) {
6155     case Type::STK_CPointer:
6156     case Type::STK_ObjCObjectPointer:
6157     case Type::STK_BlockPointer:
6158       if (Src.get()->isNullPointerConstant(Context,
6159                                            Expr::NPC_ValueDependentIsNull))
6160         return CK_NullToPointer;
6161       return CK_IntegralToPointer;
6162     case Type::STK_Bool:
6163       return CK_IntegralToBoolean;
6164     case Type::STK_Integral:
6165       return CK_IntegralCast;
6166     case Type::STK_Floating:
6167       return CK_IntegralToFloating;
6168     case Type::STK_IntegralComplex:
6169       Src = ImpCastExprToType(Src.get(),
6170                       DestTy->castAs<ComplexType>()->getElementType(),
6171                       CK_IntegralCast);
6172       return CK_IntegralRealToComplex;
6173     case Type::STK_FloatingComplex:
6174       Src = ImpCastExprToType(Src.get(),
6175                       DestTy->castAs<ComplexType>()->getElementType(),
6176                       CK_IntegralToFloating);
6177       return CK_FloatingRealToComplex;
6178     case Type::STK_MemberPointer:
6179       llvm_unreachable("member pointer type in C");
6180     case Type::STK_FixedPoint:
6181       Diag(Src.get()->getExprLoc(),
6182            diag::err_unimplemented_conversion_with_fixed_point_type)
6183           << SrcTy;
6184       return CK_IntegralCast;
6185     }
6186     llvm_unreachable("Should have returned before this");
6187 
6188   case Type::STK_Floating:
6189     switch (DestTy->getScalarTypeKind()) {
6190     case Type::STK_Floating:
6191       return CK_FloatingCast;
6192     case Type::STK_Bool:
6193       return CK_FloatingToBoolean;
6194     case Type::STK_Integral:
6195       return CK_FloatingToIntegral;
6196     case Type::STK_FloatingComplex:
6197       Src = ImpCastExprToType(Src.get(),
6198                               DestTy->castAs<ComplexType>()->getElementType(),
6199                               CK_FloatingCast);
6200       return CK_FloatingRealToComplex;
6201     case Type::STK_IntegralComplex:
6202       Src = ImpCastExprToType(Src.get(),
6203                               DestTy->castAs<ComplexType>()->getElementType(),
6204                               CK_FloatingToIntegral);
6205       return CK_IntegralRealToComplex;
6206     case Type::STK_CPointer:
6207     case Type::STK_ObjCObjectPointer:
6208     case Type::STK_BlockPointer:
6209       llvm_unreachable("valid float->pointer cast?");
6210     case Type::STK_MemberPointer:
6211       llvm_unreachable("member pointer type in C");
6212     case Type::STK_FixedPoint:
6213       Diag(Src.get()->getExprLoc(),
6214            diag::err_unimplemented_conversion_with_fixed_point_type)
6215           << SrcTy;
6216       return CK_IntegralCast;
6217     }
6218     llvm_unreachable("Should have returned before this");
6219 
6220   case Type::STK_FloatingComplex:
6221     switch (DestTy->getScalarTypeKind()) {
6222     case Type::STK_FloatingComplex:
6223       return CK_FloatingComplexCast;
6224     case Type::STK_IntegralComplex:
6225       return CK_FloatingComplexToIntegralComplex;
6226     case Type::STK_Floating: {
6227       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6228       if (Context.hasSameType(ET, DestTy))
6229         return CK_FloatingComplexToReal;
6230       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6231       return CK_FloatingCast;
6232     }
6233     case Type::STK_Bool:
6234       return CK_FloatingComplexToBoolean;
6235     case Type::STK_Integral:
6236       Src = ImpCastExprToType(Src.get(),
6237                               SrcTy->castAs<ComplexType>()->getElementType(),
6238                               CK_FloatingComplexToReal);
6239       return CK_FloatingToIntegral;
6240     case Type::STK_CPointer:
6241     case Type::STK_ObjCObjectPointer:
6242     case Type::STK_BlockPointer:
6243       llvm_unreachable("valid complex float->pointer cast?");
6244     case Type::STK_MemberPointer:
6245       llvm_unreachable("member pointer type in C");
6246     case Type::STK_FixedPoint:
6247       Diag(Src.get()->getExprLoc(),
6248            diag::err_unimplemented_conversion_with_fixed_point_type)
6249           << SrcTy;
6250       return CK_IntegralCast;
6251     }
6252     llvm_unreachable("Should have returned before this");
6253 
6254   case Type::STK_IntegralComplex:
6255     switch (DestTy->getScalarTypeKind()) {
6256     case Type::STK_FloatingComplex:
6257       return CK_IntegralComplexToFloatingComplex;
6258     case Type::STK_IntegralComplex:
6259       return CK_IntegralComplexCast;
6260     case Type::STK_Integral: {
6261       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6262       if (Context.hasSameType(ET, DestTy))
6263         return CK_IntegralComplexToReal;
6264       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6265       return CK_IntegralCast;
6266     }
6267     case Type::STK_Bool:
6268       return CK_IntegralComplexToBoolean;
6269     case Type::STK_Floating:
6270       Src = ImpCastExprToType(Src.get(),
6271                               SrcTy->castAs<ComplexType>()->getElementType(),
6272                               CK_IntegralComplexToReal);
6273       return CK_IntegralToFloating;
6274     case Type::STK_CPointer:
6275     case Type::STK_ObjCObjectPointer:
6276     case Type::STK_BlockPointer:
6277       llvm_unreachable("valid complex int->pointer cast?");
6278     case Type::STK_MemberPointer:
6279       llvm_unreachable("member pointer type in C");
6280     case Type::STK_FixedPoint:
6281       Diag(Src.get()->getExprLoc(),
6282            diag::err_unimplemented_conversion_with_fixed_point_type)
6283           << SrcTy;
6284       return CK_IntegralCast;
6285     }
6286     llvm_unreachable("Should have returned before this");
6287   }
6288 
6289   llvm_unreachable("Unhandled scalar cast");
6290 }
6291 
6292 static bool breakDownVectorType(QualType type, uint64_t &len,
6293                                 QualType &eltType) {
6294   // Vectors are simple.
6295   if (const VectorType *vecType = type->getAs<VectorType>()) {
6296     len = vecType->getNumElements();
6297     eltType = vecType->getElementType();
6298     assert(eltType->isScalarType());
6299     return true;
6300   }
6301 
6302   // We allow lax conversion to and from non-vector types, but only if
6303   // they're real types (i.e. non-complex, non-pointer scalar types).
6304   if (!type->isRealType()) return false;
6305 
6306   len = 1;
6307   eltType = type;
6308   return true;
6309 }
6310 
6311 /// Are the two types lax-compatible vector types?  That is, given
6312 /// that one of them is a vector, do they have equal storage sizes,
6313 /// where the storage size is the number of elements times the element
6314 /// size?
6315 ///
6316 /// This will also return false if either of the types is neither a
6317 /// vector nor a real type.
6318 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6319   assert(destTy->isVectorType() || srcTy->isVectorType());
6320 
6321   // Disallow lax conversions between scalars and ExtVectors (these
6322   // conversions are allowed for other vector types because common headers
6323   // depend on them).  Most scalar OP ExtVector cases are handled by the
6324   // splat path anyway, which does what we want (convert, not bitcast).
6325   // What this rules out for ExtVectors is crazy things like char4*float.
6326   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6327   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6328 
6329   uint64_t srcLen, destLen;
6330   QualType srcEltTy, destEltTy;
6331   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6332   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6333 
6334   // ASTContext::getTypeSize will return the size rounded up to a
6335   // power of 2, so instead of using that, we need to use the raw
6336   // element size multiplied by the element count.
6337   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6338   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6339 
6340   return (srcLen * srcEltSize == destLen * destEltSize);
6341 }
6342 
6343 /// Is this a legal conversion between two types, one of which is
6344 /// known to be a vector type?
6345 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6346   assert(destTy->isVectorType() || srcTy->isVectorType());
6347 
6348   if (!Context.getLangOpts().LaxVectorConversions)
6349     return false;
6350   return areLaxCompatibleVectorTypes(srcTy, destTy);
6351 }
6352 
6353 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6354                            CastKind &Kind) {
6355   assert(VectorTy->isVectorType() && "Not a vector type!");
6356 
6357   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6358     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6359       return Diag(R.getBegin(),
6360                   Ty->isVectorType() ?
6361                   diag::err_invalid_conversion_between_vectors :
6362                   diag::err_invalid_conversion_between_vector_and_integer)
6363         << VectorTy << Ty << R;
6364   } else
6365     return Diag(R.getBegin(),
6366                 diag::err_invalid_conversion_between_vector_and_scalar)
6367       << VectorTy << Ty << R;
6368 
6369   Kind = CK_BitCast;
6370   return false;
6371 }
6372 
6373 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6374   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6375 
6376   if (DestElemTy == SplattedExpr->getType())
6377     return SplattedExpr;
6378 
6379   assert(DestElemTy->isFloatingType() ||
6380          DestElemTy->isIntegralOrEnumerationType());
6381 
6382   CastKind CK;
6383   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6384     // OpenCL requires that we convert `true` boolean expressions to -1, but
6385     // only when splatting vectors.
6386     if (DestElemTy->isFloatingType()) {
6387       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6388       // in two steps: boolean to signed integral, then to floating.
6389       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6390                                                  CK_BooleanToSignedIntegral);
6391       SplattedExpr = CastExprRes.get();
6392       CK = CK_IntegralToFloating;
6393     } else {
6394       CK = CK_BooleanToSignedIntegral;
6395     }
6396   } else {
6397     ExprResult CastExprRes = SplattedExpr;
6398     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6399     if (CastExprRes.isInvalid())
6400       return ExprError();
6401     SplattedExpr = CastExprRes.get();
6402   }
6403   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6404 }
6405 
6406 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6407                                     Expr *CastExpr, CastKind &Kind) {
6408   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6409 
6410   QualType SrcTy = CastExpr->getType();
6411 
6412   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6413   // an ExtVectorType.
6414   // In OpenCL, casts between vectors of different types are not allowed.
6415   // (See OpenCL 6.2).
6416   if (SrcTy->isVectorType()) {
6417     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6418         (getLangOpts().OpenCL &&
6419          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6420       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6421         << DestTy << SrcTy << R;
6422       return ExprError();
6423     }
6424     Kind = CK_BitCast;
6425     return CastExpr;
6426   }
6427 
6428   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6429   // conversion will take place first from scalar to elt type, and then
6430   // splat from elt type to vector.
6431   if (SrcTy->isPointerType())
6432     return Diag(R.getBegin(),
6433                 diag::err_invalid_conversion_between_vector_and_scalar)
6434       << DestTy << SrcTy << R;
6435 
6436   Kind = CK_VectorSplat;
6437   return prepareVectorSplat(DestTy, CastExpr);
6438 }
6439 
6440 ExprResult
6441 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6442                     Declarator &D, ParsedType &Ty,
6443                     SourceLocation RParenLoc, Expr *CastExpr) {
6444   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6445          "ActOnCastExpr(): missing type or expr");
6446 
6447   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6448   if (D.isInvalidType())
6449     return ExprError();
6450 
6451   if (getLangOpts().CPlusPlus) {
6452     // Check that there are no default arguments (C++ only).
6453     CheckExtraCXXDefaultArguments(D);
6454   } else {
6455     // Make sure any TypoExprs have been dealt with.
6456     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6457     if (!Res.isUsable())
6458       return ExprError();
6459     CastExpr = Res.get();
6460   }
6461 
6462   checkUnusedDeclAttributes(D);
6463 
6464   QualType castType = castTInfo->getType();
6465   Ty = CreateParsedType(castType, castTInfo);
6466 
6467   bool isVectorLiteral = false;
6468 
6469   // Check for an altivec or OpenCL literal,
6470   // i.e. all the elements are integer constants.
6471   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6472   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6473   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6474        && castType->isVectorType() && (PE || PLE)) {
6475     if (PLE && PLE->getNumExprs() == 0) {
6476       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6477       return ExprError();
6478     }
6479     if (PE || PLE->getNumExprs() == 1) {
6480       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6481       if (!E->getType()->isVectorType())
6482         isVectorLiteral = true;
6483     }
6484     else
6485       isVectorLiteral = true;
6486   }
6487 
6488   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6489   // then handle it as such.
6490   if (isVectorLiteral)
6491     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6492 
6493   // If the Expr being casted is a ParenListExpr, handle it specially.
6494   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6495   // sequence of BinOp comma operators.
6496   if (isa<ParenListExpr>(CastExpr)) {
6497     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6498     if (Result.isInvalid()) return ExprError();
6499     CastExpr = Result.get();
6500   }
6501 
6502   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6503       !getSourceManager().isInSystemMacro(LParenLoc))
6504     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6505 
6506   CheckTollFreeBridgeCast(castType, CastExpr);
6507 
6508   CheckObjCBridgeRelatedCast(castType, CastExpr);
6509 
6510   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6511 
6512   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6513 }
6514 
6515 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6516                                     SourceLocation RParenLoc, Expr *E,
6517                                     TypeSourceInfo *TInfo) {
6518   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6519          "Expected paren or paren list expression");
6520 
6521   Expr **exprs;
6522   unsigned numExprs;
6523   Expr *subExpr;
6524   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6525   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6526     LiteralLParenLoc = PE->getLParenLoc();
6527     LiteralRParenLoc = PE->getRParenLoc();
6528     exprs = PE->getExprs();
6529     numExprs = PE->getNumExprs();
6530   } else { // isa<ParenExpr> by assertion at function entrance
6531     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6532     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6533     subExpr = cast<ParenExpr>(E)->getSubExpr();
6534     exprs = &subExpr;
6535     numExprs = 1;
6536   }
6537 
6538   QualType Ty = TInfo->getType();
6539   assert(Ty->isVectorType() && "Expected vector type");
6540 
6541   SmallVector<Expr *, 8> initExprs;
6542   const VectorType *VTy = Ty->getAs<VectorType>();
6543   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6544 
6545   // '(...)' form of vector initialization in AltiVec: the number of
6546   // initializers must be one or must match the size of the vector.
6547   // If a single value is specified in the initializer then it will be
6548   // replicated to all the components of the vector
6549   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6550     // The number of initializers must be one or must match the size of the
6551     // vector. If a single value is specified in the initializer then it will
6552     // be replicated to all the components of the vector
6553     if (numExprs == 1) {
6554       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6555       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6556       if (Literal.isInvalid())
6557         return ExprError();
6558       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6559                                   PrepareScalarCast(Literal, ElemTy));
6560       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6561     }
6562     else if (numExprs < numElems) {
6563       Diag(E->getExprLoc(),
6564            diag::err_incorrect_number_of_vector_initializers);
6565       return ExprError();
6566     }
6567     else
6568       initExprs.append(exprs, exprs + numExprs);
6569   }
6570   else {
6571     // For OpenCL, when the number of initializers is a single value,
6572     // it will be replicated to all components of the vector.
6573     if (getLangOpts().OpenCL &&
6574         VTy->getVectorKind() == VectorType::GenericVector &&
6575         numExprs == 1) {
6576         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6577         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6578         if (Literal.isInvalid())
6579           return ExprError();
6580         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6581                                     PrepareScalarCast(Literal, ElemTy));
6582         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6583     }
6584 
6585     initExprs.append(exprs, exprs + numExprs);
6586   }
6587   // FIXME: This means that pretty-printing the final AST will produce curly
6588   // braces instead of the original commas.
6589   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6590                                                    initExprs, LiteralRParenLoc);
6591   initE->setType(Ty);
6592   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6593 }
6594 
6595 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6596 /// the ParenListExpr into a sequence of comma binary operators.
6597 ExprResult
6598 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6599   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6600   if (!E)
6601     return OrigExpr;
6602 
6603   ExprResult Result(E->getExpr(0));
6604 
6605   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6606     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6607                         E->getExpr(i));
6608 
6609   if (Result.isInvalid()) return ExprError();
6610 
6611   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6612 }
6613 
6614 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6615                                     SourceLocation R,
6616                                     MultiExprArg Val) {
6617   return ParenListExpr::Create(Context, L, Val, R);
6618 }
6619 
6620 /// Emit a specialized diagnostic when one expression is a null pointer
6621 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6622 /// emitted.
6623 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6624                                       SourceLocation QuestionLoc) {
6625   Expr *NullExpr = LHSExpr;
6626   Expr *NonPointerExpr = RHSExpr;
6627   Expr::NullPointerConstantKind NullKind =
6628       NullExpr->isNullPointerConstant(Context,
6629                                       Expr::NPC_ValueDependentIsNotNull);
6630 
6631   if (NullKind == Expr::NPCK_NotNull) {
6632     NullExpr = RHSExpr;
6633     NonPointerExpr = LHSExpr;
6634     NullKind =
6635         NullExpr->isNullPointerConstant(Context,
6636                                         Expr::NPC_ValueDependentIsNotNull);
6637   }
6638 
6639   if (NullKind == Expr::NPCK_NotNull)
6640     return false;
6641 
6642   if (NullKind == Expr::NPCK_ZeroExpression)
6643     return false;
6644 
6645   if (NullKind == Expr::NPCK_ZeroLiteral) {
6646     // In this case, check to make sure that we got here from a "NULL"
6647     // string in the source code.
6648     NullExpr = NullExpr->IgnoreParenImpCasts();
6649     SourceLocation loc = NullExpr->getExprLoc();
6650     if (!findMacroSpelling(loc, "NULL"))
6651       return false;
6652   }
6653 
6654   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6655   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6656       << NonPointerExpr->getType() << DiagType
6657       << NonPointerExpr->getSourceRange();
6658   return true;
6659 }
6660 
6661 /// Return false if the condition expression is valid, true otherwise.
6662 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6663   QualType CondTy = Cond->getType();
6664 
6665   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6666   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6667     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6668       << CondTy << Cond->getSourceRange();
6669     return true;
6670   }
6671 
6672   // C99 6.5.15p2
6673   if (CondTy->isScalarType()) return false;
6674 
6675   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6676     << CondTy << Cond->getSourceRange();
6677   return true;
6678 }
6679 
6680 /// Handle when one or both operands are void type.
6681 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6682                                          ExprResult &RHS) {
6683     Expr *LHSExpr = LHS.get();
6684     Expr *RHSExpr = RHS.get();
6685 
6686     if (!LHSExpr->getType()->isVoidType())
6687       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6688           << RHSExpr->getSourceRange();
6689     if (!RHSExpr->getType()->isVoidType())
6690       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6691           << LHSExpr->getSourceRange();
6692     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6693     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6694     return S.Context.VoidTy;
6695 }
6696 
6697 /// Return false if the NullExpr can be promoted to PointerTy,
6698 /// true otherwise.
6699 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6700                                         QualType PointerTy) {
6701   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6702       !NullExpr.get()->isNullPointerConstant(S.Context,
6703                                             Expr::NPC_ValueDependentIsNull))
6704     return true;
6705 
6706   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6707   return false;
6708 }
6709 
6710 /// Checks compatibility between two pointers and return the resulting
6711 /// type.
6712 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6713                                                      ExprResult &RHS,
6714                                                      SourceLocation Loc) {
6715   QualType LHSTy = LHS.get()->getType();
6716   QualType RHSTy = RHS.get()->getType();
6717 
6718   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6719     // Two identical pointers types are always compatible.
6720     return LHSTy;
6721   }
6722 
6723   QualType lhptee, rhptee;
6724 
6725   // Get the pointee types.
6726   bool IsBlockPointer = false;
6727   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6728     lhptee = LHSBTy->getPointeeType();
6729     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6730     IsBlockPointer = true;
6731   } else {
6732     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6733     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6734   }
6735 
6736   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6737   // differently qualified versions of compatible types, the result type is
6738   // a pointer to an appropriately qualified version of the composite
6739   // type.
6740 
6741   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6742   // clause doesn't make sense for our extensions. E.g. address space 2 should
6743   // be incompatible with address space 3: they may live on different devices or
6744   // anything.
6745   Qualifiers lhQual = lhptee.getQualifiers();
6746   Qualifiers rhQual = rhptee.getQualifiers();
6747 
6748   LangAS ResultAddrSpace = LangAS::Default;
6749   LangAS LAddrSpace = lhQual.getAddressSpace();
6750   LangAS RAddrSpace = rhQual.getAddressSpace();
6751 
6752   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6753   // spaces is disallowed.
6754   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6755     ResultAddrSpace = LAddrSpace;
6756   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6757     ResultAddrSpace = RAddrSpace;
6758   else {
6759     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6760         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6761         << RHS.get()->getSourceRange();
6762     return QualType();
6763   }
6764 
6765   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6766   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6767   lhQual.removeCVRQualifiers();
6768   rhQual.removeCVRQualifiers();
6769 
6770   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6771   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6772   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6773   // qual types are compatible iff
6774   //  * corresponded types are compatible
6775   //  * CVR qualifiers are equal
6776   //  * address spaces are equal
6777   // Thus for conditional operator we merge CVR and address space unqualified
6778   // pointees and if there is a composite type we return a pointer to it with
6779   // merged qualifiers.
6780   LHSCastKind =
6781       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6782   RHSCastKind =
6783       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6784   lhQual.removeAddressSpace();
6785   rhQual.removeAddressSpace();
6786 
6787   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6788   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6789 
6790   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6791 
6792   if (CompositeTy.isNull()) {
6793     // In this situation, we assume void* type. No especially good
6794     // reason, but this is what gcc does, and we do have to pick
6795     // to get a consistent AST.
6796     QualType incompatTy;
6797     incompatTy = S.Context.getPointerType(
6798         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6799     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6800     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6801 
6802     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6803     // for casts between types with incompatible address space qualifiers.
6804     // For the following code the compiler produces casts between global and
6805     // local address spaces of the corresponded innermost pointees:
6806     // local int *global *a;
6807     // global int *global *b;
6808     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6809     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6810         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6811         << RHS.get()->getSourceRange();
6812 
6813     return incompatTy;
6814   }
6815 
6816   // The pointer types are compatible.
6817   // In case of OpenCL ResultTy should have the address space qualifier
6818   // which is a superset of address spaces of both the 2nd and the 3rd
6819   // operands of the conditional operator.
6820   QualType ResultTy = [&, ResultAddrSpace]() {
6821     if (S.getLangOpts().OpenCL) {
6822       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6823       CompositeQuals.setAddressSpace(ResultAddrSpace);
6824       return S.Context
6825           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6826           .withCVRQualifiers(MergedCVRQual);
6827     }
6828     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6829   }();
6830   if (IsBlockPointer)
6831     ResultTy = S.Context.getBlockPointerType(ResultTy);
6832   else
6833     ResultTy = S.Context.getPointerType(ResultTy);
6834 
6835   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6836   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6837   return ResultTy;
6838 }
6839 
6840 /// Return the resulting type when the operands are both block pointers.
6841 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6842                                                           ExprResult &LHS,
6843                                                           ExprResult &RHS,
6844                                                           SourceLocation Loc) {
6845   QualType LHSTy = LHS.get()->getType();
6846   QualType RHSTy = RHS.get()->getType();
6847 
6848   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6849     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6850       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6851       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6852       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6853       return destType;
6854     }
6855     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6856       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6857       << RHS.get()->getSourceRange();
6858     return QualType();
6859   }
6860 
6861   // We have 2 block pointer types.
6862   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6863 }
6864 
6865 /// Return the resulting type when the operands are both pointers.
6866 static QualType
6867 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6868                                             ExprResult &RHS,
6869                                             SourceLocation Loc) {
6870   // get the pointer types
6871   QualType LHSTy = LHS.get()->getType();
6872   QualType RHSTy = RHS.get()->getType();
6873 
6874   // get the "pointed to" types
6875   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6876   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6877 
6878   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6879   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6880     // Figure out necessary qualifiers (C99 6.5.15p6)
6881     QualType destPointee
6882       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6883     QualType destType = S.Context.getPointerType(destPointee);
6884     // Add qualifiers if necessary.
6885     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6886     // Promote to void*.
6887     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6888     return destType;
6889   }
6890   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6891     QualType destPointee
6892       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6893     QualType destType = S.Context.getPointerType(destPointee);
6894     // Add qualifiers if necessary.
6895     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6896     // Promote to void*.
6897     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6898     return destType;
6899   }
6900 
6901   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6902 }
6903 
6904 /// Return false if the first expression is not an integer and the second
6905 /// expression is not a pointer, true otherwise.
6906 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6907                                         Expr* PointerExpr, SourceLocation Loc,
6908                                         bool IsIntFirstExpr) {
6909   if (!PointerExpr->getType()->isPointerType() ||
6910       !Int.get()->getType()->isIntegerType())
6911     return false;
6912 
6913   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6914   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6915 
6916   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6917     << Expr1->getType() << Expr2->getType()
6918     << Expr1->getSourceRange() << Expr2->getSourceRange();
6919   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6920                             CK_IntegralToPointer);
6921   return true;
6922 }
6923 
6924 /// Simple conversion between integer and floating point types.
6925 ///
6926 /// Used when handling the OpenCL conditional operator where the
6927 /// condition is a vector while the other operands are scalar.
6928 ///
6929 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6930 /// types are either integer or floating type. Between the two
6931 /// operands, the type with the higher rank is defined as the "result
6932 /// type". The other operand needs to be promoted to the same type. No
6933 /// other type promotion is allowed. We cannot use
6934 /// UsualArithmeticConversions() for this purpose, since it always
6935 /// promotes promotable types.
6936 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6937                                             ExprResult &RHS,
6938                                             SourceLocation QuestionLoc) {
6939   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6940   if (LHS.isInvalid())
6941     return QualType();
6942   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6943   if (RHS.isInvalid())
6944     return QualType();
6945 
6946   // For conversion purposes, we ignore any qualifiers.
6947   // For example, "const float" and "float" are equivalent.
6948   QualType LHSType =
6949     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6950   QualType RHSType =
6951     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6952 
6953   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6954     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6955       << LHSType << LHS.get()->getSourceRange();
6956     return QualType();
6957   }
6958 
6959   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6960     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6961       << RHSType << RHS.get()->getSourceRange();
6962     return QualType();
6963   }
6964 
6965   // If both types are identical, no conversion is needed.
6966   if (LHSType == RHSType)
6967     return LHSType;
6968 
6969   // Now handle "real" floating types (i.e. float, double, long double).
6970   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6971     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6972                                  /*IsCompAssign = */ false);
6973 
6974   // Finally, we have two differing integer types.
6975   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6976   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6977 }
6978 
6979 /// Convert scalar operands to a vector that matches the
6980 ///        condition in length.
6981 ///
6982 /// Used when handling the OpenCL conditional operator where the
6983 /// condition is a vector while the other operands are scalar.
6984 ///
6985 /// We first compute the "result type" for the scalar operands
6986 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6987 /// into a vector of that type where the length matches the condition
6988 /// vector type. s6.11.6 requires that the element types of the result
6989 /// and the condition must have the same number of bits.
6990 static QualType
6991 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6992                               QualType CondTy, SourceLocation QuestionLoc) {
6993   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6994   if (ResTy.isNull()) return QualType();
6995 
6996   const VectorType *CV = CondTy->getAs<VectorType>();
6997   assert(CV);
6998 
6999   // Determine the vector result type
7000   unsigned NumElements = CV->getNumElements();
7001   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7002 
7003   // Ensure that all types have the same number of bits
7004   if (S.Context.getTypeSize(CV->getElementType())
7005       != S.Context.getTypeSize(ResTy)) {
7006     // Since VectorTy is created internally, it does not pretty print
7007     // with an OpenCL name. Instead, we just print a description.
7008     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7009     SmallString<64> Str;
7010     llvm::raw_svector_ostream OS(Str);
7011     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7012     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7013       << CondTy << OS.str();
7014     return QualType();
7015   }
7016 
7017   // Convert operands to the vector result type
7018   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7019   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7020 
7021   return VectorTy;
7022 }
7023 
7024 /// Return false if this is a valid OpenCL condition vector
7025 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7026                                        SourceLocation QuestionLoc) {
7027   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7028   // integral type.
7029   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7030   assert(CondTy);
7031   QualType EleTy = CondTy->getElementType();
7032   if (EleTy->isIntegerType()) return false;
7033 
7034   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7035     << Cond->getType() << Cond->getSourceRange();
7036   return true;
7037 }
7038 
7039 /// Return false if the vector condition type and the vector
7040 ///        result type are compatible.
7041 ///
7042 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7043 /// number of elements, and their element types have the same number
7044 /// of bits.
7045 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7046                               SourceLocation QuestionLoc) {
7047   const VectorType *CV = CondTy->getAs<VectorType>();
7048   const VectorType *RV = VecResTy->getAs<VectorType>();
7049   assert(CV && RV);
7050 
7051   if (CV->getNumElements() != RV->getNumElements()) {
7052     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7053       << CondTy << VecResTy;
7054     return true;
7055   }
7056 
7057   QualType CVE = CV->getElementType();
7058   QualType RVE = RV->getElementType();
7059 
7060   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7061     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7062       << CondTy << VecResTy;
7063     return true;
7064   }
7065 
7066   return false;
7067 }
7068 
7069 /// Return the resulting type for the conditional operator in
7070 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7071 ///        s6.3.i) when the condition is a vector type.
7072 static QualType
7073 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7074                              ExprResult &LHS, ExprResult &RHS,
7075                              SourceLocation QuestionLoc) {
7076   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7077   if (Cond.isInvalid())
7078     return QualType();
7079   QualType CondTy = Cond.get()->getType();
7080 
7081   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7082     return QualType();
7083 
7084   // If either operand is a vector then find the vector type of the
7085   // result as specified in OpenCL v1.1 s6.3.i.
7086   if (LHS.get()->getType()->isVectorType() ||
7087       RHS.get()->getType()->isVectorType()) {
7088     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7089                                               /*isCompAssign*/false,
7090                                               /*AllowBothBool*/true,
7091                                               /*AllowBoolConversions*/false);
7092     if (VecResTy.isNull()) return QualType();
7093     // The result type must match the condition type as specified in
7094     // OpenCL v1.1 s6.11.6.
7095     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7096       return QualType();
7097     return VecResTy;
7098   }
7099 
7100   // Both operands are scalar.
7101   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7102 }
7103 
7104 /// Return true if the Expr is block type
7105 static bool checkBlockType(Sema &S, const Expr *E) {
7106   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7107     QualType Ty = CE->getCallee()->getType();
7108     if (Ty->isBlockPointerType()) {
7109       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7110       return true;
7111     }
7112   }
7113   return false;
7114 }
7115 
7116 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7117 /// In that case, LHS = cond.
7118 /// C99 6.5.15
7119 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7120                                         ExprResult &RHS, ExprValueKind &VK,
7121                                         ExprObjectKind &OK,
7122                                         SourceLocation QuestionLoc) {
7123 
7124   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7125   if (!LHSResult.isUsable()) return QualType();
7126   LHS = LHSResult;
7127 
7128   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7129   if (!RHSResult.isUsable()) return QualType();
7130   RHS = RHSResult;
7131 
7132   // C++ is sufficiently different to merit its own checker.
7133   if (getLangOpts().CPlusPlus)
7134     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7135 
7136   VK = VK_RValue;
7137   OK = OK_Ordinary;
7138 
7139   // The OpenCL operator with a vector condition is sufficiently
7140   // different to merit its own checker.
7141   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7142     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7143 
7144   // First, check the condition.
7145   Cond = UsualUnaryConversions(Cond.get());
7146   if (Cond.isInvalid())
7147     return QualType();
7148   if (checkCondition(*this, Cond.get(), QuestionLoc))
7149     return QualType();
7150 
7151   // Now check the two expressions.
7152   if (LHS.get()->getType()->isVectorType() ||
7153       RHS.get()->getType()->isVectorType())
7154     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7155                                /*AllowBothBool*/true,
7156                                /*AllowBoolConversions*/false);
7157 
7158   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7159   if (LHS.isInvalid() || RHS.isInvalid())
7160     return QualType();
7161 
7162   QualType LHSTy = LHS.get()->getType();
7163   QualType RHSTy = RHS.get()->getType();
7164 
7165   // Diagnose attempts to convert between __float128 and long double where
7166   // such conversions currently can't be handled.
7167   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7168     Diag(QuestionLoc,
7169          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7170       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7171     return QualType();
7172   }
7173 
7174   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7175   // selection operator (?:).
7176   if (getLangOpts().OpenCL &&
7177       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7178     return QualType();
7179   }
7180 
7181   // If both operands have arithmetic type, do the usual arithmetic conversions
7182   // to find a common type: C99 6.5.15p3,5.
7183   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7184     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7185     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7186 
7187     return ResTy;
7188   }
7189 
7190   // If both operands are the same structure or union type, the result is that
7191   // type.
7192   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7193     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7194       if (LHSRT->getDecl() == RHSRT->getDecl())
7195         // "If both the operands have structure or union type, the result has
7196         // that type."  This implies that CV qualifiers are dropped.
7197         return LHSTy.getUnqualifiedType();
7198     // FIXME: Type of conditional expression must be complete in C mode.
7199   }
7200 
7201   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7202   // The following || allows only one side to be void (a GCC-ism).
7203   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7204     return checkConditionalVoidType(*this, LHS, RHS);
7205   }
7206 
7207   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7208   // the type of the other operand."
7209   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7210   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7211 
7212   // All objective-c pointer type analysis is done here.
7213   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7214                                                         QuestionLoc);
7215   if (LHS.isInvalid() || RHS.isInvalid())
7216     return QualType();
7217   if (!compositeType.isNull())
7218     return compositeType;
7219 
7220 
7221   // Handle block pointer types.
7222   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7223     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7224                                                      QuestionLoc);
7225 
7226   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7227   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7228     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7229                                                        QuestionLoc);
7230 
7231   // GCC compatibility: soften pointer/integer mismatch.  Note that
7232   // null pointers have been filtered out by this point.
7233   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7234       /*isIntFirstExpr=*/true))
7235     return RHSTy;
7236   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7237       /*isIntFirstExpr=*/false))
7238     return LHSTy;
7239 
7240   // Emit a better diagnostic if one of the expressions is a null pointer
7241   // constant and the other is not a pointer type. In this case, the user most
7242   // likely forgot to take the address of the other expression.
7243   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7244     return QualType();
7245 
7246   // Otherwise, the operands are not compatible.
7247   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7248     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7249     << RHS.get()->getSourceRange();
7250   return QualType();
7251 }
7252 
7253 /// FindCompositeObjCPointerType - Helper method to find composite type of
7254 /// two objective-c pointer types of the two input expressions.
7255 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7256                                             SourceLocation QuestionLoc) {
7257   QualType LHSTy = LHS.get()->getType();
7258   QualType RHSTy = RHS.get()->getType();
7259 
7260   // Handle things like Class and struct objc_class*.  Here we case the result
7261   // to the pseudo-builtin, because that will be implicitly cast back to the
7262   // redefinition type if an attempt is made to access its fields.
7263   if (LHSTy->isObjCClassType() &&
7264       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7265     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7266     return LHSTy;
7267   }
7268   if (RHSTy->isObjCClassType() &&
7269       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7270     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7271     return RHSTy;
7272   }
7273   // And the same for struct objc_object* / id
7274   if (LHSTy->isObjCIdType() &&
7275       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7276     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7277     return LHSTy;
7278   }
7279   if (RHSTy->isObjCIdType() &&
7280       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7281     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7282     return RHSTy;
7283   }
7284   // And the same for struct objc_selector* / SEL
7285   if (Context.isObjCSelType(LHSTy) &&
7286       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7287     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7288     return LHSTy;
7289   }
7290   if (Context.isObjCSelType(RHSTy) &&
7291       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7292     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7293     return RHSTy;
7294   }
7295   // Check constraints for Objective-C object pointers types.
7296   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7297 
7298     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7299       // Two identical object pointer types are always compatible.
7300       return LHSTy;
7301     }
7302     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7303     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7304     QualType compositeType = LHSTy;
7305 
7306     // If both operands are interfaces and either operand can be
7307     // assigned to the other, use that type as the composite
7308     // type. This allows
7309     //   xxx ? (A*) a : (B*) b
7310     // where B is a subclass of A.
7311     //
7312     // Additionally, as for assignment, if either type is 'id'
7313     // allow silent coercion. Finally, if the types are
7314     // incompatible then make sure to use 'id' as the composite
7315     // type so the result is acceptable for sending messages to.
7316 
7317     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7318     // It could return the composite type.
7319     if (!(compositeType =
7320           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7321       // Nothing more to do.
7322     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7323       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7324     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7325       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7326     } else if ((LHSTy->isObjCQualifiedIdType() ||
7327                 RHSTy->isObjCQualifiedIdType()) &&
7328                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7329       // Need to handle "id<xx>" explicitly.
7330       // GCC allows qualified id and any Objective-C type to devolve to
7331       // id. Currently localizing to here until clear this should be
7332       // part of ObjCQualifiedIdTypesAreCompatible.
7333       compositeType = Context.getObjCIdType();
7334     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7335       compositeType = Context.getObjCIdType();
7336     } else {
7337       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7338       << LHSTy << RHSTy
7339       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7340       QualType incompatTy = Context.getObjCIdType();
7341       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7342       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7343       return incompatTy;
7344     }
7345     // The object pointer types are compatible.
7346     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7347     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7348     return compositeType;
7349   }
7350   // Check Objective-C object pointer types and 'void *'
7351   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7352     if (getLangOpts().ObjCAutoRefCount) {
7353       // ARC forbids the implicit conversion of object pointers to 'void *',
7354       // so these types are not compatible.
7355       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7356           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7357       LHS = RHS = true;
7358       return QualType();
7359     }
7360     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7361     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7362     QualType destPointee
7363     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7364     QualType destType = Context.getPointerType(destPointee);
7365     // Add qualifiers if necessary.
7366     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7367     // Promote to void*.
7368     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7369     return destType;
7370   }
7371   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7372     if (getLangOpts().ObjCAutoRefCount) {
7373       // ARC forbids the implicit conversion of object pointers to 'void *',
7374       // so these types are not compatible.
7375       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7376           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7377       LHS = RHS = true;
7378       return QualType();
7379     }
7380     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7381     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7382     QualType destPointee
7383     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7384     QualType destType = Context.getPointerType(destPointee);
7385     // Add qualifiers if necessary.
7386     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7387     // Promote to void*.
7388     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7389     return destType;
7390   }
7391   return QualType();
7392 }
7393 
7394 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7395 /// ParenRange in parentheses.
7396 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7397                                const PartialDiagnostic &Note,
7398                                SourceRange ParenRange) {
7399   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7400   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7401       EndLoc.isValid()) {
7402     Self.Diag(Loc, Note)
7403       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7404       << FixItHint::CreateInsertion(EndLoc, ")");
7405   } else {
7406     // We can't display the parentheses, so just show the bare note.
7407     Self.Diag(Loc, Note) << ParenRange;
7408   }
7409 }
7410 
7411 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7412   return BinaryOperator::isAdditiveOp(Opc) ||
7413          BinaryOperator::isMultiplicativeOp(Opc) ||
7414          BinaryOperator::isShiftOp(Opc);
7415 }
7416 
7417 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7418 /// expression, either using a built-in or overloaded operator,
7419 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7420 /// expression.
7421 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7422                                    Expr **RHSExprs) {
7423   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7424   E = E->IgnoreImpCasts();
7425   E = E->IgnoreConversionOperator();
7426   E = E->IgnoreImpCasts();
7427   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7428     E = MTE->GetTemporaryExpr();
7429     E = E->IgnoreImpCasts();
7430   }
7431 
7432   // Built-in binary operator.
7433   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7434     if (IsArithmeticOp(OP->getOpcode())) {
7435       *Opcode = OP->getOpcode();
7436       *RHSExprs = OP->getRHS();
7437       return true;
7438     }
7439   }
7440 
7441   // Overloaded operator.
7442   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7443     if (Call->getNumArgs() != 2)
7444       return false;
7445 
7446     // Make sure this is really a binary operator that is safe to pass into
7447     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7448     OverloadedOperatorKind OO = Call->getOperator();
7449     if (OO < OO_Plus || OO > OO_Arrow ||
7450         OO == OO_PlusPlus || OO == OO_MinusMinus)
7451       return false;
7452 
7453     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7454     if (IsArithmeticOp(OpKind)) {
7455       *Opcode = OpKind;
7456       *RHSExprs = Call->getArg(1);
7457       return true;
7458     }
7459   }
7460 
7461   return false;
7462 }
7463 
7464 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7465 /// or is a logical expression such as (x==y) which has int type, but is
7466 /// commonly interpreted as boolean.
7467 static bool ExprLooksBoolean(Expr *E) {
7468   E = E->IgnoreParenImpCasts();
7469 
7470   if (E->getType()->isBooleanType())
7471     return true;
7472   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7473     return OP->isComparisonOp() || OP->isLogicalOp();
7474   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7475     return OP->getOpcode() == UO_LNot;
7476   if (E->getType()->isPointerType())
7477     return true;
7478   // FIXME: What about overloaded operator calls returning "unspecified boolean
7479   // type"s (commonly pointer-to-members)?
7480 
7481   return false;
7482 }
7483 
7484 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7485 /// and binary operator are mixed in a way that suggests the programmer assumed
7486 /// the conditional operator has higher precedence, for example:
7487 /// "int x = a + someBinaryCondition ? 1 : 2".
7488 static void DiagnoseConditionalPrecedence(Sema &Self,
7489                                           SourceLocation OpLoc,
7490                                           Expr *Condition,
7491                                           Expr *LHSExpr,
7492                                           Expr *RHSExpr) {
7493   BinaryOperatorKind CondOpcode;
7494   Expr *CondRHS;
7495 
7496   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7497     return;
7498   if (!ExprLooksBoolean(CondRHS))
7499     return;
7500 
7501   // The condition is an arithmetic binary expression, with a right-
7502   // hand side that looks boolean, so warn.
7503 
7504   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7505       << Condition->getSourceRange()
7506       << BinaryOperator::getOpcodeStr(CondOpcode);
7507 
7508   SuggestParentheses(
7509       Self, OpLoc,
7510       Self.PDiag(diag::note_precedence_silence)
7511           << BinaryOperator::getOpcodeStr(CondOpcode),
7512       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7513 
7514   SuggestParentheses(Self, OpLoc,
7515                      Self.PDiag(diag::note_precedence_conditional_first),
7516                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7517 }
7518 
7519 /// Compute the nullability of a conditional expression.
7520 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7521                                               QualType LHSTy, QualType RHSTy,
7522                                               ASTContext &Ctx) {
7523   if (!ResTy->isAnyPointerType())
7524     return ResTy;
7525 
7526   auto GetNullability = [&Ctx](QualType Ty) {
7527     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7528     if (Kind)
7529       return *Kind;
7530     return NullabilityKind::Unspecified;
7531   };
7532 
7533   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7534   NullabilityKind MergedKind;
7535 
7536   // Compute nullability of a binary conditional expression.
7537   if (IsBin) {
7538     if (LHSKind == NullabilityKind::NonNull)
7539       MergedKind = NullabilityKind::NonNull;
7540     else
7541       MergedKind = RHSKind;
7542   // Compute nullability of a normal conditional expression.
7543   } else {
7544     if (LHSKind == NullabilityKind::Nullable ||
7545         RHSKind == NullabilityKind::Nullable)
7546       MergedKind = NullabilityKind::Nullable;
7547     else if (LHSKind == NullabilityKind::NonNull)
7548       MergedKind = RHSKind;
7549     else if (RHSKind == NullabilityKind::NonNull)
7550       MergedKind = LHSKind;
7551     else
7552       MergedKind = NullabilityKind::Unspecified;
7553   }
7554 
7555   // Return if ResTy already has the correct nullability.
7556   if (GetNullability(ResTy) == MergedKind)
7557     return ResTy;
7558 
7559   // Strip all nullability from ResTy.
7560   while (ResTy->getNullability(Ctx))
7561     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7562 
7563   // Create a new AttributedType with the new nullability kind.
7564   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7565   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7566 }
7567 
7568 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7569 /// in the case of a the GNU conditional expr extension.
7570 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7571                                     SourceLocation ColonLoc,
7572                                     Expr *CondExpr, Expr *LHSExpr,
7573                                     Expr *RHSExpr) {
7574   if (!getLangOpts().CPlusPlus) {
7575     // C cannot handle TypoExpr nodes in the condition because it
7576     // doesn't handle dependent types properly, so make sure any TypoExprs have
7577     // been dealt with before checking the operands.
7578     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7579     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7580     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7581 
7582     if (!CondResult.isUsable())
7583       return ExprError();
7584 
7585     if (LHSExpr) {
7586       if (!LHSResult.isUsable())
7587         return ExprError();
7588     }
7589 
7590     if (!RHSResult.isUsable())
7591       return ExprError();
7592 
7593     CondExpr = CondResult.get();
7594     LHSExpr = LHSResult.get();
7595     RHSExpr = RHSResult.get();
7596   }
7597 
7598   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7599   // was the condition.
7600   OpaqueValueExpr *opaqueValue = nullptr;
7601   Expr *commonExpr = nullptr;
7602   if (!LHSExpr) {
7603     commonExpr = CondExpr;
7604     // Lower out placeholder types first.  This is important so that we don't
7605     // try to capture a placeholder. This happens in few cases in C++; such
7606     // as Objective-C++'s dictionary subscripting syntax.
7607     if (commonExpr->hasPlaceholderType()) {
7608       ExprResult result = CheckPlaceholderExpr(commonExpr);
7609       if (!result.isUsable()) return ExprError();
7610       commonExpr = result.get();
7611     }
7612     // We usually want to apply unary conversions *before* saving, except
7613     // in the special case of a C++ l-value conditional.
7614     if (!(getLangOpts().CPlusPlus
7615           && !commonExpr->isTypeDependent()
7616           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7617           && commonExpr->isGLValue()
7618           && commonExpr->isOrdinaryOrBitFieldObject()
7619           && RHSExpr->isOrdinaryOrBitFieldObject()
7620           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7621       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7622       if (commonRes.isInvalid())
7623         return ExprError();
7624       commonExpr = commonRes.get();
7625     }
7626 
7627     // If the common expression is a class or array prvalue, materialize it
7628     // so that we can safely refer to it multiple times.
7629     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7630                                    commonExpr->getType()->isArrayType())) {
7631       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7632       if (MatExpr.isInvalid())
7633         return ExprError();
7634       commonExpr = MatExpr.get();
7635     }
7636 
7637     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7638                                                 commonExpr->getType(),
7639                                                 commonExpr->getValueKind(),
7640                                                 commonExpr->getObjectKind(),
7641                                                 commonExpr);
7642     LHSExpr = CondExpr = opaqueValue;
7643   }
7644 
7645   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7646   ExprValueKind VK = VK_RValue;
7647   ExprObjectKind OK = OK_Ordinary;
7648   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7649   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7650                                              VK, OK, QuestionLoc);
7651   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7652       RHS.isInvalid())
7653     return ExprError();
7654 
7655   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7656                                 RHS.get());
7657 
7658   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7659 
7660   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7661                                          Context);
7662 
7663   if (!commonExpr)
7664     return new (Context)
7665         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7666                             RHS.get(), result, VK, OK);
7667 
7668   return new (Context) BinaryConditionalOperator(
7669       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7670       ColonLoc, result, VK, OK);
7671 }
7672 
7673 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7674 // being closely modeled after the C99 spec:-). The odd characteristic of this
7675 // routine is it effectively iqnores the qualifiers on the top level pointee.
7676 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7677 // FIXME: add a couple examples in this comment.
7678 static Sema::AssignConvertType
7679 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7680   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7681   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7682 
7683   // get the "pointed to" type (ignoring qualifiers at the top level)
7684   const Type *lhptee, *rhptee;
7685   Qualifiers lhq, rhq;
7686   std::tie(lhptee, lhq) =
7687       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7688   std::tie(rhptee, rhq) =
7689       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7690 
7691   Sema::AssignConvertType ConvTy = Sema::Compatible;
7692 
7693   // C99 6.5.16.1p1: This following citation is common to constraints
7694   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7695   // qualifiers of the type *pointed to* by the right;
7696 
7697   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7698   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7699       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7700     // Ignore lifetime for further calculation.
7701     lhq.removeObjCLifetime();
7702     rhq.removeObjCLifetime();
7703   }
7704 
7705   if (!lhq.compatiblyIncludes(rhq)) {
7706     // Treat address-space mismatches as fatal.  TODO: address subspaces
7707     if (!lhq.isAddressSpaceSupersetOf(rhq))
7708       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7709 
7710     // It's okay to add or remove GC or lifetime qualifiers when converting to
7711     // and from void*.
7712     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7713                         .compatiblyIncludes(
7714                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7715              && (lhptee->isVoidType() || rhptee->isVoidType()))
7716       ; // keep old
7717 
7718     // Treat lifetime mismatches as fatal.
7719     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7720       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7721 
7722     // For GCC/MS compatibility, other qualifier mismatches are treated
7723     // as still compatible in C.
7724     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7725   }
7726 
7727   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7728   // incomplete type and the other is a pointer to a qualified or unqualified
7729   // version of void...
7730   if (lhptee->isVoidType()) {
7731     if (rhptee->isIncompleteOrObjectType())
7732       return ConvTy;
7733 
7734     // As an extension, we allow cast to/from void* to function pointer.
7735     assert(rhptee->isFunctionType());
7736     return Sema::FunctionVoidPointer;
7737   }
7738 
7739   if (rhptee->isVoidType()) {
7740     if (lhptee->isIncompleteOrObjectType())
7741       return ConvTy;
7742 
7743     // As an extension, we allow cast to/from void* to function pointer.
7744     assert(lhptee->isFunctionType());
7745     return Sema::FunctionVoidPointer;
7746   }
7747 
7748   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7749   // unqualified versions of compatible types, ...
7750   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7751   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7752     // Check if the pointee types are compatible ignoring the sign.
7753     // We explicitly check for char so that we catch "char" vs
7754     // "unsigned char" on systems where "char" is unsigned.
7755     if (lhptee->isCharType())
7756       ltrans = S.Context.UnsignedCharTy;
7757     else if (lhptee->hasSignedIntegerRepresentation())
7758       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7759 
7760     if (rhptee->isCharType())
7761       rtrans = S.Context.UnsignedCharTy;
7762     else if (rhptee->hasSignedIntegerRepresentation())
7763       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7764 
7765     if (ltrans == rtrans) {
7766       // Types are compatible ignoring the sign. Qualifier incompatibility
7767       // takes priority over sign incompatibility because the sign
7768       // warning can be disabled.
7769       if (ConvTy != Sema::Compatible)
7770         return ConvTy;
7771 
7772       return Sema::IncompatiblePointerSign;
7773     }
7774 
7775     // If we are a multi-level pointer, it's possible that our issue is simply
7776     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7777     // the eventual target type is the same and the pointers have the same
7778     // level of indirection, this must be the issue.
7779     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7780       do {
7781         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7782         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7783       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7784 
7785       if (lhptee == rhptee)
7786         return Sema::IncompatibleNestedPointerQualifiers;
7787     }
7788 
7789     // General pointer incompatibility takes priority over qualifiers.
7790     return Sema::IncompatiblePointer;
7791   }
7792   if (!S.getLangOpts().CPlusPlus &&
7793       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7794     return Sema::IncompatiblePointer;
7795   return ConvTy;
7796 }
7797 
7798 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7799 /// block pointer types are compatible or whether a block and normal pointer
7800 /// are compatible. It is more restrict than comparing two function pointer
7801 // types.
7802 static Sema::AssignConvertType
7803 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7804                                     QualType RHSType) {
7805   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7806   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7807 
7808   QualType lhptee, rhptee;
7809 
7810   // get the "pointed to" type (ignoring qualifiers at the top level)
7811   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7812   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7813 
7814   // In C++, the types have to match exactly.
7815   if (S.getLangOpts().CPlusPlus)
7816     return Sema::IncompatibleBlockPointer;
7817 
7818   Sema::AssignConvertType ConvTy = Sema::Compatible;
7819 
7820   // For blocks we enforce that qualifiers are identical.
7821   Qualifiers LQuals = lhptee.getLocalQualifiers();
7822   Qualifiers RQuals = rhptee.getLocalQualifiers();
7823   if (S.getLangOpts().OpenCL) {
7824     LQuals.removeAddressSpace();
7825     RQuals.removeAddressSpace();
7826   }
7827   if (LQuals != RQuals)
7828     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7829 
7830   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7831   // assignment.
7832   // The current behavior is similar to C++ lambdas. A block might be
7833   // assigned to a variable iff its return type and parameters are compatible
7834   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7835   // an assignment. Presumably it should behave in way that a function pointer
7836   // assignment does in C, so for each parameter and return type:
7837   //  * CVR and address space of LHS should be a superset of CVR and address
7838   //  space of RHS.
7839   //  * unqualified types should be compatible.
7840   if (S.getLangOpts().OpenCL) {
7841     if (!S.Context.typesAreBlockPointerCompatible(
7842             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7843             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7844       return Sema::IncompatibleBlockPointer;
7845   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7846     return Sema::IncompatibleBlockPointer;
7847 
7848   return ConvTy;
7849 }
7850 
7851 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7852 /// for assignment compatibility.
7853 static Sema::AssignConvertType
7854 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7855                                    QualType RHSType) {
7856   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7857   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7858 
7859   if (LHSType->isObjCBuiltinType()) {
7860     // Class is not compatible with ObjC object pointers.
7861     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7862         !RHSType->isObjCQualifiedClassType())
7863       return Sema::IncompatiblePointer;
7864     return Sema::Compatible;
7865   }
7866   if (RHSType->isObjCBuiltinType()) {
7867     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7868         !LHSType->isObjCQualifiedClassType())
7869       return Sema::IncompatiblePointer;
7870     return Sema::Compatible;
7871   }
7872   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7873   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7874 
7875   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7876       // make an exception for id<P>
7877       !LHSType->isObjCQualifiedIdType())
7878     return Sema::CompatiblePointerDiscardsQualifiers;
7879 
7880   if (S.Context.typesAreCompatible(LHSType, RHSType))
7881     return Sema::Compatible;
7882   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7883     return Sema::IncompatibleObjCQualifiedId;
7884   return Sema::IncompatiblePointer;
7885 }
7886 
7887 Sema::AssignConvertType
7888 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7889                                  QualType LHSType, QualType RHSType) {
7890   // Fake up an opaque expression.  We don't actually care about what
7891   // cast operations are required, so if CheckAssignmentConstraints
7892   // adds casts to this they'll be wasted, but fortunately that doesn't
7893   // usually happen on valid code.
7894   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7895   ExprResult RHSPtr = &RHSExpr;
7896   CastKind K;
7897 
7898   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7899 }
7900 
7901 /// This helper function returns true if QT is a vector type that has element
7902 /// type ElementType.
7903 static bool isVector(QualType QT, QualType ElementType) {
7904   if (const VectorType *VT = QT->getAs<VectorType>())
7905     return VT->getElementType() == ElementType;
7906   return false;
7907 }
7908 
7909 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7910 /// has code to accommodate several GCC extensions when type checking
7911 /// pointers. Here are some objectionable examples that GCC considers warnings:
7912 ///
7913 ///  int a, *pint;
7914 ///  short *pshort;
7915 ///  struct foo *pfoo;
7916 ///
7917 ///  pint = pshort; // warning: assignment from incompatible pointer type
7918 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7919 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7920 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7921 ///
7922 /// As a result, the code for dealing with pointers is more complex than the
7923 /// C99 spec dictates.
7924 ///
7925 /// Sets 'Kind' for any result kind except Incompatible.
7926 Sema::AssignConvertType
7927 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7928                                  CastKind &Kind, bool ConvertRHS) {
7929   QualType RHSType = RHS.get()->getType();
7930   QualType OrigLHSType = LHSType;
7931 
7932   // Get canonical types.  We're not formatting these types, just comparing
7933   // them.
7934   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7935   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7936 
7937   // Common case: no conversion required.
7938   if (LHSType == RHSType) {
7939     Kind = CK_NoOp;
7940     return Compatible;
7941   }
7942 
7943   // If we have an atomic type, try a non-atomic assignment, then just add an
7944   // atomic qualification step.
7945   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7946     Sema::AssignConvertType result =
7947       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7948     if (result != Compatible)
7949       return result;
7950     if (Kind != CK_NoOp && ConvertRHS)
7951       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7952     Kind = CK_NonAtomicToAtomic;
7953     return Compatible;
7954   }
7955 
7956   // If the left-hand side is a reference type, then we are in a
7957   // (rare!) case where we've allowed the use of references in C,
7958   // e.g., as a parameter type in a built-in function. In this case,
7959   // just make sure that the type referenced is compatible with the
7960   // right-hand side type. The caller is responsible for adjusting
7961   // LHSType so that the resulting expression does not have reference
7962   // type.
7963   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7964     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7965       Kind = CK_LValueBitCast;
7966       return Compatible;
7967     }
7968     return Incompatible;
7969   }
7970 
7971   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7972   // to the same ExtVector type.
7973   if (LHSType->isExtVectorType()) {
7974     if (RHSType->isExtVectorType())
7975       return Incompatible;
7976     if (RHSType->isArithmeticType()) {
7977       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7978       if (ConvertRHS)
7979         RHS = prepareVectorSplat(LHSType, RHS.get());
7980       Kind = CK_VectorSplat;
7981       return Compatible;
7982     }
7983   }
7984 
7985   // Conversions to or from vector type.
7986   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7987     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7988       // Allow assignments of an AltiVec vector type to an equivalent GCC
7989       // vector type and vice versa
7990       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7991         Kind = CK_BitCast;
7992         return Compatible;
7993       }
7994 
7995       // If we are allowing lax vector conversions, and LHS and RHS are both
7996       // vectors, the total size only needs to be the same. This is a bitcast;
7997       // no bits are changed but the result type is different.
7998       if (isLaxVectorConversion(RHSType, LHSType)) {
7999         Kind = CK_BitCast;
8000         return IncompatibleVectors;
8001       }
8002     }
8003 
8004     // When the RHS comes from another lax conversion (e.g. binops between
8005     // scalars and vectors) the result is canonicalized as a vector. When the
8006     // LHS is also a vector, the lax is allowed by the condition above. Handle
8007     // the case where LHS is a scalar.
8008     if (LHSType->isScalarType()) {
8009       const VectorType *VecType = RHSType->getAs<VectorType>();
8010       if (VecType && VecType->getNumElements() == 1 &&
8011           isLaxVectorConversion(RHSType, LHSType)) {
8012         ExprResult *VecExpr = &RHS;
8013         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8014         Kind = CK_BitCast;
8015         return Compatible;
8016       }
8017     }
8018 
8019     return Incompatible;
8020   }
8021 
8022   // Diagnose attempts to convert between __float128 and long double where
8023   // such conversions currently can't be handled.
8024   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8025     return Incompatible;
8026 
8027   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8028   // discards the imaginary part.
8029   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8030       !LHSType->getAs<ComplexType>())
8031     return Incompatible;
8032 
8033   // Arithmetic conversions.
8034   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8035       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8036     if (ConvertRHS)
8037       Kind = PrepareScalarCast(RHS, LHSType);
8038     return Compatible;
8039   }
8040 
8041   // Conversions to normal pointers.
8042   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8043     // U* -> T*
8044     if (isa<PointerType>(RHSType)) {
8045       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8046       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8047       if (AddrSpaceL != AddrSpaceR)
8048         Kind = CK_AddressSpaceConversion;
8049       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8050         Kind = CK_NoOp;
8051       else
8052         Kind = CK_BitCast;
8053       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8054     }
8055 
8056     // int -> T*
8057     if (RHSType->isIntegerType()) {
8058       Kind = CK_IntegralToPointer; // FIXME: null?
8059       return IntToPointer;
8060     }
8061 
8062     // C pointers are not compatible with ObjC object pointers,
8063     // with two exceptions:
8064     if (isa<ObjCObjectPointerType>(RHSType)) {
8065       //  - conversions to void*
8066       if (LHSPointer->getPointeeType()->isVoidType()) {
8067         Kind = CK_BitCast;
8068         return Compatible;
8069       }
8070 
8071       //  - conversions from 'Class' to the redefinition type
8072       if (RHSType->isObjCClassType() &&
8073           Context.hasSameType(LHSType,
8074                               Context.getObjCClassRedefinitionType())) {
8075         Kind = CK_BitCast;
8076         return Compatible;
8077       }
8078 
8079       Kind = CK_BitCast;
8080       return IncompatiblePointer;
8081     }
8082 
8083     // U^ -> void*
8084     if (RHSType->getAs<BlockPointerType>()) {
8085       if (LHSPointer->getPointeeType()->isVoidType()) {
8086         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8087         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8088                                 ->getPointeeType()
8089                                 .getAddressSpace();
8090         Kind =
8091             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8092         return Compatible;
8093       }
8094     }
8095 
8096     return Incompatible;
8097   }
8098 
8099   // Conversions to block pointers.
8100   if (isa<BlockPointerType>(LHSType)) {
8101     // U^ -> T^
8102     if (RHSType->isBlockPointerType()) {
8103       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8104                               ->getPointeeType()
8105                               .getAddressSpace();
8106       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8107                               ->getPointeeType()
8108                               .getAddressSpace();
8109       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8110       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8111     }
8112 
8113     // int or null -> T^
8114     if (RHSType->isIntegerType()) {
8115       Kind = CK_IntegralToPointer; // FIXME: null
8116       return IntToBlockPointer;
8117     }
8118 
8119     // id -> T^
8120     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8121       Kind = CK_AnyPointerToBlockPointerCast;
8122       return Compatible;
8123     }
8124 
8125     // void* -> T^
8126     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8127       if (RHSPT->getPointeeType()->isVoidType()) {
8128         Kind = CK_AnyPointerToBlockPointerCast;
8129         return Compatible;
8130       }
8131 
8132     return Incompatible;
8133   }
8134 
8135   // Conversions to Objective-C pointers.
8136   if (isa<ObjCObjectPointerType>(LHSType)) {
8137     // A* -> B*
8138     if (RHSType->isObjCObjectPointerType()) {
8139       Kind = CK_BitCast;
8140       Sema::AssignConvertType result =
8141         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8142       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8143           result == Compatible &&
8144           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8145         result = IncompatibleObjCWeakRef;
8146       return result;
8147     }
8148 
8149     // int or null -> A*
8150     if (RHSType->isIntegerType()) {
8151       Kind = CK_IntegralToPointer; // FIXME: null
8152       return IntToPointer;
8153     }
8154 
8155     // In general, C pointers are not compatible with ObjC object pointers,
8156     // with two exceptions:
8157     if (isa<PointerType>(RHSType)) {
8158       Kind = CK_CPointerToObjCPointerCast;
8159 
8160       //  - conversions from 'void*'
8161       if (RHSType->isVoidPointerType()) {
8162         return Compatible;
8163       }
8164 
8165       //  - conversions to 'Class' from its redefinition type
8166       if (LHSType->isObjCClassType() &&
8167           Context.hasSameType(RHSType,
8168                               Context.getObjCClassRedefinitionType())) {
8169         return Compatible;
8170       }
8171 
8172       return IncompatiblePointer;
8173     }
8174 
8175     // Only under strict condition T^ is compatible with an Objective-C pointer.
8176     if (RHSType->isBlockPointerType() &&
8177         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8178       if (ConvertRHS)
8179         maybeExtendBlockObject(RHS);
8180       Kind = CK_BlockPointerToObjCPointerCast;
8181       return Compatible;
8182     }
8183 
8184     return Incompatible;
8185   }
8186 
8187   // Conversions from pointers that are not covered by the above.
8188   if (isa<PointerType>(RHSType)) {
8189     // T* -> _Bool
8190     if (LHSType == Context.BoolTy) {
8191       Kind = CK_PointerToBoolean;
8192       return Compatible;
8193     }
8194 
8195     // T* -> int
8196     if (LHSType->isIntegerType()) {
8197       Kind = CK_PointerToIntegral;
8198       return PointerToInt;
8199     }
8200 
8201     return Incompatible;
8202   }
8203 
8204   // Conversions from Objective-C pointers that are not covered by the above.
8205   if (isa<ObjCObjectPointerType>(RHSType)) {
8206     // T* -> _Bool
8207     if (LHSType == Context.BoolTy) {
8208       Kind = CK_PointerToBoolean;
8209       return Compatible;
8210     }
8211 
8212     // T* -> int
8213     if (LHSType->isIntegerType()) {
8214       Kind = CK_PointerToIntegral;
8215       return PointerToInt;
8216     }
8217 
8218     return Incompatible;
8219   }
8220 
8221   // struct A -> struct B
8222   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8223     if (Context.typesAreCompatible(LHSType, RHSType)) {
8224       Kind = CK_NoOp;
8225       return Compatible;
8226     }
8227   }
8228 
8229   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8230     Kind = CK_IntToOCLSampler;
8231     return Compatible;
8232   }
8233 
8234   return Incompatible;
8235 }
8236 
8237 /// Constructs a transparent union from an expression that is
8238 /// used to initialize the transparent union.
8239 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8240                                       ExprResult &EResult, QualType UnionType,
8241                                       FieldDecl *Field) {
8242   // Build an initializer list that designates the appropriate member
8243   // of the transparent union.
8244   Expr *E = EResult.get();
8245   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8246                                                    E, SourceLocation());
8247   Initializer->setType(UnionType);
8248   Initializer->setInitializedFieldInUnion(Field);
8249 
8250   // Build a compound literal constructing a value of the transparent
8251   // union type from this initializer list.
8252   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8253   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8254                                         VK_RValue, Initializer, false);
8255 }
8256 
8257 Sema::AssignConvertType
8258 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8259                                                ExprResult &RHS) {
8260   QualType RHSType = RHS.get()->getType();
8261 
8262   // If the ArgType is a Union type, we want to handle a potential
8263   // transparent_union GCC extension.
8264   const RecordType *UT = ArgType->getAsUnionType();
8265   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8266     return Incompatible;
8267 
8268   // The field to initialize within the transparent union.
8269   RecordDecl *UD = UT->getDecl();
8270   FieldDecl *InitField = nullptr;
8271   // It's compatible if the expression matches any of the fields.
8272   for (auto *it : UD->fields()) {
8273     if (it->getType()->isPointerType()) {
8274       // If the transparent union contains a pointer type, we allow:
8275       // 1) void pointer
8276       // 2) null pointer constant
8277       if (RHSType->isPointerType())
8278         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8279           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8280           InitField = it;
8281           break;
8282         }
8283 
8284       if (RHS.get()->isNullPointerConstant(Context,
8285                                            Expr::NPC_ValueDependentIsNull)) {
8286         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8287                                 CK_NullToPointer);
8288         InitField = it;
8289         break;
8290       }
8291     }
8292 
8293     CastKind Kind;
8294     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8295           == Compatible) {
8296       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8297       InitField = it;
8298       break;
8299     }
8300   }
8301 
8302   if (!InitField)
8303     return Incompatible;
8304 
8305   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8306   return Compatible;
8307 }
8308 
8309 Sema::AssignConvertType
8310 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8311                                        bool Diagnose,
8312                                        bool DiagnoseCFAudited,
8313                                        bool ConvertRHS) {
8314   // We need to be able to tell the caller whether we diagnosed a problem, if
8315   // they ask us to issue diagnostics.
8316   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8317 
8318   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8319   // we can't avoid *all* modifications at the moment, so we need some somewhere
8320   // to put the updated value.
8321   ExprResult LocalRHS = CallerRHS;
8322   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8323 
8324   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8325     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8326       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8327           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8328         Diag(RHS.get()->getExprLoc(),
8329              diag::warn_noderef_to_dereferenceable_pointer)
8330             << RHS.get()->getSourceRange();
8331       }
8332     }
8333   }
8334 
8335   if (getLangOpts().CPlusPlus) {
8336     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8337       // C++ 5.17p3: If the left operand is not of class type, the
8338       // expression is implicitly converted (C++ 4) to the
8339       // cv-unqualified type of the left operand.
8340       QualType RHSType = RHS.get()->getType();
8341       if (Diagnose) {
8342         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8343                                         AA_Assigning);
8344       } else {
8345         ImplicitConversionSequence ICS =
8346             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8347                                   /*SuppressUserConversions=*/false,
8348                                   /*AllowExplicit=*/false,
8349                                   /*InOverloadResolution=*/false,
8350                                   /*CStyle=*/false,
8351                                   /*AllowObjCWritebackConversion=*/false);
8352         if (ICS.isFailure())
8353           return Incompatible;
8354         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8355                                         ICS, AA_Assigning);
8356       }
8357       if (RHS.isInvalid())
8358         return Incompatible;
8359       Sema::AssignConvertType result = Compatible;
8360       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8361           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8362         result = IncompatibleObjCWeakRef;
8363       return result;
8364     }
8365 
8366     // FIXME: Currently, we fall through and treat C++ classes like C
8367     // structures.
8368     // FIXME: We also fall through for atomics; not sure what should
8369     // happen there, though.
8370   } else if (RHS.get()->getType() == Context.OverloadTy) {
8371     // As a set of extensions to C, we support overloading on functions. These
8372     // functions need to be resolved here.
8373     DeclAccessPair DAP;
8374     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8375             RHS.get(), LHSType, /*Complain=*/false, DAP))
8376       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8377     else
8378       return Incompatible;
8379   }
8380 
8381   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8382   // a null pointer constant.
8383   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8384        LHSType->isBlockPointerType()) &&
8385       RHS.get()->isNullPointerConstant(Context,
8386                                        Expr::NPC_ValueDependentIsNull)) {
8387     if (Diagnose || ConvertRHS) {
8388       CastKind Kind;
8389       CXXCastPath Path;
8390       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8391                              /*IgnoreBaseAccess=*/false, Diagnose);
8392       if (ConvertRHS)
8393         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8394     }
8395     return Compatible;
8396   }
8397 
8398   // OpenCL queue_t type assignment.
8399   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8400                                  Context, Expr::NPC_ValueDependentIsNull)) {
8401     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8402     return Compatible;
8403   }
8404 
8405   // This check seems unnatural, however it is necessary to ensure the proper
8406   // conversion of functions/arrays. If the conversion were done for all
8407   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8408   // expressions that suppress this implicit conversion (&, sizeof).
8409   //
8410   // Suppress this for references: C++ 8.5.3p5.
8411   if (!LHSType->isReferenceType()) {
8412     // FIXME: We potentially allocate here even if ConvertRHS is false.
8413     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8414     if (RHS.isInvalid())
8415       return Incompatible;
8416   }
8417   CastKind Kind;
8418   Sema::AssignConvertType result =
8419     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8420 
8421   // C99 6.5.16.1p2: The value of the right operand is converted to the
8422   // type of the assignment expression.
8423   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8424   // so that we can use references in built-in functions even in C.
8425   // The getNonReferenceType() call makes sure that the resulting expression
8426   // does not have reference type.
8427   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8428     QualType Ty = LHSType.getNonLValueExprType(Context);
8429     Expr *E = RHS.get();
8430 
8431     // Check for various Objective-C errors. If we are not reporting
8432     // diagnostics and just checking for errors, e.g., during overload
8433     // resolution, return Incompatible to indicate the failure.
8434     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8435         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8436                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8437       if (!Diagnose)
8438         return Incompatible;
8439     }
8440     if (getLangOpts().ObjC &&
8441         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8442                                            E->getType(), E, Diagnose) ||
8443          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8444       if (!Diagnose)
8445         return Incompatible;
8446       // Replace the expression with a corrected version and continue so we
8447       // can find further errors.
8448       RHS = E;
8449       return Compatible;
8450     }
8451 
8452     if (ConvertRHS)
8453       RHS = ImpCastExprToType(E, Ty, Kind);
8454   }
8455 
8456   return result;
8457 }
8458 
8459 namespace {
8460 /// The original operand to an operator, prior to the application of the usual
8461 /// arithmetic conversions and converting the arguments of a builtin operator
8462 /// candidate.
8463 struct OriginalOperand {
8464   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8465     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8466       Op = MTE->GetTemporaryExpr();
8467     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8468       Op = BTE->getSubExpr();
8469     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8470       Orig = ICE->getSubExprAsWritten();
8471       Conversion = ICE->getConversionFunction();
8472     }
8473   }
8474 
8475   QualType getType() const { return Orig->getType(); }
8476 
8477   Expr *Orig;
8478   NamedDecl *Conversion;
8479 };
8480 }
8481 
8482 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8483                                ExprResult &RHS) {
8484   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8485 
8486   Diag(Loc, diag::err_typecheck_invalid_operands)
8487     << OrigLHS.getType() << OrigRHS.getType()
8488     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8489 
8490   // If a user-defined conversion was applied to either of the operands prior
8491   // to applying the built-in operator rules, tell the user about it.
8492   if (OrigLHS.Conversion) {
8493     Diag(OrigLHS.Conversion->getLocation(),
8494          diag::note_typecheck_invalid_operands_converted)
8495       << 0 << LHS.get()->getType();
8496   }
8497   if (OrigRHS.Conversion) {
8498     Diag(OrigRHS.Conversion->getLocation(),
8499          diag::note_typecheck_invalid_operands_converted)
8500       << 1 << RHS.get()->getType();
8501   }
8502 
8503   return QualType();
8504 }
8505 
8506 // Diagnose cases where a scalar was implicitly converted to a vector and
8507 // diagnose the underlying types. Otherwise, diagnose the error
8508 // as invalid vector logical operands for non-C++ cases.
8509 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8510                                             ExprResult &RHS) {
8511   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8512   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8513 
8514   bool LHSNatVec = LHSType->isVectorType();
8515   bool RHSNatVec = RHSType->isVectorType();
8516 
8517   if (!(LHSNatVec && RHSNatVec)) {
8518     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8519     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8520     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8521         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8522         << Vector->getSourceRange();
8523     return QualType();
8524   }
8525 
8526   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8527       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8528       << RHS.get()->getSourceRange();
8529 
8530   return QualType();
8531 }
8532 
8533 /// Try to convert a value of non-vector type to a vector type by converting
8534 /// the type to the element type of the vector and then performing a splat.
8535 /// If the language is OpenCL, we only use conversions that promote scalar
8536 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8537 /// for float->int.
8538 ///
8539 /// OpenCL V2.0 6.2.6.p2:
8540 /// An error shall occur if any scalar operand type has greater rank
8541 /// than the type of the vector element.
8542 ///
8543 /// \param scalar - if non-null, actually perform the conversions
8544 /// \return true if the operation fails (but without diagnosing the failure)
8545 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8546                                      QualType scalarTy,
8547                                      QualType vectorEltTy,
8548                                      QualType vectorTy,
8549                                      unsigned &DiagID) {
8550   // The conversion to apply to the scalar before splatting it,
8551   // if necessary.
8552   CastKind scalarCast = CK_NoOp;
8553 
8554   if (vectorEltTy->isIntegralType(S.Context)) {
8555     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8556         (scalarTy->isIntegerType() &&
8557          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8558       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8559       return true;
8560     }
8561     if (!scalarTy->isIntegralType(S.Context))
8562       return true;
8563     scalarCast = CK_IntegralCast;
8564   } else if (vectorEltTy->isRealFloatingType()) {
8565     if (scalarTy->isRealFloatingType()) {
8566       if (S.getLangOpts().OpenCL &&
8567           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8568         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8569         return true;
8570       }
8571       scalarCast = CK_FloatingCast;
8572     }
8573     else if (scalarTy->isIntegralType(S.Context))
8574       scalarCast = CK_IntegralToFloating;
8575     else
8576       return true;
8577   } else {
8578     return true;
8579   }
8580 
8581   // Adjust scalar if desired.
8582   if (scalar) {
8583     if (scalarCast != CK_NoOp)
8584       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8585     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8586   }
8587   return false;
8588 }
8589 
8590 /// Convert vector E to a vector with the same number of elements but different
8591 /// element type.
8592 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8593   const auto *VecTy = E->getType()->getAs<VectorType>();
8594   assert(VecTy && "Expression E must be a vector");
8595   QualType NewVecTy = S.Context.getVectorType(ElementType,
8596                                               VecTy->getNumElements(),
8597                                               VecTy->getVectorKind());
8598 
8599   // Look through the implicit cast. Return the subexpression if its type is
8600   // NewVecTy.
8601   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8602     if (ICE->getSubExpr()->getType() == NewVecTy)
8603       return ICE->getSubExpr();
8604 
8605   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8606   return S.ImpCastExprToType(E, NewVecTy, Cast);
8607 }
8608 
8609 /// Test if a (constant) integer Int can be casted to another integer type
8610 /// IntTy without losing precision.
8611 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8612                                       QualType OtherIntTy) {
8613   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8614 
8615   // Reject cases where the value of the Int is unknown as that would
8616   // possibly cause truncation, but accept cases where the scalar can be
8617   // demoted without loss of precision.
8618   Expr::EvalResult EVResult;
8619   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8620   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8621   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8622   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8623 
8624   if (CstInt) {
8625     // If the scalar is constant and is of a higher order and has more active
8626     // bits that the vector element type, reject it.
8627     llvm::APSInt Result = EVResult.Val.getInt();
8628     unsigned NumBits = IntSigned
8629                            ? (Result.isNegative() ? Result.getMinSignedBits()
8630                                                   : Result.getActiveBits())
8631                            : Result.getActiveBits();
8632     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8633       return true;
8634 
8635     // If the signedness of the scalar type and the vector element type
8636     // differs and the number of bits is greater than that of the vector
8637     // element reject it.
8638     return (IntSigned != OtherIntSigned &&
8639             NumBits > S.Context.getIntWidth(OtherIntTy));
8640   }
8641 
8642   // Reject cases where the value of the scalar is not constant and it's
8643   // order is greater than that of the vector element type.
8644   return (Order < 0);
8645 }
8646 
8647 /// Test if a (constant) integer Int can be casted to floating point type
8648 /// FloatTy without losing precision.
8649 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8650                                      QualType FloatTy) {
8651   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8652 
8653   // Determine if the integer constant can be expressed as a floating point
8654   // number of the appropriate type.
8655   Expr::EvalResult EVResult;
8656   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8657 
8658   uint64_t Bits = 0;
8659   if (CstInt) {
8660     // Reject constants that would be truncated if they were converted to
8661     // the floating point type. Test by simple to/from conversion.
8662     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8663     //        could be avoided if there was a convertFromAPInt method
8664     //        which could signal back if implicit truncation occurred.
8665     llvm::APSInt Result = EVResult.Val.getInt();
8666     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8667     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8668                            llvm::APFloat::rmTowardZero);
8669     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8670                              !IntTy->hasSignedIntegerRepresentation());
8671     bool Ignored = false;
8672     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8673                            &Ignored);
8674     if (Result != ConvertBack)
8675       return true;
8676   } else {
8677     // Reject types that cannot be fully encoded into the mantissa of
8678     // the float.
8679     Bits = S.Context.getTypeSize(IntTy);
8680     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8681         S.Context.getFloatTypeSemantics(FloatTy));
8682     if (Bits > FloatPrec)
8683       return true;
8684   }
8685 
8686   return false;
8687 }
8688 
8689 /// Attempt to convert and splat Scalar into a vector whose types matches
8690 /// Vector following GCC conversion rules. The rule is that implicit
8691 /// conversion can occur when Scalar can be casted to match Vector's element
8692 /// type without causing truncation of Scalar.
8693 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8694                                         ExprResult *Vector) {
8695   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8696   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8697   const VectorType *VT = VectorTy->getAs<VectorType>();
8698 
8699   assert(!isa<ExtVectorType>(VT) &&
8700          "ExtVectorTypes should not be handled here!");
8701 
8702   QualType VectorEltTy = VT->getElementType();
8703 
8704   // Reject cases where the vector element type or the scalar element type are
8705   // not integral or floating point types.
8706   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8707     return true;
8708 
8709   // The conversion to apply to the scalar before splatting it,
8710   // if necessary.
8711   CastKind ScalarCast = CK_NoOp;
8712 
8713   // Accept cases where the vector elements are integers and the scalar is
8714   // an integer.
8715   // FIXME: Notionally if the scalar was a floating point value with a precise
8716   //        integral representation, we could cast it to an appropriate integer
8717   //        type and then perform the rest of the checks here. GCC will perform
8718   //        this conversion in some cases as determined by the input language.
8719   //        We should accept it on a language independent basis.
8720   if (VectorEltTy->isIntegralType(S.Context) &&
8721       ScalarTy->isIntegralType(S.Context) &&
8722       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8723 
8724     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8725       return true;
8726 
8727     ScalarCast = CK_IntegralCast;
8728   } else if (VectorEltTy->isRealFloatingType()) {
8729     if (ScalarTy->isRealFloatingType()) {
8730 
8731       // Reject cases where the scalar type is not a constant and has a higher
8732       // Order than the vector element type.
8733       llvm::APFloat Result(0.0);
8734       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8735       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8736       if (!CstScalar && Order < 0)
8737         return true;
8738 
8739       // If the scalar cannot be safely casted to the vector element type,
8740       // reject it.
8741       if (CstScalar) {
8742         bool Truncated = false;
8743         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8744                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8745         if (Truncated)
8746           return true;
8747       }
8748 
8749       ScalarCast = CK_FloatingCast;
8750     } else if (ScalarTy->isIntegralType(S.Context)) {
8751       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8752         return true;
8753 
8754       ScalarCast = CK_IntegralToFloating;
8755     } else
8756       return true;
8757   }
8758 
8759   // Adjust scalar if desired.
8760   if (Scalar) {
8761     if (ScalarCast != CK_NoOp)
8762       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8763     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8764   }
8765   return false;
8766 }
8767 
8768 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8769                                    SourceLocation Loc, bool IsCompAssign,
8770                                    bool AllowBothBool,
8771                                    bool AllowBoolConversions) {
8772   if (!IsCompAssign) {
8773     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8774     if (LHS.isInvalid())
8775       return QualType();
8776   }
8777   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8778   if (RHS.isInvalid())
8779     return QualType();
8780 
8781   // For conversion purposes, we ignore any qualifiers.
8782   // For example, "const float" and "float" are equivalent.
8783   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8784   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8785 
8786   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8787   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8788   assert(LHSVecType || RHSVecType);
8789 
8790   // AltiVec-style "vector bool op vector bool" combinations are allowed
8791   // for some operators but not others.
8792   if (!AllowBothBool &&
8793       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8794       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8795     return InvalidOperands(Loc, LHS, RHS);
8796 
8797   // If the vector types are identical, return.
8798   if (Context.hasSameType(LHSType, RHSType))
8799     return LHSType;
8800 
8801   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8802   if (LHSVecType && RHSVecType &&
8803       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8804     if (isa<ExtVectorType>(LHSVecType)) {
8805       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8806       return LHSType;
8807     }
8808 
8809     if (!IsCompAssign)
8810       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8811     return RHSType;
8812   }
8813 
8814   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8815   // can be mixed, with the result being the non-bool type.  The non-bool
8816   // operand must have integer element type.
8817   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8818       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8819       (Context.getTypeSize(LHSVecType->getElementType()) ==
8820        Context.getTypeSize(RHSVecType->getElementType()))) {
8821     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8822         LHSVecType->getElementType()->isIntegerType() &&
8823         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8824       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8825       return LHSType;
8826     }
8827     if (!IsCompAssign &&
8828         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8829         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8830         RHSVecType->getElementType()->isIntegerType()) {
8831       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8832       return RHSType;
8833     }
8834   }
8835 
8836   // If there's a vector type and a scalar, try to convert the scalar to
8837   // the vector element type and splat.
8838   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8839   if (!RHSVecType) {
8840     if (isa<ExtVectorType>(LHSVecType)) {
8841       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8842                                     LHSVecType->getElementType(), LHSType,
8843                                     DiagID))
8844         return LHSType;
8845     } else {
8846       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8847         return LHSType;
8848     }
8849   }
8850   if (!LHSVecType) {
8851     if (isa<ExtVectorType>(RHSVecType)) {
8852       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8853                                     LHSType, RHSVecType->getElementType(),
8854                                     RHSType, DiagID))
8855         return RHSType;
8856     } else {
8857       if (LHS.get()->getValueKind() == VK_LValue ||
8858           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8859         return RHSType;
8860     }
8861   }
8862 
8863   // FIXME: The code below also handles conversion between vectors and
8864   // non-scalars, we should break this down into fine grained specific checks
8865   // and emit proper diagnostics.
8866   QualType VecType = LHSVecType ? LHSType : RHSType;
8867   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8868   QualType OtherType = LHSVecType ? RHSType : LHSType;
8869   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8870   if (isLaxVectorConversion(OtherType, VecType)) {
8871     // If we're allowing lax vector conversions, only the total (data) size
8872     // needs to be the same. For non compound assignment, if one of the types is
8873     // scalar, the result is always the vector type.
8874     if (!IsCompAssign) {
8875       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8876       return VecType;
8877     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8878     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8879     // type. Note that this is already done by non-compound assignments in
8880     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8881     // <1 x T> -> T. The result is also a vector type.
8882     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8883                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8884       ExprResult *RHSExpr = &RHS;
8885       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8886       return VecType;
8887     }
8888   }
8889 
8890   // Okay, the expression is invalid.
8891 
8892   // If there's a non-vector, non-real operand, diagnose that.
8893   if ((!RHSVecType && !RHSType->isRealType()) ||
8894       (!LHSVecType && !LHSType->isRealType())) {
8895     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8896       << LHSType << RHSType
8897       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8898     return QualType();
8899   }
8900 
8901   // OpenCL V1.1 6.2.6.p1:
8902   // If the operands are of more than one vector type, then an error shall
8903   // occur. Implicit conversions between vector types are not permitted, per
8904   // section 6.2.1.
8905   if (getLangOpts().OpenCL &&
8906       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8907       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8908     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8909                                                            << RHSType;
8910     return QualType();
8911   }
8912 
8913 
8914   // If there is a vector type that is not a ExtVector and a scalar, we reach
8915   // this point if scalar could not be converted to the vector's element type
8916   // without truncation.
8917   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8918       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8919     QualType Scalar = LHSVecType ? RHSType : LHSType;
8920     QualType Vector = LHSVecType ? LHSType : RHSType;
8921     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8922     Diag(Loc,
8923          diag::err_typecheck_vector_not_convertable_implict_truncation)
8924         << ScalarOrVector << Scalar << Vector;
8925 
8926     return QualType();
8927   }
8928 
8929   // Otherwise, use the generic diagnostic.
8930   Diag(Loc, DiagID)
8931     << LHSType << RHSType
8932     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8933   return QualType();
8934 }
8935 
8936 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8937 // expression.  These are mainly cases where the null pointer is used as an
8938 // integer instead of a pointer.
8939 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8940                                 SourceLocation Loc, bool IsCompare) {
8941   // The canonical way to check for a GNU null is with isNullPointerConstant,
8942   // but we use a bit of a hack here for speed; this is a relatively
8943   // hot path, and isNullPointerConstant is slow.
8944   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8945   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8946 
8947   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8948 
8949   // Avoid analyzing cases where the result will either be invalid (and
8950   // diagnosed as such) or entirely valid and not something to warn about.
8951   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8952       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8953     return;
8954 
8955   // Comparison operations would not make sense with a null pointer no matter
8956   // what the other expression is.
8957   if (!IsCompare) {
8958     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8959         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8960         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8961     return;
8962   }
8963 
8964   // The rest of the operations only make sense with a null pointer
8965   // if the other expression is a pointer.
8966   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8967       NonNullType->canDecayToPointerType())
8968     return;
8969 
8970   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8971       << LHSNull /* LHS is NULL */ << NonNullType
8972       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8973 }
8974 
8975 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8976                                           SourceLocation Loc) {
8977   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8978   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
8979   if (!LUE || !RUE)
8980     return;
8981   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
8982       RUE->getKind() != UETT_SizeOf)
8983     return;
8984 
8985   QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
8986   QualType RHSTy;
8987 
8988   if (RUE->isArgumentType())
8989     RHSTy = RUE->getArgumentType();
8990   else
8991     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
8992 
8993   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
8994     return;
8995   if (LHSTy->getPointeeType() != RHSTy)
8996     return;
8997 
8998   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
8999 }
9000 
9001 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9002                                                ExprResult &RHS,
9003                                                SourceLocation Loc, bool IsDiv) {
9004   // Check for division/remainder by zero.
9005   Expr::EvalResult RHSValue;
9006   if (!RHS.get()->isValueDependent() &&
9007       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9008       RHSValue.Val.getInt() == 0)
9009     S.DiagRuntimeBehavior(Loc, RHS.get(),
9010                           S.PDiag(diag::warn_remainder_division_by_zero)
9011                             << IsDiv << RHS.get()->getSourceRange());
9012 }
9013 
9014 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9015                                            SourceLocation Loc,
9016                                            bool IsCompAssign, bool IsDiv) {
9017   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9018 
9019   if (LHS.get()->getType()->isVectorType() ||
9020       RHS.get()->getType()->isVectorType())
9021     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9022                                /*AllowBothBool*/getLangOpts().AltiVec,
9023                                /*AllowBoolConversions*/false);
9024 
9025   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9026   if (LHS.isInvalid() || RHS.isInvalid())
9027     return QualType();
9028 
9029 
9030   if (compType.isNull() || !compType->isArithmeticType())
9031     return InvalidOperands(Loc, LHS, RHS);
9032   if (IsDiv) {
9033     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9034     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9035   }
9036   return compType;
9037 }
9038 
9039 QualType Sema::CheckRemainderOperands(
9040   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9041   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9042 
9043   if (LHS.get()->getType()->isVectorType() ||
9044       RHS.get()->getType()->isVectorType()) {
9045     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9046         RHS.get()->getType()->hasIntegerRepresentation())
9047       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9048                                  /*AllowBothBool*/getLangOpts().AltiVec,
9049                                  /*AllowBoolConversions*/false);
9050     return InvalidOperands(Loc, LHS, RHS);
9051   }
9052 
9053   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9054   if (LHS.isInvalid() || RHS.isInvalid())
9055     return QualType();
9056 
9057   if (compType.isNull() || !compType->isIntegerType())
9058     return InvalidOperands(Loc, LHS, RHS);
9059   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9060   return compType;
9061 }
9062 
9063 /// Diagnose invalid arithmetic on two void pointers.
9064 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9065                                                 Expr *LHSExpr, Expr *RHSExpr) {
9066   S.Diag(Loc, S.getLangOpts().CPlusPlus
9067                 ? diag::err_typecheck_pointer_arith_void_type
9068                 : diag::ext_gnu_void_ptr)
9069     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9070                             << RHSExpr->getSourceRange();
9071 }
9072 
9073 /// Diagnose invalid arithmetic on a void pointer.
9074 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9075                                             Expr *Pointer) {
9076   S.Diag(Loc, S.getLangOpts().CPlusPlus
9077                 ? diag::err_typecheck_pointer_arith_void_type
9078                 : diag::ext_gnu_void_ptr)
9079     << 0 /* one pointer */ << Pointer->getSourceRange();
9080 }
9081 
9082 /// Diagnose invalid arithmetic on a null pointer.
9083 ///
9084 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9085 /// idiom, which we recognize as a GNU extension.
9086 ///
9087 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9088                                             Expr *Pointer, bool IsGNUIdiom) {
9089   if (IsGNUIdiom)
9090     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9091       << Pointer->getSourceRange();
9092   else
9093     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9094       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9095 }
9096 
9097 /// Diagnose invalid arithmetic on two function pointers.
9098 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9099                                                     Expr *LHS, Expr *RHS) {
9100   assert(LHS->getType()->isAnyPointerType());
9101   assert(RHS->getType()->isAnyPointerType());
9102   S.Diag(Loc, S.getLangOpts().CPlusPlus
9103                 ? diag::err_typecheck_pointer_arith_function_type
9104                 : diag::ext_gnu_ptr_func_arith)
9105     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9106     // We only show the second type if it differs from the first.
9107     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9108                                                    RHS->getType())
9109     << RHS->getType()->getPointeeType()
9110     << LHS->getSourceRange() << RHS->getSourceRange();
9111 }
9112 
9113 /// Diagnose invalid arithmetic on a function pointer.
9114 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9115                                                 Expr *Pointer) {
9116   assert(Pointer->getType()->isAnyPointerType());
9117   S.Diag(Loc, S.getLangOpts().CPlusPlus
9118                 ? diag::err_typecheck_pointer_arith_function_type
9119                 : diag::ext_gnu_ptr_func_arith)
9120     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9121     << 0 /* one pointer, so only one type */
9122     << Pointer->getSourceRange();
9123 }
9124 
9125 /// Emit error if Operand is incomplete pointer type
9126 ///
9127 /// \returns True if pointer has incomplete type
9128 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9129                                                  Expr *Operand) {
9130   QualType ResType = Operand->getType();
9131   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9132     ResType = ResAtomicType->getValueType();
9133 
9134   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9135   QualType PointeeTy = ResType->getPointeeType();
9136   return S.RequireCompleteType(Loc, PointeeTy,
9137                                diag::err_typecheck_arithmetic_incomplete_type,
9138                                PointeeTy, Operand->getSourceRange());
9139 }
9140 
9141 /// Check the validity of an arithmetic pointer operand.
9142 ///
9143 /// If the operand has pointer type, this code will check for pointer types
9144 /// which are invalid in arithmetic operations. These will be diagnosed
9145 /// appropriately, including whether or not the use is supported as an
9146 /// extension.
9147 ///
9148 /// \returns True when the operand is valid to use (even if as an extension).
9149 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9150                                             Expr *Operand) {
9151   QualType ResType = Operand->getType();
9152   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9153     ResType = ResAtomicType->getValueType();
9154 
9155   if (!ResType->isAnyPointerType()) return true;
9156 
9157   QualType PointeeTy = ResType->getPointeeType();
9158   if (PointeeTy->isVoidType()) {
9159     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9160     return !S.getLangOpts().CPlusPlus;
9161   }
9162   if (PointeeTy->isFunctionType()) {
9163     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9164     return !S.getLangOpts().CPlusPlus;
9165   }
9166 
9167   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9168 
9169   return true;
9170 }
9171 
9172 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9173 /// operands.
9174 ///
9175 /// This routine will diagnose any invalid arithmetic on pointer operands much
9176 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9177 /// for emitting a single diagnostic even for operations where both LHS and RHS
9178 /// are (potentially problematic) pointers.
9179 ///
9180 /// \returns True when the operand is valid to use (even if as an extension).
9181 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9182                                                 Expr *LHSExpr, Expr *RHSExpr) {
9183   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9184   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9185   if (!isLHSPointer && !isRHSPointer) return true;
9186 
9187   QualType LHSPointeeTy, RHSPointeeTy;
9188   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9189   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9190 
9191   // if both are pointers check if operation is valid wrt address spaces
9192   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9193     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9194     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9195     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9196       S.Diag(Loc,
9197              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9198           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9199           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9200       return false;
9201     }
9202   }
9203 
9204   // Check for arithmetic on pointers to incomplete types.
9205   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9206   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9207   if (isLHSVoidPtr || isRHSVoidPtr) {
9208     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9209     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9210     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9211 
9212     return !S.getLangOpts().CPlusPlus;
9213   }
9214 
9215   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9216   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9217   if (isLHSFuncPtr || isRHSFuncPtr) {
9218     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9219     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9220                                                                 RHSExpr);
9221     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9222 
9223     return !S.getLangOpts().CPlusPlus;
9224   }
9225 
9226   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9227     return false;
9228   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9229     return false;
9230 
9231   return true;
9232 }
9233 
9234 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9235 /// literal.
9236 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9237                                   Expr *LHSExpr, Expr *RHSExpr) {
9238   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9239   Expr* IndexExpr = RHSExpr;
9240   if (!StrExpr) {
9241     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9242     IndexExpr = LHSExpr;
9243   }
9244 
9245   bool IsStringPlusInt = StrExpr &&
9246       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9247   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9248     return;
9249 
9250   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9251   Self.Diag(OpLoc, diag::warn_string_plus_int)
9252       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9253 
9254   // Only print a fixit for "str" + int, not for int + "str".
9255   if (IndexExpr == RHSExpr) {
9256     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9257     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9258         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9259         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9260         << FixItHint::CreateInsertion(EndLoc, "]");
9261   } else
9262     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9263 }
9264 
9265 /// Emit a warning when adding a char literal to a string.
9266 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9267                                    Expr *LHSExpr, Expr *RHSExpr) {
9268   const Expr *StringRefExpr = LHSExpr;
9269   const CharacterLiteral *CharExpr =
9270       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9271 
9272   if (!CharExpr) {
9273     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9274     StringRefExpr = RHSExpr;
9275   }
9276 
9277   if (!CharExpr || !StringRefExpr)
9278     return;
9279 
9280   const QualType StringType = StringRefExpr->getType();
9281 
9282   // Return if not a PointerType.
9283   if (!StringType->isAnyPointerType())
9284     return;
9285 
9286   // Return if not a CharacterType.
9287   if (!StringType->getPointeeType()->isAnyCharacterType())
9288     return;
9289 
9290   ASTContext &Ctx = Self.getASTContext();
9291   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9292 
9293   const QualType CharType = CharExpr->getType();
9294   if (!CharType->isAnyCharacterType() &&
9295       CharType->isIntegerType() &&
9296       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9297     Self.Diag(OpLoc, diag::warn_string_plus_char)
9298         << DiagRange << Ctx.CharTy;
9299   } else {
9300     Self.Diag(OpLoc, diag::warn_string_plus_char)
9301         << DiagRange << CharExpr->getType();
9302   }
9303 
9304   // Only print a fixit for str + char, not for char + str.
9305   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9306     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9307     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9308         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9309         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9310         << FixItHint::CreateInsertion(EndLoc, "]");
9311   } else {
9312     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9313   }
9314 }
9315 
9316 /// Emit error when two pointers are incompatible.
9317 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9318                                            Expr *LHSExpr, Expr *RHSExpr) {
9319   assert(LHSExpr->getType()->isAnyPointerType());
9320   assert(RHSExpr->getType()->isAnyPointerType());
9321   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9322     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9323     << RHSExpr->getSourceRange();
9324 }
9325 
9326 // C99 6.5.6
9327 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9328                                      SourceLocation Loc, BinaryOperatorKind Opc,
9329                                      QualType* CompLHSTy) {
9330   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9331 
9332   if (LHS.get()->getType()->isVectorType() ||
9333       RHS.get()->getType()->isVectorType()) {
9334     QualType compType = CheckVectorOperands(
9335         LHS, RHS, Loc, CompLHSTy,
9336         /*AllowBothBool*/getLangOpts().AltiVec,
9337         /*AllowBoolConversions*/getLangOpts().ZVector);
9338     if (CompLHSTy) *CompLHSTy = compType;
9339     return compType;
9340   }
9341 
9342   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9343   if (LHS.isInvalid() || RHS.isInvalid())
9344     return QualType();
9345 
9346   // Diagnose "string literal" '+' int and string '+' "char literal".
9347   if (Opc == BO_Add) {
9348     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9349     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9350   }
9351 
9352   // handle the common case first (both operands are arithmetic).
9353   if (!compType.isNull() && compType->isArithmeticType()) {
9354     if (CompLHSTy) *CompLHSTy = compType;
9355     return compType;
9356   }
9357 
9358   // Type-checking.  Ultimately the pointer's going to be in PExp;
9359   // note that we bias towards the LHS being the pointer.
9360   Expr *PExp = LHS.get(), *IExp = RHS.get();
9361 
9362   bool isObjCPointer;
9363   if (PExp->getType()->isPointerType()) {
9364     isObjCPointer = false;
9365   } else if (PExp->getType()->isObjCObjectPointerType()) {
9366     isObjCPointer = true;
9367   } else {
9368     std::swap(PExp, IExp);
9369     if (PExp->getType()->isPointerType()) {
9370       isObjCPointer = false;
9371     } else if (PExp->getType()->isObjCObjectPointerType()) {
9372       isObjCPointer = true;
9373     } else {
9374       return InvalidOperands(Loc, LHS, RHS);
9375     }
9376   }
9377   assert(PExp->getType()->isAnyPointerType());
9378 
9379   if (!IExp->getType()->isIntegerType())
9380     return InvalidOperands(Loc, LHS, RHS);
9381 
9382   // Adding to a null pointer results in undefined behavior.
9383   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9384           Context, Expr::NPC_ValueDependentIsNotNull)) {
9385     // In C++ adding zero to a null pointer is defined.
9386     Expr::EvalResult KnownVal;
9387     if (!getLangOpts().CPlusPlus ||
9388         (!IExp->isValueDependent() &&
9389          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9390           KnownVal.Val.getInt() != 0))) {
9391       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9392       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9393           Context, BO_Add, PExp, IExp);
9394       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9395     }
9396   }
9397 
9398   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9399     return QualType();
9400 
9401   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9402     return QualType();
9403 
9404   // Check array bounds for pointer arithemtic
9405   CheckArrayAccess(PExp, IExp);
9406 
9407   if (CompLHSTy) {
9408     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9409     if (LHSTy.isNull()) {
9410       LHSTy = LHS.get()->getType();
9411       if (LHSTy->isPromotableIntegerType())
9412         LHSTy = Context.getPromotedIntegerType(LHSTy);
9413     }
9414     *CompLHSTy = LHSTy;
9415   }
9416 
9417   return PExp->getType();
9418 }
9419 
9420 // C99 6.5.6
9421 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9422                                         SourceLocation Loc,
9423                                         QualType* CompLHSTy) {
9424   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9425 
9426   if (LHS.get()->getType()->isVectorType() ||
9427       RHS.get()->getType()->isVectorType()) {
9428     QualType compType = CheckVectorOperands(
9429         LHS, RHS, Loc, CompLHSTy,
9430         /*AllowBothBool*/getLangOpts().AltiVec,
9431         /*AllowBoolConversions*/getLangOpts().ZVector);
9432     if (CompLHSTy) *CompLHSTy = compType;
9433     return compType;
9434   }
9435 
9436   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9437   if (LHS.isInvalid() || RHS.isInvalid())
9438     return QualType();
9439 
9440   // Enforce type constraints: C99 6.5.6p3.
9441 
9442   // Handle the common case first (both operands are arithmetic).
9443   if (!compType.isNull() && compType->isArithmeticType()) {
9444     if (CompLHSTy) *CompLHSTy = compType;
9445     return compType;
9446   }
9447 
9448   // Either ptr - int   or   ptr - ptr.
9449   if (LHS.get()->getType()->isAnyPointerType()) {
9450     QualType lpointee = LHS.get()->getType()->getPointeeType();
9451 
9452     // Diagnose bad cases where we step over interface counts.
9453     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9454         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9455       return QualType();
9456 
9457     // The result type of a pointer-int computation is the pointer type.
9458     if (RHS.get()->getType()->isIntegerType()) {
9459       // Subtracting from a null pointer should produce a warning.
9460       // The last argument to the diagnose call says this doesn't match the
9461       // GNU int-to-pointer idiom.
9462       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9463                                            Expr::NPC_ValueDependentIsNotNull)) {
9464         // In C++ adding zero to a null pointer is defined.
9465         Expr::EvalResult KnownVal;
9466         if (!getLangOpts().CPlusPlus ||
9467             (!RHS.get()->isValueDependent() &&
9468              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9469               KnownVal.Val.getInt() != 0))) {
9470           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9471         }
9472       }
9473 
9474       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9475         return QualType();
9476 
9477       // Check array bounds for pointer arithemtic
9478       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9479                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9480 
9481       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9482       return LHS.get()->getType();
9483     }
9484 
9485     // Handle pointer-pointer subtractions.
9486     if (const PointerType *RHSPTy
9487           = RHS.get()->getType()->getAs<PointerType>()) {
9488       QualType rpointee = RHSPTy->getPointeeType();
9489 
9490       if (getLangOpts().CPlusPlus) {
9491         // Pointee types must be the same: C++ [expr.add]
9492         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9493           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9494         }
9495       } else {
9496         // Pointee types must be compatible C99 6.5.6p3
9497         if (!Context.typesAreCompatible(
9498                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9499                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9500           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9501           return QualType();
9502         }
9503       }
9504 
9505       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9506                                                LHS.get(), RHS.get()))
9507         return QualType();
9508 
9509       // FIXME: Add warnings for nullptr - ptr.
9510 
9511       // The pointee type may have zero size.  As an extension, a structure or
9512       // union may have zero size or an array may have zero length.  In this
9513       // case subtraction does not make sense.
9514       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9515         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9516         if (ElementSize.isZero()) {
9517           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9518             << rpointee.getUnqualifiedType()
9519             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9520         }
9521       }
9522 
9523       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9524       return Context.getPointerDiffType();
9525     }
9526   }
9527 
9528   return InvalidOperands(Loc, LHS, RHS);
9529 }
9530 
9531 static bool isScopedEnumerationType(QualType T) {
9532   if (const EnumType *ET = T->getAs<EnumType>())
9533     return ET->getDecl()->isScoped();
9534   return false;
9535 }
9536 
9537 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9538                                    SourceLocation Loc, BinaryOperatorKind Opc,
9539                                    QualType LHSType) {
9540   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9541   // so skip remaining warnings as we don't want to modify values within Sema.
9542   if (S.getLangOpts().OpenCL)
9543     return;
9544 
9545   // Check right/shifter operand
9546   Expr::EvalResult RHSResult;
9547   if (RHS.get()->isValueDependent() ||
9548       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9549     return;
9550   llvm::APSInt Right = RHSResult.Val.getInt();
9551 
9552   if (Right.isNegative()) {
9553     S.DiagRuntimeBehavior(Loc, RHS.get(),
9554                           S.PDiag(diag::warn_shift_negative)
9555                             << RHS.get()->getSourceRange());
9556     return;
9557   }
9558   llvm::APInt LeftBits(Right.getBitWidth(),
9559                        S.Context.getTypeSize(LHS.get()->getType()));
9560   if (Right.uge(LeftBits)) {
9561     S.DiagRuntimeBehavior(Loc, RHS.get(),
9562                           S.PDiag(diag::warn_shift_gt_typewidth)
9563                             << RHS.get()->getSourceRange());
9564     return;
9565   }
9566   if (Opc != BO_Shl)
9567     return;
9568 
9569   // When left shifting an ICE which is signed, we can check for overflow which
9570   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9571   // integers have defined behavior modulo one more than the maximum value
9572   // representable in the result type, so never warn for those.
9573   Expr::EvalResult LHSResult;
9574   if (LHS.get()->isValueDependent() ||
9575       LHSType->hasUnsignedIntegerRepresentation() ||
9576       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9577     return;
9578   llvm::APSInt Left = LHSResult.Val.getInt();
9579 
9580   // If LHS does not have a signed type and non-negative value
9581   // then, the behavior is undefined. Warn about it.
9582   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9583     S.DiagRuntimeBehavior(Loc, LHS.get(),
9584                           S.PDiag(diag::warn_shift_lhs_negative)
9585                             << LHS.get()->getSourceRange());
9586     return;
9587   }
9588 
9589   llvm::APInt ResultBits =
9590       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9591   if (LeftBits.uge(ResultBits))
9592     return;
9593   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9594   Result = Result.shl(Right);
9595 
9596   // Print the bit representation of the signed integer as an unsigned
9597   // hexadecimal number.
9598   SmallString<40> HexResult;
9599   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9600 
9601   // If we are only missing a sign bit, this is less likely to result in actual
9602   // bugs -- if the result is cast back to an unsigned type, it will have the
9603   // expected value. Thus we place this behind a different warning that can be
9604   // turned off separately if needed.
9605   if (LeftBits == ResultBits - 1) {
9606     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9607         << HexResult << LHSType
9608         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9609     return;
9610   }
9611 
9612   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9613     << HexResult.str() << Result.getMinSignedBits() << LHSType
9614     << Left.getBitWidth() << LHS.get()->getSourceRange()
9615     << RHS.get()->getSourceRange();
9616 }
9617 
9618 /// Return the resulting type when a vector is shifted
9619 ///        by a scalar or vector shift amount.
9620 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9621                                  SourceLocation Loc, bool IsCompAssign) {
9622   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9623   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9624       !LHS.get()->getType()->isVectorType()) {
9625     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9626       << RHS.get()->getType() << LHS.get()->getType()
9627       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9628     return QualType();
9629   }
9630 
9631   if (!IsCompAssign) {
9632     LHS = S.UsualUnaryConversions(LHS.get());
9633     if (LHS.isInvalid()) return QualType();
9634   }
9635 
9636   RHS = S.UsualUnaryConversions(RHS.get());
9637   if (RHS.isInvalid()) return QualType();
9638 
9639   QualType LHSType = LHS.get()->getType();
9640   // Note that LHS might be a scalar because the routine calls not only in
9641   // OpenCL case.
9642   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9643   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9644 
9645   // Note that RHS might not be a vector.
9646   QualType RHSType = RHS.get()->getType();
9647   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9648   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9649 
9650   // The operands need to be integers.
9651   if (!LHSEleType->isIntegerType()) {
9652     S.Diag(Loc, diag::err_typecheck_expect_int)
9653       << LHS.get()->getType() << LHS.get()->getSourceRange();
9654     return QualType();
9655   }
9656 
9657   if (!RHSEleType->isIntegerType()) {
9658     S.Diag(Loc, diag::err_typecheck_expect_int)
9659       << RHS.get()->getType() << RHS.get()->getSourceRange();
9660     return QualType();
9661   }
9662 
9663   if (!LHSVecTy) {
9664     assert(RHSVecTy);
9665     if (IsCompAssign)
9666       return RHSType;
9667     if (LHSEleType != RHSEleType) {
9668       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9669       LHSEleType = RHSEleType;
9670     }
9671     QualType VecTy =
9672         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9673     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9674     LHSType = VecTy;
9675   } else if (RHSVecTy) {
9676     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9677     // are applied component-wise. So if RHS is a vector, then ensure
9678     // that the number of elements is the same as LHS...
9679     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9680       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9681         << LHS.get()->getType() << RHS.get()->getType()
9682         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9683       return QualType();
9684     }
9685     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9686       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9687       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9688       if (LHSBT != RHSBT &&
9689           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9690         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9691             << LHS.get()->getType() << RHS.get()->getType()
9692             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9693       }
9694     }
9695   } else {
9696     // ...else expand RHS to match the number of elements in LHS.
9697     QualType VecTy =
9698       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9699     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9700   }
9701 
9702   return LHSType;
9703 }
9704 
9705 // C99 6.5.7
9706 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9707                                   SourceLocation Loc, BinaryOperatorKind Opc,
9708                                   bool IsCompAssign) {
9709   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9710 
9711   // Vector shifts promote their scalar inputs to vector type.
9712   if (LHS.get()->getType()->isVectorType() ||
9713       RHS.get()->getType()->isVectorType()) {
9714     if (LangOpts.ZVector) {
9715       // The shift operators for the z vector extensions work basically
9716       // like general shifts, except that neither the LHS nor the RHS is
9717       // allowed to be a "vector bool".
9718       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9719         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9720           return InvalidOperands(Loc, LHS, RHS);
9721       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9722         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9723           return InvalidOperands(Loc, LHS, RHS);
9724     }
9725     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9726   }
9727 
9728   // Shifts don't perform usual arithmetic conversions, they just do integer
9729   // promotions on each operand. C99 6.5.7p3
9730 
9731   // For the LHS, do usual unary conversions, but then reset them away
9732   // if this is a compound assignment.
9733   ExprResult OldLHS = LHS;
9734   LHS = UsualUnaryConversions(LHS.get());
9735   if (LHS.isInvalid())
9736     return QualType();
9737   QualType LHSType = LHS.get()->getType();
9738   if (IsCompAssign) LHS = OldLHS;
9739 
9740   // The RHS is simpler.
9741   RHS = UsualUnaryConversions(RHS.get());
9742   if (RHS.isInvalid())
9743     return QualType();
9744   QualType RHSType = RHS.get()->getType();
9745 
9746   // C99 6.5.7p2: Each of the operands shall have integer type.
9747   if (!LHSType->hasIntegerRepresentation() ||
9748       !RHSType->hasIntegerRepresentation())
9749     return InvalidOperands(Loc, LHS, RHS);
9750 
9751   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9752   // hasIntegerRepresentation() above instead of this.
9753   if (isScopedEnumerationType(LHSType) ||
9754       isScopedEnumerationType(RHSType)) {
9755     return InvalidOperands(Loc, LHS, RHS);
9756   }
9757   // Sanity-check shift operands
9758   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9759 
9760   // "The type of the result is that of the promoted left operand."
9761   return LHSType;
9762 }
9763 
9764 /// If two different enums are compared, raise a warning.
9765 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9766                                 Expr *RHS) {
9767   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9768   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9769 
9770   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9771   if (!LHSEnumType)
9772     return;
9773   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9774   if (!RHSEnumType)
9775     return;
9776 
9777   // Ignore anonymous enums.
9778   if (!LHSEnumType->getDecl()->getIdentifier() &&
9779       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9780     return;
9781   if (!RHSEnumType->getDecl()->getIdentifier() &&
9782       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9783     return;
9784 
9785   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9786     return;
9787 
9788   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9789       << LHSStrippedType << RHSStrippedType
9790       << LHS->getSourceRange() << RHS->getSourceRange();
9791 }
9792 
9793 /// Diagnose bad pointer comparisons.
9794 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9795                                               ExprResult &LHS, ExprResult &RHS,
9796                                               bool IsError) {
9797   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9798                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9799     << LHS.get()->getType() << RHS.get()->getType()
9800     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9801 }
9802 
9803 /// Returns false if the pointers are converted to a composite type,
9804 /// true otherwise.
9805 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9806                                            ExprResult &LHS, ExprResult &RHS) {
9807   // C++ [expr.rel]p2:
9808   //   [...] Pointer conversions (4.10) and qualification
9809   //   conversions (4.4) are performed on pointer operands (or on
9810   //   a pointer operand and a null pointer constant) to bring
9811   //   them to their composite pointer type. [...]
9812   //
9813   // C++ [expr.eq]p1 uses the same notion for (in)equality
9814   // comparisons of pointers.
9815 
9816   QualType LHSType = LHS.get()->getType();
9817   QualType RHSType = RHS.get()->getType();
9818   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9819          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9820 
9821   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9822   if (T.isNull()) {
9823     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9824         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9825       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9826     else
9827       S.InvalidOperands(Loc, LHS, RHS);
9828     return true;
9829   }
9830 
9831   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9832   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9833   return false;
9834 }
9835 
9836 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9837                                                     ExprResult &LHS,
9838                                                     ExprResult &RHS,
9839                                                     bool IsError) {
9840   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9841                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9842     << LHS.get()->getType() << RHS.get()->getType()
9843     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9844 }
9845 
9846 static bool isObjCObjectLiteral(ExprResult &E) {
9847   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9848   case Stmt::ObjCArrayLiteralClass:
9849   case Stmt::ObjCDictionaryLiteralClass:
9850   case Stmt::ObjCStringLiteralClass:
9851   case Stmt::ObjCBoxedExprClass:
9852     return true;
9853   default:
9854     // Note that ObjCBoolLiteral is NOT an object literal!
9855     return false;
9856   }
9857 }
9858 
9859 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9860   const ObjCObjectPointerType *Type =
9861     LHS->getType()->getAs<ObjCObjectPointerType>();
9862 
9863   // If this is not actually an Objective-C object, bail out.
9864   if (!Type)
9865     return false;
9866 
9867   // Get the LHS object's interface type.
9868   QualType InterfaceType = Type->getPointeeType();
9869 
9870   // If the RHS isn't an Objective-C object, bail out.
9871   if (!RHS->getType()->isObjCObjectPointerType())
9872     return false;
9873 
9874   // Try to find the -isEqual: method.
9875   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9876   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9877                                                       InterfaceType,
9878                                                       /*instance=*/true);
9879   if (!Method) {
9880     if (Type->isObjCIdType()) {
9881       // For 'id', just check the global pool.
9882       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9883                                                   /*receiverId=*/true);
9884     } else {
9885       // Check protocols.
9886       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9887                                              /*instance=*/true);
9888     }
9889   }
9890 
9891   if (!Method)
9892     return false;
9893 
9894   QualType T = Method->parameters()[0]->getType();
9895   if (!T->isObjCObjectPointerType())
9896     return false;
9897 
9898   QualType R = Method->getReturnType();
9899   if (!R->isScalarType())
9900     return false;
9901 
9902   return true;
9903 }
9904 
9905 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9906   FromE = FromE->IgnoreParenImpCasts();
9907   switch (FromE->getStmtClass()) {
9908     default:
9909       break;
9910     case Stmt::ObjCStringLiteralClass:
9911       // "string literal"
9912       return LK_String;
9913     case Stmt::ObjCArrayLiteralClass:
9914       // "array literal"
9915       return LK_Array;
9916     case Stmt::ObjCDictionaryLiteralClass:
9917       // "dictionary literal"
9918       return LK_Dictionary;
9919     case Stmt::BlockExprClass:
9920       return LK_Block;
9921     case Stmt::ObjCBoxedExprClass: {
9922       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9923       switch (Inner->getStmtClass()) {
9924         case Stmt::IntegerLiteralClass:
9925         case Stmt::FloatingLiteralClass:
9926         case Stmt::CharacterLiteralClass:
9927         case Stmt::ObjCBoolLiteralExprClass:
9928         case Stmt::CXXBoolLiteralExprClass:
9929           // "numeric literal"
9930           return LK_Numeric;
9931         case Stmt::ImplicitCastExprClass: {
9932           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9933           // Boolean literals can be represented by implicit casts.
9934           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9935             return LK_Numeric;
9936           break;
9937         }
9938         default:
9939           break;
9940       }
9941       return LK_Boxed;
9942     }
9943   }
9944   return LK_None;
9945 }
9946 
9947 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9948                                           ExprResult &LHS, ExprResult &RHS,
9949                                           BinaryOperator::Opcode Opc){
9950   Expr *Literal;
9951   Expr *Other;
9952   if (isObjCObjectLiteral(LHS)) {
9953     Literal = LHS.get();
9954     Other = RHS.get();
9955   } else {
9956     Literal = RHS.get();
9957     Other = LHS.get();
9958   }
9959 
9960   // Don't warn on comparisons against nil.
9961   Other = Other->IgnoreParenCasts();
9962   if (Other->isNullPointerConstant(S.getASTContext(),
9963                                    Expr::NPC_ValueDependentIsNotNull))
9964     return;
9965 
9966   // This should be kept in sync with warn_objc_literal_comparison.
9967   // LK_String should always be after the other literals, since it has its own
9968   // warning flag.
9969   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9970   assert(LiteralKind != Sema::LK_Block);
9971   if (LiteralKind == Sema::LK_None) {
9972     llvm_unreachable("Unknown Objective-C object literal kind");
9973   }
9974 
9975   if (LiteralKind == Sema::LK_String)
9976     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9977       << Literal->getSourceRange();
9978   else
9979     S.Diag(Loc, diag::warn_objc_literal_comparison)
9980       << LiteralKind << Literal->getSourceRange();
9981 
9982   if (BinaryOperator::isEqualityOp(Opc) &&
9983       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9984     SourceLocation Start = LHS.get()->getBeginLoc();
9985     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
9986     CharSourceRange OpRange =
9987       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9988 
9989     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9990       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9991       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9992       << FixItHint::CreateInsertion(End, "]");
9993   }
9994 }
9995 
9996 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9997 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9998                                            ExprResult &RHS, SourceLocation Loc,
9999                                            BinaryOperatorKind Opc) {
10000   // Check that left hand side is !something.
10001   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10002   if (!UO || UO->getOpcode() != UO_LNot) return;
10003 
10004   // Only check if the right hand side is non-bool arithmetic type.
10005   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10006 
10007   // Make sure that the something in !something is not bool.
10008   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10009   if (SubExpr->isKnownToHaveBooleanValue()) return;
10010 
10011   // Emit warning.
10012   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10013   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10014       << Loc << IsBitwiseOp;
10015 
10016   // First note suggest !(x < y)
10017   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10018   SourceLocation FirstClose = RHS.get()->getEndLoc();
10019   FirstClose = S.getLocForEndOfToken(FirstClose);
10020   if (FirstClose.isInvalid())
10021     FirstOpen = SourceLocation();
10022   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10023       << IsBitwiseOp
10024       << FixItHint::CreateInsertion(FirstOpen, "(")
10025       << FixItHint::CreateInsertion(FirstClose, ")");
10026 
10027   // Second note suggests (!x) < y
10028   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10029   SourceLocation SecondClose = LHS.get()->getEndLoc();
10030   SecondClose = S.getLocForEndOfToken(SecondClose);
10031   if (SecondClose.isInvalid())
10032     SecondOpen = SourceLocation();
10033   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10034       << FixItHint::CreateInsertion(SecondOpen, "(")
10035       << FixItHint::CreateInsertion(SecondClose, ")");
10036 }
10037 
10038 // Get the decl for a simple expression: a reference to a variable,
10039 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10040 static ValueDecl *getCompareDecl(Expr *E) {
10041   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10042     return DR->getDecl();
10043   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10044     if (Ivar->isFreeIvar())
10045       return Ivar->getDecl();
10046   }
10047   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10048     if (Mem->isImplicitAccess())
10049       return Mem->getMemberDecl();
10050   }
10051   return nullptr;
10052 }
10053 
10054 /// Diagnose some forms of syntactically-obvious tautological comparison.
10055 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10056                                            Expr *LHS, Expr *RHS,
10057                                            BinaryOperatorKind Opc) {
10058   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10059   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10060 
10061   QualType LHSType = LHS->getType();
10062   QualType RHSType = RHS->getType();
10063   if (LHSType->hasFloatingRepresentation() ||
10064       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10065       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10066       S.inTemplateInstantiation())
10067     return;
10068 
10069   // Comparisons between two array types are ill-formed for operator<=>, so
10070   // we shouldn't emit any additional warnings about it.
10071   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10072     return;
10073 
10074   // For non-floating point types, check for self-comparisons of the form
10075   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10076   // often indicate logic errors in the program.
10077   //
10078   // NOTE: Don't warn about comparison expressions resulting from macro
10079   // expansion. Also don't warn about comparisons which are only self
10080   // comparisons within a template instantiation. The warnings should catch
10081   // obvious cases in the definition of the template anyways. The idea is to
10082   // warn when the typed comparison operator will always evaluate to the same
10083   // result.
10084   ValueDecl *DL = getCompareDecl(LHSStripped);
10085   ValueDecl *DR = getCompareDecl(RHSStripped);
10086   if (DL && DR && declaresSameEntity(DL, DR)) {
10087     StringRef Result;
10088     switch (Opc) {
10089     case BO_EQ: case BO_LE: case BO_GE:
10090       Result = "true";
10091       break;
10092     case BO_NE: case BO_LT: case BO_GT:
10093       Result = "false";
10094       break;
10095     case BO_Cmp:
10096       Result = "'std::strong_ordering::equal'";
10097       break;
10098     default:
10099       break;
10100     }
10101     S.DiagRuntimeBehavior(Loc, nullptr,
10102                           S.PDiag(diag::warn_comparison_always)
10103                               << 0 /*self-comparison*/ << !Result.empty()
10104                               << Result);
10105   } else if (DL && DR &&
10106              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10107              !DL->isWeak() && !DR->isWeak()) {
10108     // What is it always going to evaluate to?
10109     StringRef Result;
10110     switch(Opc) {
10111     case BO_EQ: // e.g. array1 == array2
10112       Result = "false";
10113       break;
10114     case BO_NE: // e.g. array1 != array2
10115       Result = "true";
10116       break;
10117     default: // e.g. array1 <= array2
10118       // The best we can say is 'a constant'
10119       break;
10120     }
10121     S.DiagRuntimeBehavior(Loc, nullptr,
10122                           S.PDiag(diag::warn_comparison_always)
10123                               << 1 /*array comparison*/
10124                               << !Result.empty() << Result);
10125   }
10126 
10127   if (isa<CastExpr>(LHSStripped))
10128     LHSStripped = LHSStripped->IgnoreParenCasts();
10129   if (isa<CastExpr>(RHSStripped))
10130     RHSStripped = RHSStripped->IgnoreParenCasts();
10131 
10132   // Warn about comparisons against a string constant (unless the other
10133   // operand is null); the user probably wants strcmp.
10134   Expr *LiteralString = nullptr;
10135   Expr *LiteralStringStripped = nullptr;
10136   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10137       !RHSStripped->isNullPointerConstant(S.Context,
10138                                           Expr::NPC_ValueDependentIsNull)) {
10139     LiteralString = LHS;
10140     LiteralStringStripped = LHSStripped;
10141   } else if ((isa<StringLiteral>(RHSStripped) ||
10142               isa<ObjCEncodeExpr>(RHSStripped)) &&
10143              !LHSStripped->isNullPointerConstant(S.Context,
10144                                           Expr::NPC_ValueDependentIsNull)) {
10145     LiteralString = RHS;
10146     LiteralStringStripped = RHSStripped;
10147   }
10148 
10149   if (LiteralString) {
10150     S.DiagRuntimeBehavior(Loc, nullptr,
10151                           S.PDiag(diag::warn_stringcompare)
10152                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10153                               << LiteralString->getSourceRange());
10154   }
10155 }
10156 
10157 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10158   switch (CK) {
10159   default: {
10160 #ifndef NDEBUG
10161     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10162                  << "\n";
10163 #endif
10164     llvm_unreachable("unhandled cast kind");
10165   }
10166   case CK_UserDefinedConversion:
10167     return ICK_Identity;
10168   case CK_LValueToRValue:
10169     return ICK_Lvalue_To_Rvalue;
10170   case CK_ArrayToPointerDecay:
10171     return ICK_Array_To_Pointer;
10172   case CK_FunctionToPointerDecay:
10173     return ICK_Function_To_Pointer;
10174   case CK_IntegralCast:
10175     return ICK_Integral_Conversion;
10176   case CK_FloatingCast:
10177     return ICK_Floating_Conversion;
10178   case CK_IntegralToFloating:
10179   case CK_FloatingToIntegral:
10180     return ICK_Floating_Integral;
10181   case CK_IntegralComplexCast:
10182   case CK_FloatingComplexCast:
10183   case CK_FloatingComplexToIntegralComplex:
10184   case CK_IntegralComplexToFloatingComplex:
10185     return ICK_Complex_Conversion;
10186   case CK_FloatingComplexToReal:
10187   case CK_FloatingRealToComplex:
10188   case CK_IntegralComplexToReal:
10189   case CK_IntegralRealToComplex:
10190     return ICK_Complex_Real;
10191   }
10192 }
10193 
10194 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10195                                              QualType FromType,
10196                                              SourceLocation Loc) {
10197   // Check for a narrowing implicit conversion.
10198   StandardConversionSequence SCS;
10199   SCS.setAsIdentityConversion();
10200   SCS.setToType(0, FromType);
10201   SCS.setToType(1, ToType);
10202   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10203     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10204 
10205   APValue PreNarrowingValue;
10206   QualType PreNarrowingType;
10207   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10208                                PreNarrowingType,
10209                                /*IgnoreFloatToIntegralConversion*/ true)) {
10210   case NK_Dependent_Narrowing:
10211     // Implicit conversion to a narrower type, but the expression is
10212     // value-dependent so we can't tell whether it's actually narrowing.
10213   case NK_Not_Narrowing:
10214     return false;
10215 
10216   case NK_Constant_Narrowing:
10217     // Implicit conversion to a narrower type, and the value is not a constant
10218     // expression.
10219     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10220         << /*Constant*/ 1
10221         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10222     return true;
10223 
10224   case NK_Variable_Narrowing:
10225     // Implicit conversion to a narrower type, and the value is not a constant
10226     // expression.
10227   case NK_Type_Narrowing:
10228     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10229         << /*Constant*/ 0 << FromType << ToType;
10230     // TODO: It's not a constant expression, but what if the user intended it
10231     // to be? Can we produce notes to help them figure out why it isn't?
10232     return true;
10233   }
10234   llvm_unreachable("unhandled case in switch");
10235 }
10236 
10237 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10238                                                          ExprResult &LHS,
10239                                                          ExprResult &RHS,
10240                                                          SourceLocation Loc) {
10241   using CCT = ComparisonCategoryType;
10242 
10243   QualType LHSType = LHS.get()->getType();
10244   QualType RHSType = RHS.get()->getType();
10245   // Dig out the original argument type and expression before implicit casts
10246   // were applied. These are the types/expressions we need to check the
10247   // [expr.spaceship] requirements against.
10248   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10249   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10250   QualType LHSStrippedType = LHSStripped.get()->getType();
10251   QualType RHSStrippedType = RHSStripped.get()->getType();
10252 
10253   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10254   // other is not, the program is ill-formed.
10255   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10256     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10257     return QualType();
10258   }
10259 
10260   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10261                     RHSStrippedType->isEnumeralType();
10262   if (NumEnumArgs == 1) {
10263     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10264     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10265     if (OtherTy->hasFloatingRepresentation()) {
10266       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10267       return QualType();
10268     }
10269   }
10270   if (NumEnumArgs == 2) {
10271     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10272     // type E, the operator yields the result of converting the operands
10273     // to the underlying type of E and applying <=> to the converted operands.
10274     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10275       S.InvalidOperands(Loc, LHS, RHS);
10276       return QualType();
10277     }
10278     QualType IntType =
10279         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10280     assert(IntType->isArithmeticType());
10281 
10282     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10283     // promote the boolean type, and all other promotable integer types, to
10284     // avoid this.
10285     if (IntType->isPromotableIntegerType())
10286       IntType = S.Context.getPromotedIntegerType(IntType);
10287 
10288     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10289     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10290     LHSType = RHSType = IntType;
10291   }
10292 
10293   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10294   // usual arithmetic conversions are applied to the operands.
10295   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10296   if (LHS.isInvalid() || RHS.isInvalid())
10297     return QualType();
10298   if (Type.isNull())
10299     return S.InvalidOperands(Loc, LHS, RHS);
10300   assert(Type->isArithmeticType() || Type->isEnumeralType());
10301 
10302   bool HasNarrowing = checkThreeWayNarrowingConversion(
10303       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10304   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10305                                                    RHS.get()->getBeginLoc());
10306   if (HasNarrowing)
10307     return QualType();
10308 
10309   assert(!Type.isNull() && "composite type for <=> has not been set");
10310 
10311   auto TypeKind = [&]() {
10312     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10313       if (CT->getElementType()->hasFloatingRepresentation())
10314         return CCT::WeakEquality;
10315       return CCT::StrongEquality;
10316     }
10317     if (Type->isIntegralOrEnumerationType())
10318       return CCT::StrongOrdering;
10319     if (Type->hasFloatingRepresentation())
10320       return CCT::PartialOrdering;
10321     llvm_unreachable("other types are unimplemented");
10322   }();
10323 
10324   return S.CheckComparisonCategoryType(TypeKind, Loc);
10325 }
10326 
10327 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10328                                                  ExprResult &RHS,
10329                                                  SourceLocation Loc,
10330                                                  BinaryOperatorKind Opc) {
10331   if (Opc == BO_Cmp)
10332     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10333 
10334   // C99 6.5.8p3 / C99 6.5.9p4
10335   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10336   if (LHS.isInvalid() || RHS.isInvalid())
10337     return QualType();
10338   if (Type.isNull())
10339     return S.InvalidOperands(Loc, LHS, RHS);
10340   assert(Type->isArithmeticType() || Type->isEnumeralType());
10341 
10342   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10343 
10344   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10345     return S.InvalidOperands(Loc, LHS, RHS);
10346 
10347   // Check for comparisons of floating point operands using != and ==.
10348   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10349     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10350 
10351   // The result of comparisons is 'bool' in C++, 'int' in C.
10352   return S.Context.getLogicalOperationType();
10353 }
10354 
10355 // C99 6.5.8, C++ [expr.rel]
10356 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10357                                     SourceLocation Loc,
10358                                     BinaryOperatorKind Opc) {
10359   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10360   bool IsThreeWay = Opc == BO_Cmp;
10361   auto IsAnyPointerType = [](ExprResult E) {
10362     QualType Ty = E.get()->getType();
10363     return Ty->isPointerType() || Ty->isMemberPointerType();
10364   };
10365 
10366   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10367   // type, array-to-pointer, ..., conversions are performed on both operands to
10368   // bring them to their composite type.
10369   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10370   // any type-related checks.
10371   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10372     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10373     if (LHS.isInvalid())
10374       return QualType();
10375     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10376     if (RHS.isInvalid())
10377       return QualType();
10378   } else {
10379     LHS = DefaultLvalueConversion(LHS.get());
10380     if (LHS.isInvalid())
10381       return QualType();
10382     RHS = DefaultLvalueConversion(RHS.get());
10383     if (RHS.isInvalid())
10384       return QualType();
10385   }
10386 
10387   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10388 
10389   // Handle vector comparisons separately.
10390   if (LHS.get()->getType()->isVectorType() ||
10391       RHS.get()->getType()->isVectorType())
10392     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10393 
10394   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10395   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10396 
10397   QualType LHSType = LHS.get()->getType();
10398   QualType RHSType = RHS.get()->getType();
10399   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10400       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10401     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10402 
10403   const Expr::NullPointerConstantKind LHSNullKind =
10404       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10405   const Expr::NullPointerConstantKind RHSNullKind =
10406       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10407   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10408   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10409 
10410   auto computeResultTy = [&]() {
10411     if (Opc != BO_Cmp)
10412       return Context.getLogicalOperationType();
10413     assert(getLangOpts().CPlusPlus);
10414     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10415 
10416     QualType CompositeTy = LHS.get()->getType();
10417     assert(!CompositeTy->isReferenceType());
10418 
10419     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10420       return CheckComparisonCategoryType(Kind, Loc);
10421     };
10422 
10423     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10424     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10425     // result is of type std::strong_equality
10426     if (CompositeTy->isFunctionPointerType() ||
10427         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10428       // FIXME: consider making the function pointer case produce
10429       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10430       // and direction polls
10431       return buildResultTy(ComparisonCategoryType::StrongEquality);
10432 
10433     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10434     // pointer type, p <=> q is of type std::strong_ordering.
10435     if (CompositeTy->isPointerType()) {
10436       // P0946R0: Comparisons between a null pointer constant and an object
10437       // pointer result in std::strong_equality
10438       if (LHSIsNull != RHSIsNull)
10439         return buildResultTy(ComparisonCategoryType::StrongEquality);
10440       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10441     }
10442     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10443     // TODO: Extend support for operator<=> to ObjC types.
10444     return InvalidOperands(Loc, LHS, RHS);
10445   };
10446 
10447 
10448   if (!IsRelational && LHSIsNull != RHSIsNull) {
10449     bool IsEquality = Opc == BO_EQ;
10450     if (RHSIsNull)
10451       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10452                                    RHS.get()->getSourceRange());
10453     else
10454       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10455                                    LHS.get()->getSourceRange());
10456   }
10457 
10458   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10459       (RHSType->isIntegerType() && !RHSIsNull)) {
10460     // Skip normal pointer conversion checks in this case; we have better
10461     // diagnostics for this below.
10462   } else if (getLangOpts().CPlusPlus) {
10463     // Equality comparison of a function pointer to a void pointer is invalid,
10464     // but we allow it as an extension.
10465     // FIXME: If we really want to allow this, should it be part of composite
10466     // pointer type computation so it works in conditionals too?
10467     if (!IsRelational &&
10468         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10469          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10470       // This is a gcc extension compatibility comparison.
10471       // In a SFINAE context, we treat this as a hard error to maintain
10472       // conformance with the C++ standard.
10473       diagnoseFunctionPointerToVoidComparison(
10474           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10475 
10476       if (isSFINAEContext())
10477         return QualType();
10478 
10479       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10480       return computeResultTy();
10481     }
10482 
10483     // C++ [expr.eq]p2:
10484     //   If at least one operand is a pointer [...] bring them to their
10485     //   composite pointer type.
10486     // C++ [expr.spaceship]p6
10487     //  If at least one of the operands is of pointer type, [...] bring them
10488     //  to their composite pointer type.
10489     // C++ [expr.rel]p2:
10490     //   If both operands are pointers, [...] bring them to their composite
10491     //   pointer type.
10492     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10493             (IsRelational ? 2 : 1) &&
10494         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10495                                          RHSType->isObjCObjectPointerType()))) {
10496       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10497         return QualType();
10498       return computeResultTy();
10499     }
10500   } else if (LHSType->isPointerType() &&
10501              RHSType->isPointerType()) { // C99 6.5.8p2
10502     // All of the following pointer-related warnings are GCC extensions, except
10503     // when handling null pointer constants.
10504     QualType LCanPointeeTy =
10505       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10506     QualType RCanPointeeTy =
10507       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10508 
10509     // C99 6.5.9p2 and C99 6.5.8p2
10510     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10511                                    RCanPointeeTy.getUnqualifiedType())) {
10512       // Valid unless a relational comparison of function pointers
10513       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10514         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10515           << LHSType << RHSType << LHS.get()->getSourceRange()
10516           << RHS.get()->getSourceRange();
10517       }
10518     } else if (!IsRelational &&
10519                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10520       // Valid unless comparison between non-null pointer and function pointer
10521       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10522           && !LHSIsNull && !RHSIsNull)
10523         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10524                                                 /*isError*/false);
10525     } else {
10526       // Invalid
10527       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10528     }
10529     if (LCanPointeeTy != RCanPointeeTy) {
10530       // Treat NULL constant as a special case in OpenCL.
10531       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10532         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10533         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10534           Diag(Loc,
10535                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10536               << LHSType << RHSType << 0 /* comparison */
10537               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10538         }
10539       }
10540       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10541       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10542       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10543                                                : CK_BitCast;
10544       if (LHSIsNull && !RHSIsNull)
10545         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10546       else
10547         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10548     }
10549     return computeResultTy();
10550   }
10551 
10552   if (getLangOpts().CPlusPlus) {
10553     // C++ [expr.eq]p4:
10554     //   Two operands of type std::nullptr_t or one operand of type
10555     //   std::nullptr_t and the other a null pointer constant compare equal.
10556     if (!IsRelational && LHSIsNull && RHSIsNull) {
10557       if (LHSType->isNullPtrType()) {
10558         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10559         return computeResultTy();
10560       }
10561       if (RHSType->isNullPtrType()) {
10562         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10563         return computeResultTy();
10564       }
10565     }
10566 
10567     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10568     // These aren't covered by the composite pointer type rules.
10569     if (!IsRelational && RHSType->isNullPtrType() &&
10570         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10571       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10572       return computeResultTy();
10573     }
10574     if (!IsRelational && LHSType->isNullPtrType() &&
10575         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10576       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10577       return computeResultTy();
10578     }
10579 
10580     if (IsRelational &&
10581         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10582          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10583       // HACK: Relational comparison of nullptr_t against a pointer type is
10584       // invalid per DR583, but we allow it within std::less<> and friends,
10585       // since otherwise common uses of it break.
10586       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10587       // friends to have std::nullptr_t overload candidates.
10588       DeclContext *DC = CurContext;
10589       if (isa<FunctionDecl>(DC))
10590         DC = DC->getParent();
10591       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10592         if (CTSD->isInStdNamespace() &&
10593             llvm::StringSwitch<bool>(CTSD->getName())
10594                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10595                 .Default(false)) {
10596           if (RHSType->isNullPtrType())
10597             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10598           else
10599             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10600           return computeResultTy();
10601         }
10602       }
10603     }
10604 
10605     // C++ [expr.eq]p2:
10606     //   If at least one operand is a pointer to member, [...] bring them to
10607     //   their composite pointer type.
10608     if (!IsRelational &&
10609         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10610       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10611         return QualType();
10612       else
10613         return computeResultTy();
10614     }
10615   }
10616 
10617   // Handle block pointer types.
10618   if (!IsRelational && LHSType->isBlockPointerType() &&
10619       RHSType->isBlockPointerType()) {
10620     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10621     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10622 
10623     if (!LHSIsNull && !RHSIsNull &&
10624         !Context.typesAreCompatible(lpointee, rpointee)) {
10625       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10626         << LHSType << RHSType << LHS.get()->getSourceRange()
10627         << RHS.get()->getSourceRange();
10628     }
10629     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10630     return computeResultTy();
10631   }
10632 
10633   // Allow block pointers to be compared with null pointer constants.
10634   if (!IsRelational
10635       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10636           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10637     if (!LHSIsNull && !RHSIsNull) {
10638       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10639              ->getPointeeType()->isVoidType())
10640             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10641                 ->getPointeeType()->isVoidType())))
10642         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10643           << LHSType << RHSType << LHS.get()->getSourceRange()
10644           << RHS.get()->getSourceRange();
10645     }
10646     if (LHSIsNull && !RHSIsNull)
10647       LHS = ImpCastExprToType(LHS.get(), RHSType,
10648                               RHSType->isPointerType() ? CK_BitCast
10649                                 : CK_AnyPointerToBlockPointerCast);
10650     else
10651       RHS = ImpCastExprToType(RHS.get(), LHSType,
10652                               LHSType->isPointerType() ? CK_BitCast
10653                                 : CK_AnyPointerToBlockPointerCast);
10654     return computeResultTy();
10655   }
10656 
10657   if (LHSType->isObjCObjectPointerType() ||
10658       RHSType->isObjCObjectPointerType()) {
10659     const PointerType *LPT = LHSType->getAs<PointerType>();
10660     const PointerType *RPT = RHSType->getAs<PointerType>();
10661     if (LPT || RPT) {
10662       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10663       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10664 
10665       if (!LPtrToVoid && !RPtrToVoid &&
10666           !Context.typesAreCompatible(LHSType, RHSType)) {
10667         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10668                                           /*isError*/false);
10669       }
10670       if (LHSIsNull && !RHSIsNull) {
10671         Expr *E = LHS.get();
10672         if (getLangOpts().ObjCAutoRefCount)
10673           CheckObjCConversion(SourceRange(), RHSType, E,
10674                               CCK_ImplicitConversion);
10675         LHS = ImpCastExprToType(E, RHSType,
10676                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10677       }
10678       else {
10679         Expr *E = RHS.get();
10680         if (getLangOpts().ObjCAutoRefCount)
10681           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10682                               /*Diagnose=*/true,
10683                               /*DiagnoseCFAudited=*/false, Opc);
10684         RHS = ImpCastExprToType(E, LHSType,
10685                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10686       }
10687       return computeResultTy();
10688     }
10689     if (LHSType->isObjCObjectPointerType() &&
10690         RHSType->isObjCObjectPointerType()) {
10691       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10692         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10693                                           /*isError*/false);
10694       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10695         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10696 
10697       if (LHSIsNull && !RHSIsNull)
10698         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10699       else
10700         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10701       return computeResultTy();
10702     }
10703 
10704     if (!IsRelational && LHSType->isBlockPointerType() &&
10705         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10706       LHS = ImpCastExprToType(LHS.get(), RHSType,
10707                               CK_BlockPointerToObjCPointerCast);
10708       return computeResultTy();
10709     } else if (!IsRelational &&
10710                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10711                RHSType->isBlockPointerType()) {
10712       RHS = ImpCastExprToType(RHS.get(), LHSType,
10713                               CK_BlockPointerToObjCPointerCast);
10714       return computeResultTy();
10715     }
10716   }
10717   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10718       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10719     unsigned DiagID = 0;
10720     bool isError = false;
10721     if (LangOpts.DebuggerSupport) {
10722       // Under a debugger, allow the comparison of pointers to integers,
10723       // since users tend to want to compare addresses.
10724     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10725                (RHSIsNull && RHSType->isIntegerType())) {
10726       if (IsRelational) {
10727         isError = getLangOpts().CPlusPlus;
10728         DiagID =
10729           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10730                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10731       }
10732     } else if (getLangOpts().CPlusPlus) {
10733       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10734       isError = true;
10735     } else if (IsRelational)
10736       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10737     else
10738       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10739 
10740     if (DiagID) {
10741       Diag(Loc, DiagID)
10742         << LHSType << RHSType << LHS.get()->getSourceRange()
10743         << RHS.get()->getSourceRange();
10744       if (isError)
10745         return QualType();
10746     }
10747 
10748     if (LHSType->isIntegerType())
10749       LHS = ImpCastExprToType(LHS.get(), RHSType,
10750                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10751     else
10752       RHS = ImpCastExprToType(RHS.get(), LHSType,
10753                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10754     return computeResultTy();
10755   }
10756 
10757   // Handle block pointers.
10758   if (!IsRelational && RHSIsNull
10759       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10760     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10761     return computeResultTy();
10762   }
10763   if (!IsRelational && LHSIsNull
10764       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10765     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10766     return computeResultTy();
10767   }
10768 
10769   if (getLangOpts().OpenCLVersion >= 200) {
10770     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10771       return computeResultTy();
10772     }
10773 
10774     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10775       return computeResultTy();
10776     }
10777 
10778     if (LHSIsNull && RHSType->isQueueT()) {
10779       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10780       return computeResultTy();
10781     }
10782 
10783     if (LHSType->isQueueT() && RHSIsNull) {
10784       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10785       return computeResultTy();
10786     }
10787   }
10788 
10789   return InvalidOperands(Loc, LHS, RHS);
10790 }
10791 
10792 // Return a signed ext_vector_type that is of identical size and number of
10793 // elements. For floating point vectors, return an integer type of identical
10794 // size and number of elements. In the non ext_vector_type case, search from
10795 // the largest type to the smallest type to avoid cases where long long == long,
10796 // where long gets picked over long long.
10797 QualType Sema::GetSignedVectorType(QualType V) {
10798   const VectorType *VTy = V->getAs<VectorType>();
10799   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10800 
10801   if (isa<ExtVectorType>(VTy)) {
10802     if (TypeSize == Context.getTypeSize(Context.CharTy))
10803       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10804     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10805       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10806     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10807       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10808     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10809       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10810     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10811            "Unhandled vector element size in vector compare");
10812     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10813   }
10814 
10815   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10816     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10817                                  VectorType::GenericVector);
10818   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10819     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10820                                  VectorType::GenericVector);
10821   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10822     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10823                                  VectorType::GenericVector);
10824   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10825     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10826                                  VectorType::GenericVector);
10827   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10828          "Unhandled vector element size in vector compare");
10829   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10830                                VectorType::GenericVector);
10831 }
10832 
10833 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10834 /// operates on extended vector types.  Instead of producing an IntTy result,
10835 /// like a scalar comparison, a vector comparison produces a vector of integer
10836 /// types.
10837 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10838                                           SourceLocation Loc,
10839                                           BinaryOperatorKind Opc) {
10840   // Check to make sure we're operating on vectors of the same type and width,
10841   // Allowing one side to be a scalar of element type.
10842   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10843                               /*AllowBothBool*/true,
10844                               /*AllowBoolConversions*/getLangOpts().ZVector);
10845   if (vType.isNull())
10846     return vType;
10847 
10848   QualType LHSType = LHS.get()->getType();
10849 
10850   // If AltiVec, the comparison results in a numeric type, i.e.
10851   // bool for C++, int for C
10852   if (getLangOpts().AltiVec &&
10853       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10854     return Context.getLogicalOperationType();
10855 
10856   // For non-floating point types, check for self-comparisons of the form
10857   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10858   // often indicate logic errors in the program.
10859   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10860 
10861   // Check for comparisons of floating point operands using != and ==.
10862   if (BinaryOperator::isEqualityOp(Opc) &&
10863       LHSType->hasFloatingRepresentation()) {
10864     assert(RHS.get()->getType()->hasFloatingRepresentation());
10865     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10866   }
10867 
10868   // Return a signed type for the vector.
10869   return GetSignedVectorType(vType);
10870 }
10871 
10872 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10873                                           SourceLocation Loc) {
10874   // Ensure that either both operands are of the same vector type, or
10875   // one operand is of a vector type and the other is of its element type.
10876   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10877                                        /*AllowBothBool*/true,
10878                                        /*AllowBoolConversions*/false);
10879   if (vType.isNull())
10880     return InvalidOperands(Loc, LHS, RHS);
10881   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10882       vType->hasFloatingRepresentation())
10883     return InvalidOperands(Loc, LHS, RHS);
10884   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10885   //        usage of the logical operators && and || with vectors in C. This
10886   //        check could be notionally dropped.
10887   if (!getLangOpts().CPlusPlus &&
10888       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10889     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10890 
10891   return GetSignedVectorType(LHS.get()->getType());
10892 }
10893 
10894 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10895                                            SourceLocation Loc,
10896                                            BinaryOperatorKind Opc) {
10897   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10898 
10899   bool IsCompAssign =
10900       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10901 
10902   if (LHS.get()->getType()->isVectorType() ||
10903       RHS.get()->getType()->isVectorType()) {
10904     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10905         RHS.get()->getType()->hasIntegerRepresentation())
10906       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10907                         /*AllowBothBool*/true,
10908                         /*AllowBoolConversions*/getLangOpts().ZVector);
10909     return InvalidOperands(Loc, LHS, RHS);
10910   }
10911 
10912   if (Opc == BO_And)
10913     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10914 
10915   ExprResult LHSResult = LHS, RHSResult = RHS;
10916   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10917                                                  IsCompAssign);
10918   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10919     return QualType();
10920   LHS = LHSResult.get();
10921   RHS = RHSResult.get();
10922 
10923   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10924     return compType;
10925   return InvalidOperands(Loc, LHS, RHS);
10926 }
10927 
10928 // C99 6.5.[13,14]
10929 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10930                                            SourceLocation Loc,
10931                                            BinaryOperatorKind Opc) {
10932   // Check vector operands differently.
10933   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10934     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10935 
10936   // Diagnose cases where the user write a logical and/or but probably meant a
10937   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10938   // is a constant.
10939   if (LHS.get()->getType()->isIntegerType() &&
10940       !LHS.get()->getType()->isBooleanType() &&
10941       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10942       // Don't warn in macros or template instantiations.
10943       !Loc.isMacroID() && !inTemplateInstantiation()) {
10944     // If the RHS can be constant folded, and if it constant folds to something
10945     // that isn't 0 or 1 (which indicate a potential logical operation that
10946     // happened to fold to true/false) then warn.
10947     // Parens on the RHS are ignored.
10948     Expr::EvalResult EVResult;
10949     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10950       llvm::APSInt Result = EVResult.Val.getInt();
10951       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10952            !RHS.get()->getExprLoc().isMacroID()) ||
10953           (Result != 0 && Result != 1)) {
10954         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10955           << RHS.get()->getSourceRange()
10956           << (Opc == BO_LAnd ? "&&" : "||");
10957         // Suggest replacing the logical operator with the bitwise version
10958         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10959             << (Opc == BO_LAnd ? "&" : "|")
10960             << FixItHint::CreateReplacement(SourceRange(
10961                                                  Loc, getLocForEndOfToken(Loc)),
10962                                             Opc == BO_LAnd ? "&" : "|");
10963         if (Opc == BO_LAnd)
10964           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10965           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10966               << FixItHint::CreateRemoval(
10967                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10968                                  RHS.get()->getEndLoc()));
10969       }
10970     }
10971   }
10972 
10973   if (!Context.getLangOpts().CPlusPlus) {
10974     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10975     // not operate on the built-in scalar and vector float types.
10976     if (Context.getLangOpts().OpenCL &&
10977         Context.getLangOpts().OpenCLVersion < 120) {
10978       if (LHS.get()->getType()->isFloatingType() ||
10979           RHS.get()->getType()->isFloatingType())
10980         return InvalidOperands(Loc, LHS, RHS);
10981     }
10982 
10983     LHS = UsualUnaryConversions(LHS.get());
10984     if (LHS.isInvalid())
10985       return QualType();
10986 
10987     RHS = UsualUnaryConversions(RHS.get());
10988     if (RHS.isInvalid())
10989       return QualType();
10990 
10991     if (!LHS.get()->getType()->isScalarType() ||
10992         !RHS.get()->getType()->isScalarType())
10993       return InvalidOperands(Loc, LHS, RHS);
10994 
10995     return Context.IntTy;
10996   }
10997 
10998   // The following is safe because we only use this method for
10999   // non-overloadable operands.
11000 
11001   // C++ [expr.log.and]p1
11002   // C++ [expr.log.or]p1
11003   // The operands are both contextually converted to type bool.
11004   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11005   if (LHSRes.isInvalid())
11006     return InvalidOperands(Loc, LHS, RHS);
11007   LHS = LHSRes;
11008 
11009   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11010   if (RHSRes.isInvalid())
11011     return InvalidOperands(Loc, LHS, RHS);
11012   RHS = RHSRes;
11013 
11014   // C++ [expr.log.and]p2
11015   // C++ [expr.log.or]p2
11016   // The result is a bool.
11017   return Context.BoolTy;
11018 }
11019 
11020 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11021   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11022   if (!ME) return false;
11023   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11024   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11025       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11026   if (!Base) return false;
11027   return Base->getMethodDecl() != nullptr;
11028 }
11029 
11030 /// Is the given expression (which must be 'const') a reference to a
11031 /// variable which was originally non-const, but which has become
11032 /// 'const' due to being captured within a block?
11033 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11034 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11035   assert(E->isLValue() && E->getType().isConstQualified());
11036   E = E->IgnoreParens();
11037 
11038   // Must be a reference to a declaration from an enclosing scope.
11039   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11040   if (!DRE) return NCCK_None;
11041   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11042 
11043   // The declaration must be a variable which is not declared 'const'.
11044   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11045   if (!var) return NCCK_None;
11046   if (var->getType().isConstQualified()) return NCCK_None;
11047   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11048 
11049   // Decide whether the first capture was for a block or a lambda.
11050   DeclContext *DC = S.CurContext, *Prev = nullptr;
11051   // Decide whether the first capture was for a block or a lambda.
11052   while (DC) {
11053     // For init-capture, it is possible that the variable belongs to the
11054     // template pattern of the current context.
11055     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11056       if (var->isInitCapture() &&
11057           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11058         break;
11059     if (DC == var->getDeclContext())
11060       break;
11061     Prev = DC;
11062     DC = DC->getParent();
11063   }
11064   // Unless we have an init-capture, we've gone one step too far.
11065   if (!var->isInitCapture())
11066     DC = Prev;
11067   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11068 }
11069 
11070 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11071   Ty = Ty.getNonReferenceType();
11072   if (IsDereference && Ty->isPointerType())
11073     Ty = Ty->getPointeeType();
11074   return !Ty.isConstQualified();
11075 }
11076 
11077 // Update err_typecheck_assign_const and note_typecheck_assign_const
11078 // when this enum is changed.
11079 enum {
11080   ConstFunction,
11081   ConstVariable,
11082   ConstMember,
11083   ConstMethod,
11084   NestedConstMember,
11085   ConstUnknown,  // Keep as last element
11086 };
11087 
11088 /// Emit the "read-only variable not assignable" error and print notes to give
11089 /// more information about why the variable is not assignable, such as pointing
11090 /// to the declaration of a const variable, showing that a method is const, or
11091 /// that the function is returning a const reference.
11092 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11093                                     SourceLocation Loc) {
11094   SourceRange ExprRange = E->getSourceRange();
11095 
11096   // Only emit one error on the first const found.  All other consts will emit
11097   // a note to the error.
11098   bool DiagnosticEmitted = false;
11099 
11100   // Track if the current expression is the result of a dereference, and if the
11101   // next checked expression is the result of a dereference.
11102   bool IsDereference = false;
11103   bool NextIsDereference = false;
11104 
11105   // Loop to process MemberExpr chains.
11106   while (true) {
11107     IsDereference = NextIsDereference;
11108 
11109     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11110     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11111       NextIsDereference = ME->isArrow();
11112       const ValueDecl *VD = ME->getMemberDecl();
11113       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11114         // Mutable fields can be modified even if the class is const.
11115         if (Field->isMutable()) {
11116           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11117           break;
11118         }
11119 
11120         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11121           if (!DiagnosticEmitted) {
11122             S.Diag(Loc, diag::err_typecheck_assign_const)
11123                 << ExprRange << ConstMember << false /*static*/ << Field
11124                 << Field->getType();
11125             DiagnosticEmitted = true;
11126           }
11127           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11128               << ConstMember << false /*static*/ << Field << Field->getType()
11129               << Field->getSourceRange();
11130         }
11131         E = ME->getBase();
11132         continue;
11133       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11134         if (VDecl->getType().isConstQualified()) {
11135           if (!DiagnosticEmitted) {
11136             S.Diag(Loc, diag::err_typecheck_assign_const)
11137                 << ExprRange << ConstMember << true /*static*/ << VDecl
11138                 << VDecl->getType();
11139             DiagnosticEmitted = true;
11140           }
11141           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11142               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11143               << VDecl->getSourceRange();
11144         }
11145         // Static fields do not inherit constness from parents.
11146         break;
11147       }
11148       break; // End MemberExpr
11149     } else if (const ArraySubscriptExpr *ASE =
11150                    dyn_cast<ArraySubscriptExpr>(E)) {
11151       E = ASE->getBase()->IgnoreParenImpCasts();
11152       continue;
11153     } else if (const ExtVectorElementExpr *EVE =
11154                    dyn_cast<ExtVectorElementExpr>(E)) {
11155       E = EVE->getBase()->IgnoreParenImpCasts();
11156       continue;
11157     }
11158     break;
11159   }
11160 
11161   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11162     // Function calls
11163     const FunctionDecl *FD = CE->getDirectCallee();
11164     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11165       if (!DiagnosticEmitted) {
11166         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11167                                                       << ConstFunction << FD;
11168         DiagnosticEmitted = true;
11169       }
11170       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11171              diag::note_typecheck_assign_const)
11172           << ConstFunction << FD << FD->getReturnType()
11173           << FD->getReturnTypeSourceRange();
11174     }
11175   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11176     // Point to variable declaration.
11177     if (const ValueDecl *VD = DRE->getDecl()) {
11178       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11179         if (!DiagnosticEmitted) {
11180           S.Diag(Loc, diag::err_typecheck_assign_const)
11181               << ExprRange << ConstVariable << VD << VD->getType();
11182           DiagnosticEmitted = true;
11183         }
11184         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11185             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11186       }
11187     }
11188   } else if (isa<CXXThisExpr>(E)) {
11189     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11190       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11191         if (MD->isConst()) {
11192           if (!DiagnosticEmitted) {
11193             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11194                                                           << ConstMethod << MD;
11195             DiagnosticEmitted = true;
11196           }
11197           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11198               << ConstMethod << MD << MD->getSourceRange();
11199         }
11200       }
11201     }
11202   }
11203 
11204   if (DiagnosticEmitted)
11205     return;
11206 
11207   // Can't determine a more specific message, so display the generic error.
11208   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11209 }
11210 
11211 enum OriginalExprKind {
11212   OEK_Variable,
11213   OEK_Member,
11214   OEK_LValue
11215 };
11216 
11217 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11218                                          const RecordType *Ty,
11219                                          SourceLocation Loc, SourceRange Range,
11220                                          OriginalExprKind OEK,
11221                                          bool &DiagnosticEmitted) {
11222   std::vector<const RecordType *> RecordTypeList;
11223   RecordTypeList.push_back(Ty);
11224   unsigned NextToCheckIndex = 0;
11225   // We walk the record hierarchy breadth-first to ensure that we print
11226   // diagnostics in field nesting order.
11227   while (RecordTypeList.size() > NextToCheckIndex) {
11228     bool IsNested = NextToCheckIndex > 0;
11229     for (const FieldDecl *Field :
11230          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11231       // First, check every field for constness.
11232       QualType FieldTy = Field->getType();
11233       if (FieldTy.isConstQualified()) {
11234         if (!DiagnosticEmitted) {
11235           S.Diag(Loc, diag::err_typecheck_assign_const)
11236               << Range << NestedConstMember << OEK << VD
11237               << IsNested << Field;
11238           DiagnosticEmitted = true;
11239         }
11240         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11241             << NestedConstMember << IsNested << Field
11242             << FieldTy << Field->getSourceRange();
11243       }
11244 
11245       // Then we append it to the list to check next in order.
11246       FieldTy = FieldTy.getCanonicalType();
11247       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11248         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11249           RecordTypeList.push_back(FieldRecTy);
11250       }
11251     }
11252     ++NextToCheckIndex;
11253   }
11254 }
11255 
11256 /// Emit an error for the case where a record we are trying to assign to has a
11257 /// const-qualified field somewhere in its hierarchy.
11258 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11259                                          SourceLocation Loc) {
11260   QualType Ty = E->getType();
11261   assert(Ty->isRecordType() && "lvalue was not record?");
11262   SourceRange Range = E->getSourceRange();
11263   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11264   bool DiagEmitted = false;
11265 
11266   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11267     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11268             Range, OEK_Member, DiagEmitted);
11269   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11270     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11271             Range, OEK_Variable, DiagEmitted);
11272   else
11273     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11274             Range, OEK_LValue, DiagEmitted);
11275   if (!DiagEmitted)
11276     DiagnoseConstAssignment(S, E, Loc);
11277 }
11278 
11279 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11280 /// emit an error and return true.  If so, return false.
11281 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11282   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11283 
11284   S.CheckShadowingDeclModification(E, Loc);
11285 
11286   SourceLocation OrigLoc = Loc;
11287   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11288                                                               &Loc);
11289   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11290     IsLV = Expr::MLV_InvalidMessageExpression;
11291   if (IsLV == Expr::MLV_Valid)
11292     return false;
11293 
11294   unsigned DiagID = 0;
11295   bool NeedType = false;
11296   switch (IsLV) { // C99 6.5.16p2
11297   case Expr::MLV_ConstQualified:
11298     // Use a specialized diagnostic when we're assigning to an object
11299     // from an enclosing function or block.
11300     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11301       if (NCCK == NCCK_Block)
11302         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11303       else
11304         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11305       break;
11306     }
11307 
11308     // In ARC, use some specialized diagnostics for occasions where we
11309     // infer 'const'.  These are always pseudo-strong variables.
11310     if (S.getLangOpts().ObjCAutoRefCount) {
11311       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11312       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11313         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11314 
11315         // Use the normal diagnostic if it's pseudo-__strong but the
11316         // user actually wrote 'const'.
11317         if (var->isARCPseudoStrong() &&
11318             (!var->getTypeSourceInfo() ||
11319              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11320           // There are three pseudo-strong cases:
11321           //  - self
11322           ObjCMethodDecl *method = S.getCurMethodDecl();
11323           if (method && var == method->getSelfDecl()) {
11324             DiagID = method->isClassMethod()
11325               ? diag::err_typecheck_arc_assign_self_class_method
11326               : diag::err_typecheck_arc_assign_self;
11327 
11328           //  - Objective-C externally_retained attribute.
11329           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11330                      isa<ParmVarDecl>(var)) {
11331             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11332 
11333           //  - fast enumeration variables
11334           } else {
11335             DiagID = diag::err_typecheck_arr_assign_enumeration;
11336           }
11337 
11338           SourceRange Assign;
11339           if (Loc != OrigLoc)
11340             Assign = SourceRange(OrigLoc, OrigLoc);
11341           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11342           // We need to preserve the AST regardless, so migration tool
11343           // can do its job.
11344           return false;
11345         }
11346       }
11347     }
11348 
11349     // If none of the special cases above are triggered, then this is a
11350     // simple const assignment.
11351     if (DiagID == 0) {
11352       DiagnoseConstAssignment(S, E, Loc);
11353       return true;
11354     }
11355 
11356     break;
11357   case Expr::MLV_ConstAddrSpace:
11358     DiagnoseConstAssignment(S, E, Loc);
11359     return true;
11360   case Expr::MLV_ConstQualifiedField:
11361     DiagnoseRecursiveConstFields(S, E, Loc);
11362     return true;
11363   case Expr::MLV_ArrayType:
11364   case Expr::MLV_ArrayTemporary:
11365     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11366     NeedType = true;
11367     break;
11368   case Expr::MLV_NotObjectType:
11369     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11370     NeedType = true;
11371     break;
11372   case Expr::MLV_LValueCast:
11373     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11374     break;
11375   case Expr::MLV_Valid:
11376     llvm_unreachable("did not take early return for MLV_Valid");
11377   case Expr::MLV_InvalidExpression:
11378   case Expr::MLV_MemberFunction:
11379   case Expr::MLV_ClassTemporary:
11380     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11381     break;
11382   case Expr::MLV_IncompleteType:
11383   case Expr::MLV_IncompleteVoidType:
11384     return S.RequireCompleteType(Loc, E->getType(),
11385              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11386   case Expr::MLV_DuplicateVectorComponents:
11387     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11388     break;
11389   case Expr::MLV_NoSetterProperty:
11390     llvm_unreachable("readonly properties should be processed differently");
11391   case Expr::MLV_InvalidMessageExpression:
11392     DiagID = diag::err_readonly_message_assignment;
11393     break;
11394   case Expr::MLV_SubObjCPropertySetting:
11395     DiagID = diag::err_no_subobject_property_setting;
11396     break;
11397   }
11398 
11399   SourceRange Assign;
11400   if (Loc != OrigLoc)
11401     Assign = SourceRange(OrigLoc, OrigLoc);
11402   if (NeedType)
11403     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11404   else
11405     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11406   return true;
11407 }
11408 
11409 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11410                                          SourceLocation Loc,
11411                                          Sema &Sema) {
11412   if (Sema.inTemplateInstantiation())
11413     return;
11414   if (Sema.isUnevaluatedContext())
11415     return;
11416   if (Loc.isInvalid() || Loc.isMacroID())
11417     return;
11418   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11419     return;
11420 
11421   // C / C++ fields
11422   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11423   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11424   if (ML && MR) {
11425     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11426       return;
11427     const ValueDecl *LHSDecl =
11428         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11429     const ValueDecl *RHSDecl =
11430         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11431     if (LHSDecl != RHSDecl)
11432       return;
11433     if (LHSDecl->getType().isVolatileQualified())
11434       return;
11435     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11436       if (RefTy->getPointeeType().isVolatileQualified())
11437         return;
11438 
11439     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11440   }
11441 
11442   // Objective-C instance variables
11443   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11444   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11445   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11446     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11447     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11448     if (RL && RR && RL->getDecl() == RR->getDecl())
11449       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11450   }
11451 }
11452 
11453 // C99 6.5.16.1
11454 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11455                                        SourceLocation Loc,
11456                                        QualType CompoundType) {
11457   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11458 
11459   // Verify that LHS is a modifiable lvalue, and emit error if not.
11460   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11461     return QualType();
11462 
11463   QualType LHSType = LHSExpr->getType();
11464   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11465                                              CompoundType;
11466   // OpenCL v1.2 s6.1.1.1 p2:
11467   // The half data type can only be used to declare a pointer to a buffer that
11468   // contains half values
11469   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11470     LHSType->isHalfType()) {
11471     Diag(Loc, diag::err_opencl_half_load_store) << 1
11472         << LHSType.getUnqualifiedType();
11473     return QualType();
11474   }
11475 
11476   AssignConvertType ConvTy;
11477   if (CompoundType.isNull()) {
11478     Expr *RHSCheck = RHS.get();
11479 
11480     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11481 
11482     QualType LHSTy(LHSType);
11483     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11484     if (RHS.isInvalid())
11485       return QualType();
11486     // Special case of NSObject attributes on c-style pointer types.
11487     if (ConvTy == IncompatiblePointer &&
11488         ((Context.isObjCNSObjectType(LHSType) &&
11489           RHSType->isObjCObjectPointerType()) ||
11490          (Context.isObjCNSObjectType(RHSType) &&
11491           LHSType->isObjCObjectPointerType())))
11492       ConvTy = Compatible;
11493 
11494     if (ConvTy == Compatible &&
11495         LHSType->isObjCObjectType())
11496         Diag(Loc, diag::err_objc_object_assignment)
11497           << LHSType;
11498 
11499     // If the RHS is a unary plus or minus, check to see if they = and + are
11500     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11501     // instead of "x += 4".
11502     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11503       RHSCheck = ICE->getSubExpr();
11504     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11505       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11506           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11507           // Only if the two operators are exactly adjacent.
11508           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11509           // And there is a space or other character before the subexpr of the
11510           // unary +/-.  We don't want to warn on "x=-1".
11511           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11512           UO->getSubExpr()->getBeginLoc().isFileID()) {
11513         Diag(Loc, diag::warn_not_compound_assign)
11514           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11515           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11516       }
11517     }
11518 
11519     if (ConvTy == Compatible) {
11520       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11521         // Warn about retain cycles where a block captures the LHS, but
11522         // not if the LHS is a simple variable into which the block is
11523         // being stored...unless that variable can be captured by reference!
11524         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11525         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11526         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11527           checkRetainCycles(LHSExpr, RHS.get());
11528       }
11529 
11530       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11531           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11532         // It is safe to assign a weak reference into a strong variable.
11533         // Although this code can still have problems:
11534         //   id x = self.weakProp;
11535         //   id y = self.weakProp;
11536         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11537         // paths through the function. This should be revisited if
11538         // -Wrepeated-use-of-weak is made flow-sensitive.
11539         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11540         // variable, which will be valid for the current autorelease scope.
11541         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11542                              RHS.get()->getBeginLoc()))
11543           getCurFunction()->markSafeWeakUse(RHS.get());
11544 
11545       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11546         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11547       }
11548     }
11549   } else {
11550     // Compound assignment "x += y"
11551     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11552   }
11553 
11554   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11555                                RHS.get(), AA_Assigning))
11556     return QualType();
11557 
11558   CheckForNullPointerDereference(*this, LHSExpr);
11559 
11560   // C99 6.5.16p3: The type of an assignment expression is the type of the
11561   // left operand unless the left operand has qualified type, in which case
11562   // it is the unqualified version of the type of the left operand.
11563   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11564   // is converted to the type of the assignment expression (above).
11565   // C++ 5.17p1: the type of the assignment expression is that of its left
11566   // operand.
11567   return (getLangOpts().CPlusPlus
11568           ? LHSType : LHSType.getUnqualifiedType());
11569 }
11570 
11571 // Only ignore explicit casts to void.
11572 static bool IgnoreCommaOperand(const Expr *E) {
11573   E = E->IgnoreParens();
11574 
11575   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11576     if (CE->getCastKind() == CK_ToVoid) {
11577       return true;
11578     }
11579 
11580     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11581     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11582         CE->getSubExpr()->getType()->isDependentType()) {
11583       return true;
11584     }
11585   }
11586 
11587   return false;
11588 }
11589 
11590 // Look for instances where it is likely the comma operator is confused with
11591 // another operator.  There is a whitelist of acceptable expressions for the
11592 // left hand side of the comma operator, otherwise emit a warning.
11593 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11594   // No warnings in macros
11595   if (Loc.isMacroID())
11596     return;
11597 
11598   // Don't warn in template instantiations.
11599   if (inTemplateInstantiation())
11600     return;
11601 
11602   // Scope isn't fine-grained enough to whitelist the specific cases, so
11603   // instead, skip more than needed, then call back into here with the
11604   // CommaVisitor in SemaStmt.cpp.
11605   // The whitelisted locations are the initialization and increment portions
11606   // of a for loop.  The additional checks are on the condition of
11607   // if statements, do/while loops, and for loops.
11608   // Differences in scope flags for C89 mode requires the extra logic.
11609   const unsigned ForIncrementFlags =
11610       getLangOpts().C99 || getLangOpts().CPlusPlus
11611           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11612           : Scope::ContinueScope | Scope::BreakScope;
11613   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11614   const unsigned ScopeFlags = getCurScope()->getFlags();
11615   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11616       (ScopeFlags & ForInitFlags) == ForInitFlags)
11617     return;
11618 
11619   // If there are multiple comma operators used together, get the RHS of the
11620   // of the comma operator as the LHS.
11621   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11622     if (BO->getOpcode() != BO_Comma)
11623       break;
11624     LHS = BO->getRHS();
11625   }
11626 
11627   // Only allow some expressions on LHS to not warn.
11628   if (IgnoreCommaOperand(LHS))
11629     return;
11630 
11631   Diag(Loc, diag::warn_comma_operator);
11632   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11633       << LHS->getSourceRange()
11634       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11635                                     LangOpts.CPlusPlus ? "static_cast<void>("
11636                                                        : "(void)(")
11637       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11638                                     ")");
11639 }
11640 
11641 // C99 6.5.17
11642 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11643                                    SourceLocation Loc) {
11644   LHS = S.CheckPlaceholderExpr(LHS.get());
11645   RHS = S.CheckPlaceholderExpr(RHS.get());
11646   if (LHS.isInvalid() || RHS.isInvalid())
11647     return QualType();
11648 
11649   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11650   // operands, but not unary promotions.
11651   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11652 
11653   // So we treat the LHS as a ignored value, and in C++ we allow the
11654   // containing site to determine what should be done with the RHS.
11655   LHS = S.IgnoredValueConversions(LHS.get());
11656   if (LHS.isInvalid())
11657     return QualType();
11658 
11659   S.DiagnoseUnusedExprResult(LHS.get());
11660 
11661   if (!S.getLangOpts().CPlusPlus) {
11662     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11663     if (RHS.isInvalid())
11664       return QualType();
11665     if (!RHS.get()->getType()->isVoidType())
11666       S.RequireCompleteType(Loc, RHS.get()->getType(),
11667                             diag::err_incomplete_type);
11668   }
11669 
11670   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11671     S.DiagnoseCommaOperator(LHS.get(), Loc);
11672 
11673   return RHS.get()->getType();
11674 }
11675 
11676 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11677 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11678 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11679                                                ExprValueKind &VK,
11680                                                ExprObjectKind &OK,
11681                                                SourceLocation OpLoc,
11682                                                bool IsInc, bool IsPrefix) {
11683   if (Op->isTypeDependent())
11684     return S.Context.DependentTy;
11685 
11686   QualType ResType = Op->getType();
11687   // Atomic types can be used for increment / decrement where the non-atomic
11688   // versions can, so ignore the _Atomic() specifier for the purpose of
11689   // checking.
11690   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11691     ResType = ResAtomicType->getValueType();
11692 
11693   assert(!ResType.isNull() && "no type for increment/decrement expression");
11694 
11695   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11696     // Decrement of bool is not allowed.
11697     if (!IsInc) {
11698       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11699       return QualType();
11700     }
11701     // Increment of bool sets it to true, but is deprecated.
11702     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11703                                               : diag::warn_increment_bool)
11704       << Op->getSourceRange();
11705   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11706     // Error on enum increments and decrements in C++ mode
11707     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11708     return QualType();
11709   } else if (ResType->isRealType()) {
11710     // OK!
11711   } else if (ResType->isPointerType()) {
11712     // C99 6.5.2.4p2, 6.5.6p2
11713     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11714       return QualType();
11715   } else if (ResType->isObjCObjectPointerType()) {
11716     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11717     // Otherwise, we just need a complete type.
11718     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11719         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11720       return QualType();
11721   } else if (ResType->isAnyComplexType()) {
11722     // C99 does not support ++/-- on complex types, we allow as an extension.
11723     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11724       << ResType << Op->getSourceRange();
11725   } else if (ResType->isPlaceholderType()) {
11726     ExprResult PR = S.CheckPlaceholderExpr(Op);
11727     if (PR.isInvalid()) return QualType();
11728     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11729                                           IsInc, IsPrefix);
11730   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11731     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11732   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11733              (ResType->getAs<VectorType>()->getVectorKind() !=
11734               VectorType::AltiVecBool)) {
11735     // The z vector extensions allow ++ and -- for non-bool vectors.
11736   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11737             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11738     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11739   } else {
11740     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11741       << ResType << int(IsInc) << Op->getSourceRange();
11742     return QualType();
11743   }
11744   // At this point, we know we have a real, complex or pointer type.
11745   // Now make sure the operand is a modifiable lvalue.
11746   if (CheckForModifiableLvalue(Op, OpLoc, S))
11747     return QualType();
11748   // In C++, a prefix increment is the same type as the operand. Otherwise
11749   // (in C or with postfix), the increment is the unqualified type of the
11750   // operand.
11751   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11752     VK = VK_LValue;
11753     OK = Op->getObjectKind();
11754     return ResType;
11755   } else {
11756     VK = VK_RValue;
11757     return ResType.getUnqualifiedType();
11758   }
11759 }
11760 
11761 
11762 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11763 /// This routine allows us to typecheck complex/recursive expressions
11764 /// where the declaration is needed for type checking. We only need to
11765 /// handle cases when the expression references a function designator
11766 /// or is an lvalue. Here are some examples:
11767 ///  - &(x) => x
11768 ///  - &*****f => f for f a function designator.
11769 ///  - &s.xx => s
11770 ///  - &s.zz[1].yy -> s, if zz is an array
11771 ///  - *(x + 1) -> x, if x is an array
11772 ///  - &"123"[2] -> 0
11773 ///  - & __real__ x -> x
11774 static ValueDecl *getPrimaryDecl(Expr *E) {
11775   switch (E->getStmtClass()) {
11776   case Stmt::DeclRefExprClass:
11777     return cast<DeclRefExpr>(E)->getDecl();
11778   case Stmt::MemberExprClass:
11779     // If this is an arrow operator, the address is an offset from
11780     // the base's value, so the object the base refers to is
11781     // irrelevant.
11782     if (cast<MemberExpr>(E)->isArrow())
11783       return nullptr;
11784     // Otherwise, the expression refers to a part of the base
11785     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11786   case Stmt::ArraySubscriptExprClass: {
11787     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11788     // promotion of register arrays earlier.
11789     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11790     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11791       if (ICE->getSubExpr()->getType()->isArrayType())
11792         return getPrimaryDecl(ICE->getSubExpr());
11793     }
11794     return nullptr;
11795   }
11796   case Stmt::UnaryOperatorClass: {
11797     UnaryOperator *UO = cast<UnaryOperator>(E);
11798 
11799     switch(UO->getOpcode()) {
11800     case UO_Real:
11801     case UO_Imag:
11802     case UO_Extension:
11803       return getPrimaryDecl(UO->getSubExpr());
11804     default:
11805       return nullptr;
11806     }
11807   }
11808   case Stmt::ParenExprClass:
11809     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11810   case Stmt::ImplicitCastExprClass:
11811     // If the result of an implicit cast is an l-value, we care about
11812     // the sub-expression; otherwise, the result here doesn't matter.
11813     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11814   default:
11815     return nullptr;
11816   }
11817 }
11818 
11819 namespace {
11820   enum {
11821     AO_Bit_Field = 0,
11822     AO_Vector_Element = 1,
11823     AO_Property_Expansion = 2,
11824     AO_Register_Variable = 3,
11825     AO_No_Error = 4
11826   };
11827 }
11828 /// Diagnose invalid operand for address of operations.
11829 ///
11830 /// \param Type The type of operand which cannot have its address taken.
11831 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11832                                          Expr *E, unsigned Type) {
11833   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11834 }
11835 
11836 /// CheckAddressOfOperand - The operand of & must be either a function
11837 /// designator or an lvalue designating an object. If it is an lvalue, the
11838 /// object cannot be declared with storage class register or be a bit field.
11839 /// Note: The usual conversions are *not* applied to the operand of the &
11840 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11841 /// In C++, the operand might be an overloaded function name, in which case
11842 /// we allow the '&' but retain the overloaded-function type.
11843 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11844   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11845     if (PTy->getKind() == BuiltinType::Overload) {
11846       Expr *E = OrigOp.get()->IgnoreParens();
11847       if (!isa<OverloadExpr>(E)) {
11848         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11849         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11850           << OrigOp.get()->getSourceRange();
11851         return QualType();
11852       }
11853 
11854       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11855       if (isa<UnresolvedMemberExpr>(Ovl))
11856         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11857           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11858             << OrigOp.get()->getSourceRange();
11859           return QualType();
11860         }
11861 
11862       return Context.OverloadTy;
11863     }
11864 
11865     if (PTy->getKind() == BuiltinType::UnknownAny)
11866       return Context.UnknownAnyTy;
11867 
11868     if (PTy->getKind() == BuiltinType::BoundMember) {
11869       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11870         << OrigOp.get()->getSourceRange();
11871       return QualType();
11872     }
11873 
11874     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11875     if (OrigOp.isInvalid()) return QualType();
11876   }
11877 
11878   if (OrigOp.get()->isTypeDependent())
11879     return Context.DependentTy;
11880 
11881   assert(!OrigOp.get()->getType()->isPlaceholderType());
11882 
11883   // Make sure to ignore parentheses in subsequent checks
11884   Expr *op = OrigOp.get()->IgnoreParens();
11885 
11886   // In OpenCL captures for blocks called as lambda functions
11887   // are located in the private address space. Blocks used in
11888   // enqueue_kernel can be located in a different address space
11889   // depending on a vendor implementation. Thus preventing
11890   // taking an address of the capture to avoid invalid AS casts.
11891   if (LangOpts.OpenCL) {
11892     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11893     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11894       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11895       return QualType();
11896     }
11897   }
11898 
11899   if (getLangOpts().C99) {
11900     // Implement C99-only parts of addressof rules.
11901     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11902       if (uOp->getOpcode() == UO_Deref)
11903         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11904         // (assuming the deref expression is valid).
11905         return uOp->getSubExpr()->getType();
11906     }
11907     // Technically, there should be a check for array subscript
11908     // expressions here, but the result of one is always an lvalue anyway.
11909   }
11910   ValueDecl *dcl = getPrimaryDecl(op);
11911 
11912   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11913     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11914                                            op->getBeginLoc()))
11915       return QualType();
11916 
11917   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11918   unsigned AddressOfError = AO_No_Error;
11919 
11920   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11921     bool sfinae = (bool)isSFINAEContext();
11922     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11923                                   : diag::ext_typecheck_addrof_temporary)
11924       << op->getType() << op->getSourceRange();
11925     if (sfinae)
11926       return QualType();
11927     // Materialize the temporary as an lvalue so that we can take its address.
11928     OrigOp = op =
11929         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11930   } else if (isa<ObjCSelectorExpr>(op)) {
11931     return Context.getPointerType(op->getType());
11932   } else if (lval == Expr::LV_MemberFunction) {
11933     // If it's an instance method, make a member pointer.
11934     // The expression must have exactly the form &A::foo.
11935 
11936     // If the underlying expression isn't a decl ref, give up.
11937     if (!isa<DeclRefExpr>(op)) {
11938       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11939         << OrigOp.get()->getSourceRange();
11940       return QualType();
11941     }
11942     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11943     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11944 
11945     // The id-expression was parenthesized.
11946     if (OrigOp.get() != DRE) {
11947       Diag(OpLoc, diag::err_parens_pointer_member_function)
11948         << OrigOp.get()->getSourceRange();
11949 
11950     // The method was named without a qualifier.
11951     } else if (!DRE->getQualifier()) {
11952       if (MD->getParent()->getName().empty())
11953         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11954           << op->getSourceRange();
11955       else {
11956         SmallString<32> Str;
11957         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11958         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11959           << op->getSourceRange()
11960           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11961       }
11962     }
11963 
11964     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11965     if (isa<CXXDestructorDecl>(MD))
11966       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11967 
11968     QualType MPTy = Context.getMemberPointerType(
11969         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11970     // Under the MS ABI, lock down the inheritance model now.
11971     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11972       (void)isCompleteType(OpLoc, MPTy);
11973     return MPTy;
11974   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11975     // C99 6.5.3.2p1
11976     // The operand must be either an l-value or a function designator
11977     if (!op->getType()->isFunctionType()) {
11978       // Use a special diagnostic for loads from property references.
11979       if (isa<PseudoObjectExpr>(op)) {
11980         AddressOfError = AO_Property_Expansion;
11981       } else {
11982         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11983           << op->getType() << op->getSourceRange();
11984         return QualType();
11985       }
11986     }
11987   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11988     // The operand cannot be a bit-field
11989     AddressOfError = AO_Bit_Field;
11990   } else if (op->getObjectKind() == OK_VectorComponent) {
11991     // The operand cannot be an element of a vector
11992     AddressOfError = AO_Vector_Element;
11993   } else if (dcl) { // C99 6.5.3.2p1
11994     // We have an lvalue with a decl. Make sure the decl is not declared
11995     // with the register storage-class specifier.
11996     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11997       // in C++ it is not error to take address of a register
11998       // variable (c++03 7.1.1P3)
11999       if (vd->getStorageClass() == SC_Register &&
12000           !getLangOpts().CPlusPlus) {
12001         AddressOfError = AO_Register_Variable;
12002       }
12003     } else if (isa<MSPropertyDecl>(dcl)) {
12004       AddressOfError = AO_Property_Expansion;
12005     } else if (isa<FunctionTemplateDecl>(dcl)) {
12006       return Context.OverloadTy;
12007     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12008       // Okay: we can take the address of a field.
12009       // Could be a pointer to member, though, if there is an explicit
12010       // scope qualifier for the class.
12011       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12012         DeclContext *Ctx = dcl->getDeclContext();
12013         if (Ctx && Ctx->isRecord()) {
12014           if (dcl->getType()->isReferenceType()) {
12015             Diag(OpLoc,
12016                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12017               << dcl->getDeclName() << dcl->getType();
12018             return QualType();
12019           }
12020 
12021           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12022             Ctx = Ctx->getParent();
12023 
12024           QualType MPTy = Context.getMemberPointerType(
12025               op->getType(),
12026               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12027           // Under the MS ABI, lock down the inheritance model now.
12028           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12029             (void)isCompleteType(OpLoc, MPTy);
12030           return MPTy;
12031         }
12032       }
12033     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12034                !isa<BindingDecl>(dcl))
12035       llvm_unreachable("Unknown/unexpected decl type");
12036   }
12037 
12038   if (AddressOfError != AO_No_Error) {
12039     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12040     return QualType();
12041   }
12042 
12043   if (lval == Expr::LV_IncompleteVoidType) {
12044     // Taking the address of a void variable is technically illegal, but we
12045     // allow it in cases which are otherwise valid.
12046     // Example: "extern void x; void* y = &x;".
12047     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12048   }
12049 
12050   // If the operand has type "type", the result has type "pointer to type".
12051   if (op->getType()->isObjCObjectType())
12052     return Context.getObjCObjectPointerType(op->getType());
12053 
12054   CheckAddressOfPackedMember(op);
12055 
12056   return Context.getPointerType(op->getType());
12057 }
12058 
12059 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12060   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12061   if (!DRE)
12062     return;
12063   const Decl *D = DRE->getDecl();
12064   if (!D)
12065     return;
12066   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12067   if (!Param)
12068     return;
12069   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12070     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12071       return;
12072   if (FunctionScopeInfo *FD = S.getCurFunction())
12073     if (!FD->ModifiedNonNullParams.count(Param))
12074       FD->ModifiedNonNullParams.insert(Param);
12075 }
12076 
12077 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12078 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12079                                         SourceLocation OpLoc) {
12080   if (Op->isTypeDependent())
12081     return S.Context.DependentTy;
12082 
12083   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12084   if (ConvResult.isInvalid())
12085     return QualType();
12086   Op = ConvResult.get();
12087   QualType OpTy = Op->getType();
12088   QualType Result;
12089 
12090   if (isa<CXXReinterpretCastExpr>(Op)) {
12091     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12092     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12093                                      Op->getSourceRange());
12094   }
12095 
12096   if (const PointerType *PT = OpTy->getAs<PointerType>())
12097   {
12098     Result = PT->getPointeeType();
12099   }
12100   else if (const ObjCObjectPointerType *OPT =
12101              OpTy->getAs<ObjCObjectPointerType>())
12102     Result = OPT->getPointeeType();
12103   else {
12104     ExprResult PR = S.CheckPlaceholderExpr(Op);
12105     if (PR.isInvalid()) return QualType();
12106     if (PR.get() != Op)
12107       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12108   }
12109 
12110   if (Result.isNull()) {
12111     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12112       << OpTy << Op->getSourceRange();
12113     return QualType();
12114   }
12115 
12116   // Note that per both C89 and C99, indirection is always legal, even if Result
12117   // is an incomplete type or void.  It would be possible to warn about
12118   // dereferencing a void pointer, but it's completely well-defined, and such a
12119   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12120   // for pointers to 'void' but is fine for any other pointer type:
12121   //
12122   // C++ [expr.unary.op]p1:
12123   //   [...] the expression to which [the unary * operator] is applied shall
12124   //   be a pointer to an object type, or a pointer to a function type
12125   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12126     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12127       << OpTy << Op->getSourceRange();
12128 
12129   // Dereferences are usually l-values...
12130   VK = VK_LValue;
12131 
12132   // ...except that certain expressions are never l-values in C.
12133   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12134     VK = VK_RValue;
12135 
12136   return Result;
12137 }
12138 
12139 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12140   BinaryOperatorKind Opc;
12141   switch (Kind) {
12142   default: llvm_unreachable("Unknown binop!");
12143   case tok::periodstar:           Opc = BO_PtrMemD; break;
12144   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12145   case tok::star:                 Opc = BO_Mul; break;
12146   case tok::slash:                Opc = BO_Div; break;
12147   case tok::percent:              Opc = BO_Rem; break;
12148   case tok::plus:                 Opc = BO_Add; break;
12149   case tok::minus:                Opc = BO_Sub; break;
12150   case tok::lessless:             Opc = BO_Shl; break;
12151   case tok::greatergreater:       Opc = BO_Shr; break;
12152   case tok::lessequal:            Opc = BO_LE; break;
12153   case tok::less:                 Opc = BO_LT; break;
12154   case tok::greaterequal:         Opc = BO_GE; break;
12155   case tok::greater:              Opc = BO_GT; break;
12156   case tok::exclaimequal:         Opc = BO_NE; break;
12157   case tok::equalequal:           Opc = BO_EQ; break;
12158   case tok::spaceship:            Opc = BO_Cmp; break;
12159   case tok::amp:                  Opc = BO_And; break;
12160   case tok::caret:                Opc = BO_Xor; break;
12161   case tok::pipe:                 Opc = BO_Or; break;
12162   case tok::ampamp:               Opc = BO_LAnd; break;
12163   case tok::pipepipe:             Opc = BO_LOr; break;
12164   case tok::equal:                Opc = BO_Assign; break;
12165   case tok::starequal:            Opc = BO_MulAssign; break;
12166   case tok::slashequal:           Opc = BO_DivAssign; break;
12167   case tok::percentequal:         Opc = BO_RemAssign; break;
12168   case tok::plusequal:            Opc = BO_AddAssign; break;
12169   case tok::minusequal:           Opc = BO_SubAssign; break;
12170   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12171   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12172   case tok::ampequal:             Opc = BO_AndAssign; break;
12173   case tok::caretequal:           Opc = BO_XorAssign; break;
12174   case tok::pipeequal:            Opc = BO_OrAssign; break;
12175   case tok::comma:                Opc = BO_Comma; break;
12176   }
12177   return Opc;
12178 }
12179 
12180 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12181   tok::TokenKind Kind) {
12182   UnaryOperatorKind Opc;
12183   switch (Kind) {
12184   default: llvm_unreachable("Unknown unary op!");
12185   case tok::plusplus:     Opc = UO_PreInc; break;
12186   case tok::minusminus:   Opc = UO_PreDec; break;
12187   case tok::amp:          Opc = UO_AddrOf; break;
12188   case tok::star:         Opc = UO_Deref; break;
12189   case tok::plus:         Opc = UO_Plus; break;
12190   case tok::minus:        Opc = UO_Minus; break;
12191   case tok::tilde:        Opc = UO_Not; break;
12192   case tok::exclaim:      Opc = UO_LNot; break;
12193   case tok::kw___real:    Opc = UO_Real; break;
12194   case tok::kw___imag:    Opc = UO_Imag; break;
12195   case tok::kw___extension__: Opc = UO_Extension; break;
12196   }
12197   return Opc;
12198 }
12199 
12200 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12201 /// This warning suppressed in the event of macro expansions.
12202 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12203                                    SourceLocation OpLoc, bool IsBuiltin) {
12204   if (S.inTemplateInstantiation())
12205     return;
12206   if (S.isUnevaluatedContext())
12207     return;
12208   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12209     return;
12210   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12211   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12212   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12213   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12214   if (!LHSDeclRef || !RHSDeclRef ||
12215       LHSDeclRef->getLocation().isMacroID() ||
12216       RHSDeclRef->getLocation().isMacroID())
12217     return;
12218   const ValueDecl *LHSDecl =
12219     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12220   const ValueDecl *RHSDecl =
12221     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12222   if (LHSDecl != RHSDecl)
12223     return;
12224   if (LHSDecl->getType().isVolatileQualified())
12225     return;
12226   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12227     if (RefTy->getPointeeType().isVolatileQualified())
12228       return;
12229 
12230   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12231                           : diag::warn_self_assignment_overloaded)
12232       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12233       << RHSExpr->getSourceRange();
12234 }
12235 
12236 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12237 /// is usually indicative of introspection within the Objective-C pointer.
12238 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12239                                           SourceLocation OpLoc) {
12240   if (!S.getLangOpts().ObjC)
12241     return;
12242 
12243   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12244   const Expr *LHS = L.get();
12245   const Expr *RHS = R.get();
12246 
12247   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12248     ObjCPointerExpr = LHS;
12249     OtherExpr = RHS;
12250   }
12251   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12252     ObjCPointerExpr = RHS;
12253     OtherExpr = LHS;
12254   }
12255 
12256   // This warning is deliberately made very specific to reduce false
12257   // positives with logic that uses '&' for hashing.  This logic mainly
12258   // looks for code trying to introspect into tagged pointers, which
12259   // code should generally never do.
12260   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12261     unsigned Diag = diag::warn_objc_pointer_masking;
12262     // Determine if we are introspecting the result of performSelectorXXX.
12263     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12264     // Special case messages to -performSelector and friends, which
12265     // can return non-pointer values boxed in a pointer value.
12266     // Some clients may wish to silence warnings in this subcase.
12267     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12268       Selector S = ME->getSelector();
12269       StringRef SelArg0 = S.getNameForSlot(0);
12270       if (SelArg0.startswith("performSelector"))
12271         Diag = diag::warn_objc_pointer_masking_performSelector;
12272     }
12273 
12274     S.Diag(OpLoc, Diag)
12275       << ObjCPointerExpr->getSourceRange();
12276   }
12277 }
12278 
12279 static NamedDecl *getDeclFromExpr(Expr *E) {
12280   if (!E)
12281     return nullptr;
12282   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12283     return DRE->getDecl();
12284   if (auto *ME = dyn_cast<MemberExpr>(E))
12285     return ME->getMemberDecl();
12286   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12287     return IRE->getDecl();
12288   return nullptr;
12289 }
12290 
12291 // This helper function promotes a binary operator's operands (which are of a
12292 // half vector type) to a vector of floats and then truncates the result to
12293 // a vector of either half or short.
12294 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12295                                       BinaryOperatorKind Opc, QualType ResultTy,
12296                                       ExprValueKind VK, ExprObjectKind OK,
12297                                       bool IsCompAssign, SourceLocation OpLoc,
12298                                       FPOptions FPFeatures) {
12299   auto &Context = S.getASTContext();
12300   assert((isVector(ResultTy, Context.HalfTy) ||
12301           isVector(ResultTy, Context.ShortTy)) &&
12302          "Result must be a vector of half or short");
12303   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12304          isVector(RHS.get()->getType(), Context.HalfTy) &&
12305          "both operands expected to be a half vector");
12306 
12307   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12308   QualType BinOpResTy = RHS.get()->getType();
12309 
12310   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12311   // change BinOpResTy to a vector of ints.
12312   if (isVector(ResultTy, Context.ShortTy))
12313     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12314 
12315   if (IsCompAssign)
12316     return new (Context) CompoundAssignOperator(
12317         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12318         OpLoc, FPFeatures);
12319 
12320   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12321   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12322                                           VK, OK, OpLoc, FPFeatures);
12323   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12324 }
12325 
12326 static std::pair<ExprResult, ExprResult>
12327 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12328                            Expr *RHSExpr) {
12329   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12330   if (!S.getLangOpts().CPlusPlus) {
12331     // C cannot handle TypoExpr nodes on either side of a binop because it
12332     // doesn't handle dependent types properly, so make sure any TypoExprs have
12333     // been dealt with before checking the operands.
12334     LHS = S.CorrectDelayedTyposInExpr(LHS);
12335     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12336       if (Opc != BO_Assign)
12337         return ExprResult(E);
12338       // Avoid correcting the RHS to the same Expr as the LHS.
12339       Decl *D = getDeclFromExpr(E);
12340       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12341     });
12342   }
12343   return std::make_pair(LHS, RHS);
12344 }
12345 
12346 /// Returns true if conversion between vectors of halfs and vectors of floats
12347 /// is needed.
12348 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12349                                      QualType SrcType) {
12350   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12351          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12352          isVector(SrcType, Ctx.HalfTy);
12353 }
12354 
12355 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12356 /// operator @p Opc at location @c TokLoc. This routine only supports
12357 /// built-in operations; ActOnBinOp handles overloaded operators.
12358 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12359                                     BinaryOperatorKind Opc,
12360                                     Expr *LHSExpr, Expr *RHSExpr) {
12361   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12362     // The syntax only allows initializer lists on the RHS of assignment,
12363     // so we don't need to worry about accepting invalid code for
12364     // non-assignment operators.
12365     // C++11 5.17p9:
12366     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12367     //   of x = {} is x = T().
12368     InitializationKind Kind = InitializationKind::CreateDirectList(
12369         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12370     InitializedEntity Entity =
12371         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12372     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12373     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12374     if (Init.isInvalid())
12375       return Init;
12376     RHSExpr = Init.get();
12377   }
12378 
12379   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12380   QualType ResultTy;     // Result type of the binary operator.
12381   // The following two variables are used for compound assignment operators
12382   QualType CompLHSTy;    // Type of LHS after promotions for computation
12383   QualType CompResultTy; // Type of computation result
12384   ExprValueKind VK = VK_RValue;
12385   ExprObjectKind OK = OK_Ordinary;
12386   bool ConvertHalfVec = false;
12387 
12388   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12389   if (!LHS.isUsable() || !RHS.isUsable())
12390     return ExprError();
12391 
12392   if (getLangOpts().OpenCL) {
12393     QualType LHSTy = LHSExpr->getType();
12394     QualType RHSTy = RHSExpr->getType();
12395     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12396     // the ATOMIC_VAR_INIT macro.
12397     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12398       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12399       if (BO_Assign == Opc)
12400         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12401       else
12402         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12403       return ExprError();
12404     }
12405 
12406     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12407     // only with a builtin functions and therefore should be disallowed here.
12408     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12409         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12410         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12411         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12412       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12413       return ExprError();
12414     }
12415   }
12416 
12417   switch (Opc) {
12418   case BO_Assign:
12419     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12420     if (getLangOpts().CPlusPlus &&
12421         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12422       VK = LHS.get()->getValueKind();
12423       OK = LHS.get()->getObjectKind();
12424     }
12425     if (!ResultTy.isNull()) {
12426       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12427       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12428     }
12429     RecordModifiableNonNullParam(*this, LHS.get());
12430     break;
12431   case BO_PtrMemD:
12432   case BO_PtrMemI:
12433     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12434                                             Opc == BO_PtrMemI);
12435     break;
12436   case BO_Mul:
12437   case BO_Div:
12438     ConvertHalfVec = true;
12439     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12440                                            Opc == BO_Div);
12441     break;
12442   case BO_Rem:
12443     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12444     break;
12445   case BO_Add:
12446     ConvertHalfVec = true;
12447     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12448     break;
12449   case BO_Sub:
12450     ConvertHalfVec = true;
12451     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12452     break;
12453   case BO_Shl:
12454   case BO_Shr:
12455     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12456     break;
12457   case BO_LE:
12458   case BO_LT:
12459   case BO_GE:
12460   case BO_GT:
12461     ConvertHalfVec = true;
12462     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12463     break;
12464   case BO_EQ:
12465   case BO_NE:
12466     ConvertHalfVec = true;
12467     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12468     break;
12469   case BO_Cmp:
12470     ConvertHalfVec = true;
12471     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12472     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12473     break;
12474   case BO_And:
12475     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12476     LLVM_FALLTHROUGH;
12477   case BO_Xor:
12478   case BO_Or:
12479     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12480     break;
12481   case BO_LAnd:
12482   case BO_LOr:
12483     ConvertHalfVec = true;
12484     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12485     break;
12486   case BO_MulAssign:
12487   case BO_DivAssign:
12488     ConvertHalfVec = true;
12489     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12490                                                Opc == BO_DivAssign);
12491     CompLHSTy = CompResultTy;
12492     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12493       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12494     break;
12495   case BO_RemAssign:
12496     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12497     CompLHSTy = CompResultTy;
12498     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12499       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12500     break;
12501   case BO_AddAssign:
12502     ConvertHalfVec = true;
12503     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12504     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12505       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12506     break;
12507   case BO_SubAssign:
12508     ConvertHalfVec = true;
12509     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12510     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12511       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12512     break;
12513   case BO_ShlAssign:
12514   case BO_ShrAssign:
12515     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12516     CompLHSTy = CompResultTy;
12517     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12518       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12519     break;
12520   case BO_AndAssign:
12521   case BO_OrAssign: // fallthrough
12522     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12523     LLVM_FALLTHROUGH;
12524   case BO_XorAssign:
12525     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12526     CompLHSTy = CompResultTy;
12527     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12528       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12529     break;
12530   case BO_Comma:
12531     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12532     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12533       VK = RHS.get()->getValueKind();
12534       OK = RHS.get()->getObjectKind();
12535     }
12536     break;
12537   }
12538   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12539     return ExprError();
12540 
12541   // Some of the binary operations require promoting operands of half vector to
12542   // float vectors and truncating the result back to half vector. For now, we do
12543   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12544   // arm64).
12545   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12546          isVector(LHS.get()->getType(), Context.HalfTy) &&
12547          "both sides are half vectors or neither sides are");
12548   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12549                                             LHS.get()->getType());
12550 
12551   // Check for array bounds violations for both sides of the BinaryOperator
12552   CheckArrayAccess(LHS.get());
12553   CheckArrayAccess(RHS.get());
12554 
12555   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12556     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12557                                                  &Context.Idents.get("object_setClass"),
12558                                                  SourceLocation(), LookupOrdinaryName);
12559     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12560       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12561       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12562           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12563                                         "object_setClass(")
12564           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12565                                           ",")
12566           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12567     }
12568     else
12569       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12570   }
12571   else if (const ObjCIvarRefExpr *OIRE =
12572            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12573     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12574 
12575   // Opc is not a compound assignment if CompResultTy is null.
12576   if (CompResultTy.isNull()) {
12577     if (ConvertHalfVec)
12578       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12579                                  OpLoc, FPFeatures);
12580     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12581                                         OK, OpLoc, FPFeatures);
12582   }
12583 
12584   // Handle compound assignments.
12585   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12586       OK_ObjCProperty) {
12587     VK = VK_LValue;
12588     OK = LHS.get()->getObjectKind();
12589   }
12590 
12591   if (ConvertHalfVec)
12592     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12593                                OpLoc, FPFeatures);
12594 
12595   return new (Context) CompoundAssignOperator(
12596       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12597       OpLoc, FPFeatures);
12598 }
12599 
12600 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12601 /// operators are mixed in a way that suggests that the programmer forgot that
12602 /// comparison operators have higher precedence. The most typical example of
12603 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12604 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12605                                       SourceLocation OpLoc, Expr *LHSExpr,
12606                                       Expr *RHSExpr) {
12607   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12608   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12609 
12610   // Check that one of the sides is a comparison operator and the other isn't.
12611   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12612   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12613   if (isLeftComp == isRightComp)
12614     return;
12615 
12616   // Bitwise operations are sometimes used as eager logical ops.
12617   // Don't diagnose this.
12618   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12619   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12620   if (isLeftBitwise || isRightBitwise)
12621     return;
12622 
12623   SourceRange DiagRange = isLeftComp
12624                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12625                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12626   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12627   SourceRange ParensRange =
12628       isLeftComp
12629           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12630           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12631 
12632   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12633     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12634   SuggestParentheses(Self, OpLoc,
12635     Self.PDiag(diag::note_precedence_silence) << OpStr,
12636     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12637   SuggestParentheses(Self, OpLoc,
12638     Self.PDiag(diag::note_precedence_bitwise_first)
12639       << BinaryOperator::getOpcodeStr(Opc),
12640     ParensRange);
12641 }
12642 
12643 /// It accepts a '&&' expr that is inside a '||' one.
12644 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12645 /// in parentheses.
12646 static void
12647 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12648                                        BinaryOperator *Bop) {
12649   assert(Bop->getOpcode() == BO_LAnd);
12650   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12651       << Bop->getSourceRange() << OpLoc;
12652   SuggestParentheses(Self, Bop->getOperatorLoc(),
12653     Self.PDiag(diag::note_precedence_silence)
12654       << Bop->getOpcodeStr(),
12655     Bop->getSourceRange());
12656 }
12657 
12658 /// Returns true if the given expression can be evaluated as a constant
12659 /// 'true'.
12660 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12661   bool Res;
12662   return !E->isValueDependent() &&
12663          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12664 }
12665 
12666 /// Returns true if the given expression can be evaluated as a constant
12667 /// 'false'.
12668 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12669   bool Res;
12670   return !E->isValueDependent() &&
12671          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12672 }
12673 
12674 /// Look for '&&' in the left hand of a '||' expr.
12675 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12676                                              Expr *LHSExpr, Expr *RHSExpr) {
12677   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12678     if (Bop->getOpcode() == BO_LAnd) {
12679       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12680       if (EvaluatesAsFalse(S, RHSExpr))
12681         return;
12682       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12683       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12684         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12685     } else if (Bop->getOpcode() == BO_LOr) {
12686       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12687         // If it's "a || b && 1 || c" we didn't warn earlier for
12688         // "a || b && 1", but warn now.
12689         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12690           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12691       }
12692     }
12693   }
12694 }
12695 
12696 /// Look for '&&' in the right hand of a '||' expr.
12697 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12698                                              Expr *LHSExpr, Expr *RHSExpr) {
12699   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12700     if (Bop->getOpcode() == BO_LAnd) {
12701       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12702       if (EvaluatesAsFalse(S, LHSExpr))
12703         return;
12704       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12705       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12706         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12707     }
12708   }
12709 }
12710 
12711 /// Look for bitwise op in the left or right hand of a bitwise op with
12712 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12713 /// the '&' expression in parentheses.
12714 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12715                                          SourceLocation OpLoc, Expr *SubExpr) {
12716   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12717     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12718       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12719         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12720         << Bop->getSourceRange() << OpLoc;
12721       SuggestParentheses(S, Bop->getOperatorLoc(),
12722         S.PDiag(diag::note_precedence_silence)
12723           << Bop->getOpcodeStr(),
12724         Bop->getSourceRange());
12725     }
12726   }
12727 }
12728 
12729 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12730                                     Expr *SubExpr, StringRef Shift) {
12731   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12732     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12733       StringRef Op = Bop->getOpcodeStr();
12734       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12735           << Bop->getSourceRange() << OpLoc << Shift << Op;
12736       SuggestParentheses(S, Bop->getOperatorLoc(),
12737           S.PDiag(diag::note_precedence_silence) << Op,
12738           Bop->getSourceRange());
12739     }
12740   }
12741 }
12742 
12743 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12744                                  Expr *LHSExpr, Expr *RHSExpr) {
12745   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12746   if (!OCE)
12747     return;
12748 
12749   FunctionDecl *FD = OCE->getDirectCallee();
12750   if (!FD || !FD->isOverloadedOperator())
12751     return;
12752 
12753   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12754   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12755     return;
12756 
12757   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12758       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12759       << (Kind == OO_LessLess);
12760   SuggestParentheses(S, OCE->getOperatorLoc(),
12761                      S.PDiag(diag::note_precedence_silence)
12762                          << (Kind == OO_LessLess ? "<<" : ">>"),
12763                      OCE->getSourceRange());
12764   SuggestParentheses(
12765       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12766       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12767 }
12768 
12769 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12770 /// precedence.
12771 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12772                                     SourceLocation OpLoc, Expr *LHSExpr,
12773                                     Expr *RHSExpr){
12774   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12775   if (BinaryOperator::isBitwiseOp(Opc))
12776     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12777 
12778   // Diagnose "arg1 & arg2 | arg3"
12779   if ((Opc == BO_Or || Opc == BO_Xor) &&
12780       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12781     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12782     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12783   }
12784 
12785   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12786   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12787   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12788     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12789     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12790   }
12791 
12792   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12793       || Opc == BO_Shr) {
12794     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12795     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12796     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12797   }
12798 
12799   // Warn on overloaded shift operators and comparisons, such as:
12800   // cout << 5 == 4;
12801   if (BinaryOperator::isComparisonOp(Opc))
12802     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12803 }
12804 
12805 // Binary Operators.  'Tok' is the token for the operator.
12806 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12807                             tok::TokenKind Kind,
12808                             Expr *LHSExpr, Expr *RHSExpr) {
12809   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12810   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12811   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12812 
12813   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12814   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12815 
12816   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12817 }
12818 
12819 /// Build an overloaded binary operator expression in the given scope.
12820 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12821                                        BinaryOperatorKind Opc,
12822                                        Expr *LHS, Expr *RHS) {
12823   switch (Opc) {
12824   case BO_Assign:
12825   case BO_DivAssign:
12826   case BO_RemAssign:
12827   case BO_SubAssign:
12828   case BO_AndAssign:
12829   case BO_OrAssign:
12830   case BO_XorAssign:
12831     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12832     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12833     break;
12834   default:
12835     break;
12836   }
12837 
12838   // Find all of the overloaded operators visible from this
12839   // point. We perform both an operator-name lookup from the local
12840   // scope and an argument-dependent lookup based on the types of
12841   // the arguments.
12842   UnresolvedSet<16> Functions;
12843   OverloadedOperatorKind OverOp
12844     = BinaryOperator::getOverloadedOperator(Opc);
12845   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12846     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12847                                    RHS->getType(), Functions);
12848 
12849   // Build the (potentially-overloaded, potentially-dependent)
12850   // binary operation.
12851   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12852 }
12853 
12854 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12855                             BinaryOperatorKind Opc,
12856                             Expr *LHSExpr, Expr *RHSExpr) {
12857   ExprResult LHS, RHS;
12858   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12859   if (!LHS.isUsable() || !RHS.isUsable())
12860     return ExprError();
12861   LHSExpr = LHS.get();
12862   RHSExpr = RHS.get();
12863 
12864   // We want to end up calling one of checkPseudoObjectAssignment
12865   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12866   // both expressions are overloadable or either is type-dependent),
12867   // or CreateBuiltinBinOp (in any other case).  We also want to get
12868   // any placeholder types out of the way.
12869 
12870   // Handle pseudo-objects in the LHS.
12871   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12872     // Assignments with a pseudo-object l-value need special analysis.
12873     if (pty->getKind() == BuiltinType::PseudoObject &&
12874         BinaryOperator::isAssignmentOp(Opc))
12875       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12876 
12877     // Don't resolve overloads if the other type is overloadable.
12878     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12879       // We can't actually test that if we still have a placeholder,
12880       // though.  Fortunately, none of the exceptions we see in that
12881       // code below are valid when the LHS is an overload set.  Note
12882       // that an overload set can be dependently-typed, but it never
12883       // instantiates to having an overloadable type.
12884       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12885       if (resolvedRHS.isInvalid()) return ExprError();
12886       RHSExpr = resolvedRHS.get();
12887 
12888       if (RHSExpr->isTypeDependent() ||
12889           RHSExpr->getType()->isOverloadableType())
12890         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12891     }
12892 
12893     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12894     // template, diagnose the missing 'template' keyword instead of diagnosing
12895     // an invalid use of a bound member function.
12896     //
12897     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12898     // to C++1z [over.over]/1.4, but we already checked for that case above.
12899     if (Opc == BO_LT && inTemplateInstantiation() &&
12900         (pty->getKind() == BuiltinType::BoundMember ||
12901          pty->getKind() == BuiltinType::Overload)) {
12902       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12903       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12904           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12905             return isa<FunctionTemplateDecl>(ND);
12906           })) {
12907         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12908                                 : OE->getNameLoc(),
12909              diag::err_template_kw_missing)
12910           << OE->getName().getAsString() << "";
12911         return ExprError();
12912       }
12913     }
12914 
12915     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12916     if (LHS.isInvalid()) return ExprError();
12917     LHSExpr = LHS.get();
12918   }
12919 
12920   // Handle pseudo-objects in the RHS.
12921   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12922     // An overload in the RHS can potentially be resolved by the type
12923     // being assigned to.
12924     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12925       if (getLangOpts().CPlusPlus &&
12926           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12927            LHSExpr->getType()->isOverloadableType()))
12928         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12929 
12930       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12931     }
12932 
12933     // Don't resolve overloads if the other type is overloadable.
12934     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12935         LHSExpr->getType()->isOverloadableType())
12936       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12937 
12938     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12939     if (!resolvedRHS.isUsable()) return ExprError();
12940     RHSExpr = resolvedRHS.get();
12941   }
12942 
12943   if (getLangOpts().CPlusPlus) {
12944     // If either expression is type-dependent, always build an
12945     // overloaded op.
12946     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12947       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12948 
12949     // Otherwise, build an overloaded op if either expression has an
12950     // overloadable type.
12951     if (LHSExpr->getType()->isOverloadableType() ||
12952         RHSExpr->getType()->isOverloadableType())
12953       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12954   }
12955 
12956   // Build a built-in binary operation.
12957   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12958 }
12959 
12960 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12961   if (T.isNull() || T->isDependentType())
12962     return false;
12963 
12964   if (!T->isPromotableIntegerType())
12965     return true;
12966 
12967   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12968 }
12969 
12970 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12971                                       UnaryOperatorKind Opc,
12972                                       Expr *InputExpr) {
12973   ExprResult Input = InputExpr;
12974   ExprValueKind VK = VK_RValue;
12975   ExprObjectKind OK = OK_Ordinary;
12976   QualType resultType;
12977   bool CanOverflow = false;
12978 
12979   bool ConvertHalfVec = false;
12980   if (getLangOpts().OpenCL) {
12981     QualType Ty = InputExpr->getType();
12982     // The only legal unary operation for atomics is '&'.
12983     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12984     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12985     // only with a builtin functions and therefore should be disallowed here.
12986         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12987         || Ty->isBlockPointerType())) {
12988       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12989                        << InputExpr->getType()
12990                        << Input.get()->getSourceRange());
12991     }
12992   }
12993   switch (Opc) {
12994   case UO_PreInc:
12995   case UO_PreDec:
12996   case UO_PostInc:
12997   case UO_PostDec:
12998     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12999                                                 OpLoc,
13000                                                 Opc == UO_PreInc ||
13001                                                 Opc == UO_PostInc,
13002                                                 Opc == UO_PreInc ||
13003                                                 Opc == UO_PreDec);
13004     CanOverflow = isOverflowingIntegerType(Context, resultType);
13005     break;
13006   case UO_AddrOf:
13007     resultType = CheckAddressOfOperand(Input, OpLoc);
13008     CheckAddressOfNoDeref(InputExpr);
13009     RecordModifiableNonNullParam(*this, InputExpr);
13010     break;
13011   case UO_Deref: {
13012     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13013     if (Input.isInvalid()) return ExprError();
13014     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13015     break;
13016   }
13017   case UO_Plus:
13018   case UO_Minus:
13019     CanOverflow = Opc == UO_Minus &&
13020                   isOverflowingIntegerType(Context, Input.get()->getType());
13021     Input = UsualUnaryConversions(Input.get());
13022     if (Input.isInvalid()) return ExprError();
13023     // Unary plus and minus require promoting an operand of half vector to a
13024     // float vector and truncating the result back to a half vector. For now, we
13025     // do this only when HalfArgsAndReturns is set (that is, when the target is
13026     // arm or arm64).
13027     ConvertHalfVec =
13028         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13029 
13030     // If the operand is a half vector, promote it to a float vector.
13031     if (ConvertHalfVec)
13032       Input = convertVector(Input.get(), Context.FloatTy, *this);
13033     resultType = Input.get()->getType();
13034     if (resultType->isDependentType())
13035       break;
13036     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13037       break;
13038     else if (resultType->isVectorType() &&
13039              // The z vector extensions don't allow + or - with bool vectors.
13040              (!Context.getLangOpts().ZVector ||
13041               resultType->getAs<VectorType>()->getVectorKind() !=
13042               VectorType::AltiVecBool))
13043       break;
13044     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13045              Opc == UO_Plus &&
13046              resultType->isPointerType())
13047       break;
13048 
13049     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13050       << resultType << Input.get()->getSourceRange());
13051 
13052   case UO_Not: // bitwise complement
13053     Input = UsualUnaryConversions(Input.get());
13054     if (Input.isInvalid())
13055       return ExprError();
13056     resultType = Input.get()->getType();
13057 
13058     if (resultType->isDependentType())
13059       break;
13060     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13061     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13062       // C99 does not support '~' for complex conjugation.
13063       Diag(OpLoc, diag::ext_integer_complement_complex)
13064           << resultType << Input.get()->getSourceRange();
13065     else if (resultType->hasIntegerRepresentation())
13066       break;
13067     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13068       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13069       // on vector float types.
13070       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13071       if (!T->isIntegerType())
13072         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13073                           << resultType << Input.get()->getSourceRange());
13074     } else {
13075       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13076                        << resultType << Input.get()->getSourceRange());
13077     }
13078     break;
13079 
13080   case UO_LNot: // logical negation
13081     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13082     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13083     if (Input.isInvalid()) return ExprError();
13084     resultType = Input.get()->getType();
13085 
13086     // Though we still have to promote half FP to float...
13087     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13088       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13089       resultType = Context.FloatTy;
13090     }
13091 
13092     if (resultType->isDependentType())
13093       break;
13094     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13095       // C99 6.5.3.3p1: ok, fallthrough;
13096       if (Context.getLangOpts().CPlusPlus) {
13097         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13098         // operand contextually converted to bool.
13099         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13100                                   ScalarTypeToBooleanCastKind(resultType));
13101       } else if (Context.getLangOpts().OpenCL &&
13102                  Context.getLangOpts().OpenCLVersion < 120) {
13103         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13104         // operate on scalar float types.
13105         if (!resultType->isIntegerType() && !resultType->isPointerType())
13106           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13107                            << resultType << Input.get()->getSourceRange());
13108       }
13109     } else if (resultType->isExtVectorType()) {
13110       if (Context.getLangOpts().OpenCL &&
13111           Context.getLangOpts().OpenCLVersion < 120) {
13112         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13113         // operate on vector float types.
13114         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13115         if (!T->isIntegerType())
13116           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13117                            << resultType << Input.get()->getSourceRange());
13118       }
13119       // Vector logical not returns the signed variant of the operand type.
13120       resultType = GetSignedVectorType(resultType);
13121       break;
13122     } else {
13123       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13124       //        type in C++. We should allow that here too.
13125       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13126         << resultType << Input.get()->getSourceRange());
13127     }
13128 
13129     // LNot always has type int. C99 6.5.3.3p5.
13130     // In C++, it's bool. C++ 5.3.1p8
13131     resultType = Context.getLogicalOperationType();
13132     break;
13133   case UO_Real:
13134   case UO_Imag:
13135     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13136     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13137     // complex l-values to ordinary l-values and all other values to r-values.
13138     if (Input.isInvalid()) return ExprError();
13139     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13140       if (Input.get()->getValueKind() != VK_RValue &&
13141           Input.get()->getObjectKind() == OK_Ordinary)
13142         VK = Input.get()->getValueKind();
13143     } else if (!getLangOpts().CPlusPlus) {
13144       // In C, a volatile scalar is read by __imag. In C++, it is not.
13145       Input = DefaultLvalueConversion(Input.get());
13146     }
13147     break;
13148   case UO_Extension:
13149     resultType = Input.get()->getType();
13150     VK = Input.get()->getValueKind();
13151     OK = Input.get()->getObjectKind();
13152     break;
13153   case UO_Coawait:
13154     // It's unnecessary to represent the pass-through operator co_await in the
13155     // AST; just return the input expression instead.
13156     assert(!Input.get()->getType()->isDependentType() &&
13157                    "the co_await expression must be non-dependant before "
13158                    "building operator co_await");
13159     return Input;
13160   }
13161   if (resultType.isNull() || Input.isInvalid())
13162     return ExprError();
13163 
13164   // Check for array bounds violations in the operand of the UnaryOperator,
13165   // except for the '*' and '&' operators that have to be handled specially
13166   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13167   // that are explicitly defined as valid by the standard).
13168   if (Opc != UO_AddrOf && Opc != UO_Deref)
13169     CheckArrayAccess(Input.get());
13170 
13171   auto *UO = new (Context)
13172       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13173 
13174   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13175       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13176     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13177 
13178   // Convert the result back to a half vector.
13179   if (ConvertHalfVec)
13180     return convertVector(UO, Context.HalfTy, *this);
13181   return UO;
13182 }
13183 
13184 /// Determine whether the given expression is a qualified member
13185 /// access expression, of a form that could be turned into a pointer to member
13186 /// with the address-of operator.
13187 bool Sema::isQualifiedMemberAccess(Expr *E) {
13188   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13189     if (!DRE->getQualifier())
13190       return false;
13191 
13192     ValueDecl *VD = DRE->getDecl();
13193     if (!VD->isCXXClassMember())
13194       return false;
13195 
13196     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13197       return true;
13198     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13199       return Method->isInstance();
13200 
13201     return false;
13202   }
13203 
13204   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13205     if (!ULE->getQualifier())
13206       return false;
13207 
13208     for (NamedDecl *D : ULE->decls()) {
13209       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13210         if (Method->isInstance())
13211           return true;
13212       } else {
13213         // Overload set does not contain methods.
13214         break;
13215       }
13216     }
13217 
13218     return false;
13219   }
13220 
13221   return false;
13222 }
13223 
13224 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13225                               UnaryOperatorKind Opc, Expr *Input) {
13226   // First things first: handle placeholders so that the
13227   // overloaded-operator check considers the right type.
13228   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13229     // Increment and decrement of pseudo-object references.
13230     if (pty->getKind() == BuiltinType::PseudoObject &&
13231         UnaryOperator::isIncrementDecrementOp(Opc))
13232       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13233 
13234     // extension is always a builtin operator.
13235     if (Opc == UO_Extension)
13236       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13237 
13238     // & gets special logic for several kinds of placeholder.
13239     // The builtin code knows what to do.
13240     if (Opc == UO_AddrOf &&
13241         (pty->getKind() == BuiltinType::Overload ||
13242          pty->getKind() == BuiltinType::UnknownAny ||
13243          pty->getKind() == BuiltinType::BoundMember))
13244       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13245 
13246     // Anything else needs to be handled now.
13247     ExprResult Result = CheckPlaceholderExpr(Input);
13248     if (Result.isInvalid()) return ExprError();
13249     Input = Result.get();
13250   }
13251 
13252   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13253       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13254       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13255     // Find all of the overloaded operators visible from this
13256     // point. We perform both an operator-name lookup from the local
13257     // scope and an argument-dependent lookup based on the types of
13258     // the arguments.
13259     UnresolvedSet<16> Functions;
13260     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13261     if (S && OverOp != OO_None)
13262       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13263                                    Functions);
13264 
13265     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13266   }
13267 
13268   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13269 }
13270 
13271 // Unary Operators.  'Tok' is the token for the operator.
13272 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13273                               tok::TokenKind Op, Expr *Input) {
13274   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13275 }
13276 
13277 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13278 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13279                                 LabelDecl *TheDecl) {
13280   TheDecl->markUsed(Context);
13281   // Create the AST node.  The address of a label always has type 'void*'.
13282   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13283                                      Context.getPointerType(Context.VoidTy));
13284 }
13285 
13286 /// Given the last statement in a statement-expression, check whether
13287 /// the result is a producing expression (like a call to an
13288 /// ns_returns_retained function) and, if so, rebuild it to hoist the
13289 /// release out of the full-expression.  Otherwise, return null.
13290 /// Cannot fail.
13291 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
13292   // Should always be wrapped with one of these.
13293   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
13294   if (!cleanups) return nullptr;
13295 
13296   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
13297   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
13298     return nullptr;
13299 
13300   // Splice out the cast.  This shouldn't modify any interesting
13301   // features of the statement.
13302   Expr *producer = cast->getSubExpr();
13303   assert(producer->getType() == cast->getType());
13304   assert(producer->getValueKind() == cast->getValueKind());
13305   cleanups->setSubExpr(producer);
13306   return cleanups;
13307 }
13308 
13309 void Sema::ActOnStartStmtExpr() {
13310   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13311 }
13312 
13313 void Sema::ActOnStmtExprError() {
13314   // Note that function is also called by TreeTransform when leaving a
13315   // StmtExpr scope without rebuilding anything.
13316 
13317   DiscardCleanupsInEvaluationContext();
13318   PopExpressionEvaluationContext();
13319 }
13320 
13321 ExprResult
13322 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13323                     SourceLocation RPLoc) { // "({..})"
13324   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13325   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13326 
13327   if (hasAnyUnrecoverableErrorsInThisFunction())
13328     DiscardCleanupsInEvaluationContext();
13329   assert(!Cleanup.exprNeedsCleanups() &&
13330          "cleanups within StmtExpr not correctly bound!");
13331   PopExpressionEvaluationContext();
13332 
13333   // FIXME: there are a variety of strange constraints to enforce here, for
13334   // example, it is not possible to goto into a stmt expression apparently.
13335   // More semantic analysis is needed.
13336 
13337   // If there are sub-stmts in the compound stmt, take the type of the last one
13338   // as the type of the stmtexpr.
13339   QualType Ty = Context.VoidTy;
13340   bool StmtExprMayBindToTemp = false;
13341   if (!Compound->body_empty()) {
13342     Stmt *LastStmt = Compound->body_back();
13343     LabelStmt *LastLabelStmt = nullptr;
13344     // If LastStmt is a label, skip down through into the body.
13345     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
13346       LastLabelStmt = Label;
13347       LastStmt = Label->getSubStmt();
13348     }
13349 
13350     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
13351       // Do function/array conversion on the last expression, but not
13352       // lvalue-to-rvalue.  However, initialize an unqualified type.
13353       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
13354       if (LastExpr.isInvalid())
13355         return ExprError();
13356       Ty = LastExpr.get()->getType().getUnqualifiedType();
13357 
13358       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
13359         // In ARC, if the final expression ends in a consume, splice
13360         // the consume out and bind it later.  In the alternate case
13361         // (when dealing with a retainable type), the result
13362         // initialization will create a produce.  In both cases the
13363         // result will be +1, and we'll need to balance that out with
13364         // a bind.
13365         if (Expr *rebuiltLastStmt
13366               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
13367           LastExpr = rebuiltLastStmt;
13368         } else {
13369           LastExpr = PerformCopyInitialization(
13370               InitializedEntity::InitializeStmtExprResult(LPLoc, Ty),
13371               SourceLocation(), LastExpr);
13372         }
13373 
13374         if (LastExpr.isInvalid())
13375           return ExprError();
13376         if (LastExpr.get() != nullptr) {
13377           if (!LastLabelStmt)
13378             Compound->setLastStmt(LastExpr.get());
13379           else
13380             LastLabelStmt->setSubStmt(LastExpr.get());
13381           StmtExprMayBindToTemp = true;
13382         }
13383       }
13384     }
13385   }
13386 
13387   // FIXME: Check that expression type is complete/non-abstract; statement
13388   // expressions are not lvalues.
13389   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13390   if (StmtExprMayBindToTemp)
13391     return MaybeBindToTemporary(ResStmtExpr);
13392   return ResStmtExpr;
13393 }
13394 
13395 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13396                                       TypeSourceInfo *TInfo,
13397                                       ArrayRef<OffsetOfComponent> Components,
13398                                       SourceLocation RParenLoc) {
13399   QualType ArgTy = TInfo->getType();
13400   bool Dependent = ArgTy->isDependentType();
13401   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13402 
13403   // We must have at least one component that refers to the type, and the first
13404   // one is known to be a field designator.  Verify that the ArgTy represents
13405   // a struct/union/class.
13406   if (!Dependent && !ArgTy->isRecordType())
13407     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13408                        << ArgTy << TypeRange);
13409 
13410   // Type must be complete per C99 7.17p3 because a declaring a variable
13411   // with an incomplete type would be ill-formed.
13412   if (!Dependent
13413       && RequireCompleteType(BuiltinLoc, ArgTy,
13414                              diag::err_offsetof_incomplete_type, TypeRange))
13415     return ExprError();
13416 
13417   bool DidWarnAboutNonPOD = false;
13418   QualType CurrentType = ArgTy;
13419   SmallVector<OffsetOfNode, 4> Comps;
13420   SmallVector<Expr*, 4> Exprs;
13421   for (const OffsetOfComponent &OC : Components) {
13422     if (OC.isBrackets) {
13423       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13424       if (!CurrentType->isDependentType()) {
13425         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13426         if(!AT)
13427           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13428                            << CurrentType);
13429         CurrentType = AT->getElementType();
13430       } else
13431         CurrentType = Context.DependentTy;
13432 
13433       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13434       if (IdxRval.isInvalid())
13435         return ExprError();
13436       Expr *Idx = IdxRval.get();
13437 
13438       // The expression must be an integral expression.
13439       // FIXME: An integral constant expression?
13440       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13441           !Idx->getType()->isIntegerType())
13442         return ExprError(
13443             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13444             << Idx->getSourceRange());
13445 
13446       // Record this array index.
13447       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13448       Exprs.push_back(Idx);
13449       continue;
13450     }
13451 
13452     // Offset of a field.
13453     if (CurrentType->isDependentType()) {
13454       // We have the offset of a field, but we can't look into the dependent
13455       // type. Just record the identifier of the field.
13456       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13457       CurrentType = Context.DependentTy;
13458       continue;
13459     }
13460 
13461     // We need to have a complete type to look into.
13462     if (RequireCompleteType(OC.LocStart, CurrentType,
13463                             diag::err_offsetof_incomplete_type))
13464       return ExprError();
13465 
13466     // Look for the designated field.
13467     const RecordType *RC = CurrentType->getAs<RecordType>();
13468     if (!RC)
13469       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13470                        << CurrentType);
13471     RecordDecl *RD = RC->getDecl();
13472 
13473     // C++ [lib.support.types]p5:
13474     //   The macro offsetof accepts a restricted set of type arguments in this
13475     //   International Standard. type shall be a POD structure or a POD union
13476     //   (clause 9).
13477     // C++11 [support.types]p4:
13478     //   If type is not a standard-layout class (Clause 9), the results are
13479     //   undefined.
13480     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13481       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13482       unsigned DiagID =
13483         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13484                             : diag::ext_offsetof_non_pod_type;
13485 
13486       if (!IsSafe && !DidWarnAboutNonPOD &&
13487           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13488                               PDiag(DiagID)
13489                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13490                               << CurrentType))
13491         DidWarnAboutNonPOD = true;
13492     }
13493 
13494     // Look for the field.
13495     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13496     LookupQualifiedName(R, RD);
13497     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13498     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13499     if (!MemberDecl) {
13500       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13501         MemberDecl = IndirectMemberDecl->getAnonField();
13502     }
13503 
13504     if (!MemberDecl)
13505       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13506                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13507                                                               OC.LocEnd));
13508 
13509     // C99 7.17p3:
13510     //   (If the specified member is a bit-field, the behavior is undefined.)
13511     //
13512     // We diagnose this as an error.
13513     if (MemberDecl->isBitField()) {
13514       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13515         << MemberDecl->getDeclName()
13516         << SourceRange(BuiltinLoc, RParenLoc);
13517       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13518       return ExprError();
13519     }
13520 
13521     RecordDecl *Parent = MemberDecl->getParent();
13522     if (IndirectMemberDecl)
13523       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13524 
13525     // If the member was found in a base class, introduce OffsetOfNodes for
13526     // the base class indirections.
13527     CXXBasePaths Paths;
13528     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13529                       Paths)) {
13530       if (Paths.getDetectedVirtual()) {
13531         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13532           << MemberDecl->getDeclName()
13533           << SourceRange(BuiltinLoc, RParenLoc);
13534         return ExprError();
13535       }
13536 
13537       CXXBasePath &Path = Paths.front();
13538       for (const CXXBasePathElement &B : Path)
13539         Comps.push_back(OffsetOfNode(B.Base));
13540     }
13541 
13542     if (IndirectMemberDecl) {
13543       for (auto *FI : IndirectMemberDecl->chain()) {
13544         assert(isa<FieldDecl>(FI));
13545         Comps.push_back(OffsetOfNode(OC.LocStart,
13546                                      cast<FieldDecl>(FI), OC.LocEnd));
13547       }
13548     } else
13549       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13550 
13551     CurrentType = MemberDecl->getType().getNonReferenceType();
13552   }
13553 
13554   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13555                               Comps, Exprs, RParenLoc);
13556 }
13557 
13558 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13559                                       SourceLocation BuiltinLoc,
13560                                       SourceLocation TypeLoc,
13561                                       ParsedType ParsedArgTy,
13562                                       ArrayRef<OffsetOfComponent> Components,
13563                                       SourceLocation RParenLoc) {
13564 
13565   TypeSourceInfo *ArgTInfo;
13566   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13567   if (ArgTy.isNull())
13568     return ExprError();
13569 
13570   if (!ArgTInfo)
13571     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13572 
13573   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13574 }
13575 
13576 
13577 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13578                                  Expr *CondExpr,
13579                                  Expr *LHSExpr, Expr *RHSExpr,
13580                                  SourceLocation RPLoc) {
13581   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13582 
13583   ExprValueKind VK = VK_RValue;
13584   ExprObjectKind OK = OK_Ordinary;
13585   QualType resType;
13586   bool ValueDependent = false;
13587   bool CondIsTrue = false;
13588   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13589     resType = Context.DependentTy;
13590     ValueDependent = true;
13591   } else {
13592     // The conditional expression is required to be a constant expression.
13593     llvm::APSInt condEval(32);
13594     ExprResult CondICE
13595       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13596           diag::err_typecheck_choose_expr_requires_constant, false);
13597     if (CondICE.isInvalid())
13598       return ExprError();
13599     CondExpr = CondICE.get();
13600     CondIsTrue = condEval.getZExtValue();
13601 
13602     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13603     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13604 
13605     resType = ActiveExpr->getType();
13606     ValueDependent = ActiveExpr->isValueDependent();
13607     VK = ActiveExpr->getValueKind();
13608     OK = ActiveExpr->getObjectKind();
13609   }
13610 
13611   return new (Context)
13612       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13613                  CondIsTrue, resType->isDependentType(), ValueDependent);
13614 }
13615 
13616 //===----------------------------------------------------------------------===//
13617 // Clang Extensions.
13618 //===----------------------------------------------------------------------===//
13619 
13620 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13621 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13622   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13623 
13624   if (LangOpts.CPlusPlus) {
13625     Decl *ManglingContextDecl;
13626     if (MangleNumberingContext *MCtx =
13627             getCurrentMangleNumberContext(Block->getDeclContext(),
13628                                           ManglingContextDecl)) {
13629       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13630       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13631     }
13632   }
13633 
13634   PushBlockScope(CurScope, Block);
13635   CurContext->addDecl(Block);
13636   if (CurScope)
13637     PushDeclContext(CurScope, Block);
13638   else
13639     CurContext = Block;
13640 
13641   getCurBlock()->HasImplicitReturnType = true;
13642 
13643   // Enter a new evaluation context to insulate the block from any
13644   // cleanups from the enclosing full-expression.
13645   PushExpressionEvaluationContext(
13646       ExpressionEvaluationContext::PotentiallyEvaluated);
13647 }
13648 
13649 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13650                                Scope *CurScope) {
13651   assert(ParamInfo.getIdentifier() == nullptr &&
13652          "block-id should have no identifier!");
13653   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13654   BlockScopeInfo *CurBlock = getCurBlock();
13655 
13656   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13657   QualType T = Sig->getType();
13658 
13659   // FIXME: We should allow unexpanded parameter packs here, but that would,
13660   // in turn, make the block expression contain unexpanded parameter packs.
13661   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13662     // Drop the parameters.
13663     FunctionProtoType::ExtProtoInfo EPI;
13664     EPI.HasTrailingReturn = false;
13665     EPI.TypeQuals.addConst();
13666     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13667     Sig = Context.getTrivialTypeSourceInfo(T);
13668   }
13669 
13670   // GetTypeForDeclarator always produces a function type for a block
13671   // literal signature.  Furthermore, it is always a FunctionProtoType
13672   // unless the function was written with a typedef.
13673   assert(T->isFunctionType() &&
13674          "GetTypeForDeclarator made a non-function block signature");
13675 
13676   // Look for an explicit signature in that function type.
13677   FunctionProtoTypeLoc ExplicitSignature;
13678 
13679   if ((ExplicitSignature =
13680            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13681 
13682     // Check whether that explicit signature was synthesized by
13683     // GetTypeForDeclarator.  If so, don't save that as part of the
13684     // written signature.
13685     if (ExplicitSignature.getLocalRangeBegin() ==
13686         ExplicitSignature.getLocalRangeEnd()) {
13687       // This would be much cheaper if we stored TypeLocs instead of
13688       // TypeSourceInfos.
13689       TypeLoc Result = ExplicitSignature.getReturnLoc();
13690       unsigned Size = Result.getFullDataSize();
13691       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13692       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13693 
13694       ExplicitSignature = FunctionProtoTypeLoc();
13695     }
13696   }
13697 
13698   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13699   CurBlock->FunctionType = T;
13700 
13701   const FunctionType *Fn = T->getAs<FunctionType>();
13702   QualType RetTy = Fn->getReturnType();
13703   bool isVariadic =
13704     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13705 
13706   CurBlock->TheDecl->setIsVariadic(isVariadic);
13707 
13708   // Context.DependentTy is used as a placeholder for a missing block
13709   // return type.  TODO:  what should we do with declarators like:
13710   //   ^ * { ... }
13711   // If the answer is "apply template argument deduction"....
13712   if (RetTy != Context.DependentTy) {
13713     CurBlock->ReturnType = RetTy;
13714     CurBlock->TheDecl->setBlockMissingReturnType(false);
13715     CurBlock->HasImplicitReturnType = false;
13716   }
13717 
13718   // Push block parameters from the declarator if we had them.
13719   SmallVector<ParmVarDecl*, 8> Params;
13720   if (ExplicitSignature) {
13721     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13722       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13723       if (Param->getIdentifier() == nullptr &&
13724           !Param->isImplicit() &&
13725           !Param->isInvalidDecl() &&
13726           !getLangOpts().CPlusPlus)
13727         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13728       Params.push_back(Param);
13729     }
13730 
13731   // Fake up parameter variables if we have a typedef, like
13732   //   ^ fntype { ... }
13733   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13734     for (const auto &I : Fn->param_types()) {
13735       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13736           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13737       Params.push_back(Param);
13738     }
13739   }
13740 
13741   // Set the parameters on the block decl.
13742   if (!Params.empty()) {
13743     CurBlock->TheDecl->setParams(Params);
13744     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13745                              /*CheckParameterNames=*/false);
13746   }
13747 
13748   // Finally we can process decl attributes.
13749   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13750 
13751   // Put the parameter variables in scope.
13752   for (auto AI : CurBlock->TheDecl->parameters()) {
13753     AI->setOwningFunction(CurBlock->TheDecl);
13754 
13755     // If this has an identifier, add it to the scope stack.
13756     if (AI->getIdentifier()) {
13757       CheckShadow(CurBlock->TheScope, AI);
13758 
13759       PushOnScopeChains(AI, CurBlock->TheScope);
13760     }
13761   }
13762 }
13763 
13764 /// ActOnBlockError - If there is an error parsing a block, this callback
13765 /// is invoked to pop the information about the block from the action impl.
13766 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13767   // Leave the expression-evaluation context.
13768   DiscardCleanupsInEvaluationContext();
13769   PopExpressionEvaluationContext();
13770 
13771   // Pop off CurBlock, handle nested blocks.
13772   PopDeclContext();
13773   PopFunctionScopeInfo();
13774 }
13775 
13776 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13777 /// literal was successfully completed.  ^(int x){...}
13778 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13779                                     Stmt *Body, Scope *CurScope) {
13780   // If blocks are disabled, emit an error.
13781   if (!LangOpts.Blocks)
13782     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13783 
13784   // Leave the expression-evaluation context.
13785   if (hasAnyUnrecoverableErrorsInThisFunction())
13786     DiscardCleanupsInEvaluationContext();
13787   assert(!Cleanup.exprNeedsCleanups() &&
13788          "cleanups within block not correctly bound!");
13789   PopExpressionEvaluationContext();
13790 
13791   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13792   BlockDecl *BD = BSI->TheDecl;
13793 
13794   if (BSI->HasImplicitReturnType)
13795     deduceClosureReturnType(*BSI);
13796 
13797   PopDeclContext();
13798 
13799   QualType RetTy = Context.VoidTy;
13800   if (!BSI->ReturnType.isNull())
13801     RetTy = BSI->ReturnType;
13802 
13803   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13804   QualType BlockTy;
13805 
13806   // Set the captured variables on the block.
13807   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13808   SmallVector<BlockDecl::Capture, 4> Captures;
13809   for (Capture &Cap : BSI->Captures) {
13810     if (Cap.isThisCapture())
13811       continue;
13812     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13813                               Cap.isNested(), Cap.getInitExpr());
13814     Captures.push_back(NewCap);
13815   }
13816   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13817 
13818   // If the user wrote a function type in some form, try to use that.
13819   if (!BSI->FunctionType.isNull()) {
13820     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13821 
13822     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13823     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13824 
13825     // Turn protoless block types into nullary block types.
13826     if (isa<FunctionNoProtoType>(FTy)) {
13827       FunctionProtoType::ExtProtoInfo EPI;
13828       EPI.ExtInfo = Ext;
13829       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13830 
13831     // Otherwise, if we don't need to change anything about the function type,
13832     // preserve its sugar structure.
13833     } else if (FTy->getReturnType() == RetTy &&
13834                (!NoReturn || FTy->getNoReturnAttr())) {
13835       BlockTy = BSI->FunctionType;
13836 
13837     // Otherwise, make the minimal modifications to the function type.
13838     } else {
13839       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13840       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13841       EPI.TypeQuals = Qualifiers();
13842       EPI.ExtInfo = Ext;
13843       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13844     }
13845 
13846   // If we don't have a function type, just build one from nothing.
13847   } else {
13848     FunctionProtoType::ExtProtoInfo EPI;
13849     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13850     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13851   }
13852 
13853   DiagnoseUnusedParameters(BD->parameters());
13854   BlockTy = Context.getBlockPointerType(BlockTy);
13855 
13856   // If needed, diagnose invalid gotos and switches in the block.
13857   if (getCurFunction()->NeedsScopeChecking() &&
13858       !PP.isCodeCompletionEnabled())
13859     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13860 
13861   BD->setBody(cast<CompoundStmt>(Body));
13862 
13863   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13864     DiagnoseUnguardedAvailabilityViolations(BD);
13865 
13866   // Try to apply the named return value optimization. We have to check again
13867   // if we can do this, though, because blocks keep return statements around
13868   // to deduce an implicit return type.
13869   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13870       !BD->isDependentContext())
13871     computeNRVO(Body, BSI);
13872 
13873   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13874   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13875   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13876 
13877   // If the block isn't obviously global, i.e. it captures anything at
13878   // all, then we need to do a few things in the surrounding context:
13879   if (Result->getBlockDecl()->hasCaptures()) {
13880     // First, this expression has a new cleanup object.
13881     ExprCleanupObjects.push_back(Result->getBlockDecl());
13882     Cleanup.setExprNeedsCleanups(true);
13883 
13884     // It also gets a branch-protected scope if any of the captured
13885     // variables needs destruction.
13886     for (const auto &CI : Result->getBlockDecl()->captures()) {
13887       const VarDecl *var = CI.getVariable();
13888       if (var->getType().isDestructedType() != QualType::DK_none) {
13889         setFunctionHasBranchProtectedScope();
13890         break;
13891       }
13892     }
13893   }
13894 
13895   if (getCurFunction())
13896     getCurFunction()->addBlock(BD);
13897 
13898   return Result;
13899 }
13900 
13901 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13902                             SourceLocation RPLoc) {
13903   TypeSourceInfo *TInfo;
13904   GetTypeFromParser(Ty, &TInfo);
13905   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13906 }
13907 
13908 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13909                                 Expr *E, TypeSourceInfo *TInfo,
13910                                 SourceLocation RPLoc) {
13911   Expr *OrigExpr = E;
13912   bool IsMS = false;
13913 
13914   // CUDA device code does not support varargs.
13915   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13916     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13917       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13918       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13919         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13920     }
13921   }
13922 
13923   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13924   // as Microsoft ABI on an actual Microsoft platform, where
13925   // __builtin_ms_va_list and __builtin_va_list are the same.)
13926   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13927       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13928     QualType MSVaListType = Context.getBuiltinMSVaListType();
13929     if (Context.hasSameType(MSVaListType, E->getType())) {
13930       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13931         return ExprError();
13932       IsMS = true;
13933     }
13934   }
13935 
13936   // Get the va_list type
13937   QualType VaListType = Context.getBuiltinVaListType();
13938   if (!IsMS) {
13939     if (VaListType->isArrayType()) {
13940       // Deal with implicit array decay; for example, on x86-64,
13941       // va_list is an array, but it's supposed to decay to
13942       // a pointer for va_arg.
13943       VaListType = Context.getArrayDecayedType(VaListType);
13944       // Make sure the input expression also decays appropriately.
13945       ExprResult Result = UsualUnaryConversions(E);
13946       if (Result.isInvalid())
13947         return ExprError();
13948       E = Result.get();
13949     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13950       // If va_list is a record type and we are compiling in C++ mode,
13951       // check the argument using reference binding.
13952       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13953           Context, Context.getLValueReferenceType(VaListType), false);
13954       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13955       if (Init.isInvalid())
13956         return ExprError();
13957       E = Init.getAs<Expr>();
13958     } else {
13959       // Otherwise, the va_list argument must be an l-value because
13960       // it is modified by va_arg.
13961       if (!E->isTypeDependent() &&
13962           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13963         return ExprError();
13964     }
13965   }
13966 
13967   if (!IsMS && !E->isTypeDependent() &&
13968       !Context.hasSameType(VaListType, E->getType()))
13969     return ExprError(
13970         Diag(E->getBeginLoc(),
13971              diag::err_first_argument_to_va_arg_not_of_type_va_list)
13972         << OrigExpr->getType() << E->getSourceRange());
13973 
13974   if (!TInfo->getType()->isDependentType()) {
13975     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13976                             diag::err_second_parameter_to_va_arg_incomplete,
13977                             TInfo->getTypeLoc()))
13978       return ExprError();
13979 
13980     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13981                                TInfo->getType(),
13982                                diag::err_second_parameter_to_va_arg_abstract,
13983                                TInfo->getTypeLoc()))
13984       return ExprError();
13985 
13986     if (!TInfo->getType().isPODType(Context)) {
13987       Diag(TInfo->getTypeLoc().getBeginLoc(),
13988            TInfo->getType()->isObjCLifetimeType()
13989              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13990              : diag::warn_second_parameter_to_va_arg_not_pod)
13991         << TInfo->getType()
13992         << TInfo->getTypeLoc().getSourceRange();
13993     }
13994 
13995     // Check for va_arg where arguments of the given type will be promoted
13996     // (i.e. this va_arg is guaranteed to have undefined behavior).
13997     QualType PromoteType;
13998     if (TInfo->getType()->isPromotableIntegerType()) {
13999       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14000       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14001         PromoteType = QualType();
14002     }
14003     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14004       PromoteType = Context.DoubleTy;
14005     if (!PromoteType.isNull())
14006       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14007                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14008                           << TInfo->getType()
14009                           << PromoteType
14010                           << TInfo->getTypeLoc().getSourceRange());
14011   }
14012 
14013   QualType T = TInfo->getType().getNonLValueExprType(Context);
14014   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14015 }
14016 
14017 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14018   // The type of __null will be int or long, depending on the size of
14019   // pointers on the target.
14020   QualType Ty;
14021   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14022   if (pw == Context.getTargetInfo().getIntWidth())
14023     Ty = Context.IntTy;
14024   else if (pw == Context.getTargetInfo().getLongWidth())
14025     Ty = Context.LongTy;
14026   else if (pw == Context.getTargetInfo().getLongLongWidth())
14027     Ty = Context.LongLongTy;
14028   else {
14029     llvm_unreachable("I don't know size of pointer!");
14030   }
14031 
14032   return new (Context) GNUNullExpr(Ty, TokenLoc);
14033 }
14034 
14035 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14036                                               bool Diagnose) {
14037   if (!getLangOpts().ObjC)
14038     return false;
14039 
14040   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14041   if (!PT)
14042     return false;
14043 
14044   if (!PT->isObjCIdType()) {
14045     // Check if the destination is the 'NSString' interface.
14046     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14047     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14048       return false;
14049   }
14050 
14051   // Ignore any parens, implicit casts (should only be
14052   // array-to-pointer decays), and not-so-opaque values.  The last is
14053   // important for making this trigger for property assignments.
14054   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14055   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14056     if (OV->getSourceExpr())
14057       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14058 
14059   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14060   if (!SL || !SL->isAscii())
14061     return false;
14062   if (Diagnose) {
14063     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14064         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14065     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14066   }
14067   return true;
14068 }
14069 
14070 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14071                                               const Expr *SrcExpr) {
14072   if (!DstType->isFunctionPointerType() ||
14073       !SrcExpr->getType()->isFunctionType())
14074     return false;
14075 
14076   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14077   if (!DRE)
14078     return false;
14079 
14080   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14081   if (!FD)
14082     return false;
14083 
14084   return !S.checkAddressOfFunctionIsAvailable(FD,
14085                                               /*Complain=*/true,
14086                                               SrcExpr->getBeginLoc());
14087 }
14088 
14089 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14090                                     SourceLocation Loc,
14091                                     QualType DstType, QualType SrcType,
14092                                     Expr *SrcExpr, AssignmentAction Action,
14093                                     bool *Complained) {
14094   if (Complained)
14095     *Complained = false;
14096 
14097   // Decode the result (notice that AST's are still created for extensions).
14098   bool CheckInferredResultType = false;
14099   bool isInvalid = false;
14100   unsigned DiagKind = 0;
14101   FixItHint Hint;
14102   ConversionFixItGenerator ConvHints;
14103   bool MayHaveConvFixit = false;
14104   bool MayHaveFunctionDiff = false;
14105   const ObjCInterfaceDecl *IFace = nullptr;
14106   const ObjCProtocolDecl *PDecl = nullptr;
14107 
14108   switch (ConvTy) {
14109   case Compatible:
14110       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14111       return false;
14112 
14113   case PointerToInt:
14114     DiagKind = diag::ext_typecheck_convert_pointer_int;
14115     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14116     MayHaveConvFixit = true;
14117     break;
14118   case IntToPointer:
14119     DiagKind = diag::ext_typecheck_convert_int_pointer;
14120     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14121     MayHaveConvFixit = true;
14122     break;
14123   case IncompatiblePointer:
14124     if (Action == AA_Passing_CFAudited)
14125       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14126     else if (SrcType->isFunctionPointerType() &&
14127              DstType->isFunctionPointerType())
14128       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14129     else
14130       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14131 
14132     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14133       SrcType->isObjCObjectPointerType();
14134     if (Hint.isNull() && !CheckInferredResultType) {
14135       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14136     }
14137     else if (CheckInferredResultType) {
14138       SrcType = SrcType.getUnqualifiedType();
14139       DstType = DstType.getUnqualifiedType();
14140     }
14141     MayHaveConvFixit = true;
14142     break;
14143   case IncompatiblePointerSign:
14144     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14145     break;
14146   case FunctionVoidPointer:
14147     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14148     break;
14149   case IncompatiblePointerDiscardsQualifiers: {
14150     // Perform array-to-pointer decay if necessary.
14151     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14152 
14153     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14154     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14155     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14156       DiagKind = diag::err_typecheck_incompatible_address_space;
14157       break;
14158 
14159     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14160       DiagKind = diag::err_typecheck_incompatible_ownership;
14161       break;
14162     }
14163 
14164     llvm_unreachable("unknown error case for discarding qualifiers!");
14165     // fallthrough
14166   }
14167   case CompatiblePointerDiscardsQualifiers:
14168     // If the qualifiers lost were because we were applying the
14169     // (deprecated) C++ conversion from a string literal to a char*
14170     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14171     // Ideally, this check would be performed in
14172     // checkPointerTypesForAssignment. However, that would require a
14173     // bit of refactoring (so that the second argument is an
14174     // expression, rather than a type), which should be done as part
14175     // of a larger effort to fix checkPointerTypesForAssignment for
14176     // C++ semantics.
14177     if (getLangOpts().CPlusPlus &&
14178         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14179       return false;
14180     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14181     break;
14182   case IncompatibleNestedPointerQualifiers:
14183     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14184     break;
14185   case IntToBlockPointer:
14186     DiagKind = diag::err_int_to_block_pointer;
14187     break;
14188   case IncompatibleBlockPointer:
14189     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14190     break;
14191   case IncompatibleObjCQualifiedId: {
14192     if (SrcType->isObjCQualifiedIdType()) {
14193       const ObjCObjectPointerType *srcOPT =
14194                 SrcType->getAs<ObjCObjectPointerType>();
14195       for (auto *srcProto : srcOPT->quals()) {
14196         PDecl = srcProto;
14197         break;
14198       }
14199       if (const ObjCInterfaceType *IFaceT =
14200             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14201         IFace = IFaceT->getDecl();
14202     }
14203     else if (DstType->isObjCQualifiedIdType()) {
14204       const ObjCObjectPointerType *dstOPT =
14205         DstType->getAs<ObjCObjectPointerType>();
14206       for (auto *dstProto : dstOPT->quals()) {
14207         PDecl = dstProto;
14208         break;
14209       }
14210       if (const ObjCInterfaceType *IFaceT =
14211             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14212         IFace = IFaceT->getDecl();
14213     }
14214     DiagKind = diag::warn_incompatible_qualified_id;
14215     break;
14216   }
14217   case IncompatibleVectors:
14218     DiagKind = diag::warn_incompatible_vectors;
14219     break;
14220   case IncompatibleObjCWeakRef:
14221     DiagKind = diag::err_arc_weak_unavailable_assign;
14222     break;
14223   case Incompatible:
14224     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14225       if (Complained)
14226         *Complained = true;
14227       return true;
14228     }
14229 
14230     DiagKind = diag::err_typecheck_convert_incompatible;
14231     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14232     MayHaveConvFixit = true;
14233     isInvalid = true;
14234     MayHaveFunctionDiff = true;
14235     break;
14236   }
14237 
14238   QualType FirstType, SecondType;
14239   switch (Action) {
14240   case AA_Assigning:
14241   case AA_Initializing:
14242     // The destination type comes first.
14243     FirstType = DstType;
14244     SecondType = SrcType;
14245     break;
14246 
14247   case AA_Returning:
14248   case AA_Passing:
14249   case AA_Passing_CFAudited:
14250   case AA_Converting:
14251   case AA_Sending:
14252   case AA_Casting:
14253     // The source type comes first.
14254     FirstType = SrcType;
14255     SecondType = DstType;
14256     break;
14257   }
14258 
14259   PartialDiagnostic FDiag = PDiag(DiagKind);
14260   if (Action == AA_Passing_CFAudited)
14261     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14262   else
14263     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14264 
14265   // If we can fix the conversion, suggest the FixIts.
14266   assert(ConvHints.isNull() || Hint.isNull());
14267   if (!ConvHints.isNull()) {
14268     for (FixItHint &H : ConvHints.Hints)
14269       FDiag << H;
14270   } else {
14271     FDiag << Hint;
14272   }
14273   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14274 
14275   if (MayHaveFunctionDiff)
14276     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14277 
14278   Diag(Loc, FDiag);
14279   if (DiagKind == diag::warn_incompatible_qualified_id &&
14280       PDecl && IFace && !IFace->hasDefinition())
14281       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14282         << IFace << PDecl;
14283 
14284   if (SecondType == Context.OverloadTy)
14285     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14286                               FirstType, /*TakingAddress=*/true);
14287 
14288   if (CheckInferredResultType)
14289     EmitRelatedResultTypeNote(SrcExpr);
14290 
14291   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14292     EmitRelatedResultTypeNoteForReturn(DstType);
14293 
14294   if (Complained)
14295     *Complained = true;
14296   return isInvalid;
14297 }
14298 
14299 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14300                                                  llvm::APSInt *Result) {
14301   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14302   public:
14303     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14304       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14305     }
14306   } Diagnoser;
14307 
14308   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14309 }
14310 
14311 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14312                                                  llvm::APSInt *Result,
14313                                                  unsigned DiagID,
14314                                                  bool AllowFold) {
14315   class IDDiagnoser : public VerifyICEDiagnoser {
14316     unsigned DiagID;
14317 
14318   public:
14319     IDDiagnoser(unsigned DiagID)
14320       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14321 
14322     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14323       S.Diag(Loc, DiagID) << SR;
14324     }
14325   } Diagnoser(DiagID);
14326 
14327   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14328 }
14329 
14330 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14331                                             SourceRange SR) {
14332   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14333 }
14334 
14335 ExprResult
14336 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14337                                       VerifyICEDiagnoser &Diagnoser,
14338                                       bool AllowFold) {
14339   SourceLocation DiagLoc = E->getBeginLoc();
14340 
14341   if (getLangOpts().CPlusPlus11) {
14342     // C++11 [expr.const]p5:
14343     //   If an expression of literal class type is used in a context where an
14344     //   integral constant expression is required, then that class type shall
14345     //   have a single non-explicit conversion function to an integral or
14346     //   unscoped enumeration type
14347     ExprResult Converted;
14348     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14349     public:
14350       CXX11ConvertDiagnoser(bool Silent)
14351           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14352                                 Silent, true) {}
14353 
14354       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14355                                            QualType T) override {
14356         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14357       }
14358 
14359       SemaDiagnosticBuilder diagnoseIncomplete(
14360           Sema &S, SourceLocation Loc, QualType T) override {
14361         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14362       }
14363 
14364       SemaDiagnosticBuilder diagnoseExplicitConv(
14365           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14366         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14367       }
14368 
14369       SemaDiagnosticBuilder noteExplicitConv(
14370           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14371         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14372                  << ConvTy->isEnumeralType() << ConvTy;
14373       }
14374 
14375       SemaDiagnosticBuilder diagnoseAmbiguous(
14376           Sema &S, SourceLocation Loc, QualType T) override {
14377         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14378       }
14379 
14380       SemaDiagnosticBuilder noteAmbiguous(
14381           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14382         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14383                  << ConvTy->isEnumeralType() << ConvTy;
14384       }
14385 
14386       SemaDiagnosticBuilder diagnoseConversion(
14387           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14388         llvm_unreachable("conversion functions are permitted");
14389       }
14390     } ConvertDiagnoser(Diagnoser.Suppress);
14391 
14392     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14393                                                     ConvertDiagnoser);
14394     if (Converted.isInvalid())
14395       return Converted;
14396     E = Converted.get();
14397     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14398       return ExprError();
14399   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14400     // An ICE must be of integral or unscoped enumeration type.
14401     if (!Diagnoser.Suppress)
14402       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14403     return ExprError();
14404   }
14405 
14406   if (!isa<ConstantExpr>(E))
14407     E = ConstantExpr::Create(Context, E);
14408 
14409   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14410   // in the non-ICE case.
14411   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14412     if (Result)
14413       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14414     return E;
14415   }
14416 
14417   Expr::EvalResult EvalResult;
14418   SmallVector<PartialDiagnosticAt, 8> Notes;
14419   EvalResult.Diag = &Notes;
14420 
14421   // Try to evaluate the expression, and produce diagnostics explaining why it's
14422   // not a constant expression as a side-effect.
14423   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14424                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14425 
14426   // In C++11, we can rely on diagnostics being produced for any expression
14427   // which is not a constant expression. If no diagnostics were produced, then
14428   // this is a constant expression.
14429   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14430     if (Result)
14431       *Result = EvalResult.Val.getInt();
14432     return E;
14433   }
14434 
14435   // If our only note is the usual "invalid subexpression" note, just point
14436   // the caret at its location rather than producing an essentially
14437   // redundant note.
14438   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14439         diag::note_invalid_subexpr_in_const_expr) {
14440     DiagLoc = Notes[0].first;
14441     Notes.clear();
14442   }
14443 
14444   if (!Folded || !AllowFold) {
14445     if (!Diagnoser.Suppress) {
14446       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14447       for (const PartialDiagnosticAt &Note : Notes)
14448         Diag(Note.first, Note.second);
14449     }
14450 
14451     return ExprError();
14452   }
14453 
14454   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14455   for (const PartialDiagnosticAt &Note : Notes)
14456     Diag(Note.first, Note.second);
14457 
14458   if (Result)
14459     *Result = EvalResult.Val.getInt();
14460   return E;
14461 }
14462 
14463 namespace {
14464   // Handle the case where we conclude a expression which we speculatively
14465   // considered to be unevaluated is actually evaluated.
14466   class TransformToPE : public TreeTransform<TransformToPE> {
14467     typedef TreeTransform<TransformToPE> BaseTransform;
14468 
14469   public:
14470     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14471 
14472     // Make sure we redo semantic analysis
14473     bool AlwaysRebuild() { return true; }
14474 
14475     // Make sure we handle LabelStmts correctly.
14476     // FIXME: This does the right thing, but maybe we need a more general
14477     // fix to TreeTransform?
14478     StmtResult TransformLabelStmt(LabelStmt *S) {
14479       S->getDecl()->setStmt(nullptr);
14480       return BaseTransform::TransformLabelStmt(S);
14481     }
14482 
14483     // We need to special-case DeclRefExprs referring to FieldDecls which
14484     // are not part of a member pointer formation; normal TreeTransforming
14485     // doesn't catch this case because of the way we represent them in the AST.
14486     // FIXME: This is a bit ugly; is it really the best way to handle this
14487     // case?
14488     //
14489     // Error on DeclRefExprs referring to FieldDecls.
14490     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14491       if (isa<FieldDecl>(E->getDecl()) &&
14492           !SemaRef.isUnevaluatedContext())
14493         return SemaRef.Diag(E->getLocation(),
14494                             diag::err_invalid_non_static_member_use)
14495             << E->getDecl() << E->getSourceRange();
14496 
14497       return BaseTransform::TransformDeclRefExpr(E);
14498     }
14499 
14500     // Exception: filter out member pointer formation
14501     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14502       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14503         return E;
14504 
14505       return BaseTransform::TransformUnaryOperator(E);
14506     }
14507 
14508     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14509       // Lambdas never need to be transformed.
14510       return E;
14511     }
14512   };
14513 }
14514 
14515 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14516   assert(isUnevaluatedContext() &&
14517          "Should only transform unevaluated expressions");
14518   ExprEvalContexts.back().Context =
14519       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14520   if (isUnevaluatedContext())
14521     return E;
14522   return TransformToPE(*this).TransformExpr(E);
14523 }
14524 
14525 void
14526 Sema::PushExpressionEvaluationContext(
14527     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14528     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14529   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14530                                 LambdaContextDecl, ExprContext);
14531   Cleanup.reset();
14532   if (!MaybeODRUseExprs.empty())
14533     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14534 }
14535 
14536 void
14537 Sema::PushExpressionEvaluationContext(
14538     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14539     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14540   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14541   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14542 }
14543 
14544 namespace {
14545 
14546 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14547   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14548   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14549     if (E->getOpcode() == UO_Deref)
14550       return CheckPossibleDeref(S, E->getSubExpr());
14551   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14552     return CheckPossibleDeref(S, E->getBase());
14553   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14554     return CheckPossibleDeref(S, E->getBase());
14555   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14556     QualType Inner;
14557     QualType Ty = E->getType();
14558     if (const auto *Ptr = Ty->getAs<PointerType>())
14559       Inner = Ptr->getPointeeType();
14560     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14561       Inner = Arr->getElementType();
14562     else
14563       return nullptr;
14564 
14565     if (Inner->hasAttr(attr::NoDeref))
14566       return E;
14567   }
14568   return nullptr;
14569 }
14570 
14571 } // namespace
14572 
14573 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14574   for (const Expr *E : Rec.PossibleDerefs) {
14575     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14576     if (DeclRef) {
14577       const ValueDecl *Decl = DeclRef->getDecl();
14578       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14579           << Decl->getName() << E->getSourceRange();
14580       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14581     } else {
14582       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14583           << E->getSourceRange();
14584     }
14585   }
14586   Rec.PossibleDerefs.clear();
14587 }
14588 
14589 void Sema::PopExpressionEvaluationContext() {
14590   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14591   unsigned NumTypos = Rec.NumTypos;
14592 
14593   if (!Rec.Lambdas.empty()) {
14594     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14595     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14596         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14597       unsigned D;
14598       if (Rec.isUnevaluated()) {
14599         // C++11 [expr.prim.lambda]p2:
14600         //   A lambda-expression shall not appear in an unevaluated operand
14601         //   (Clause 5).
14602         D = diag::err_lambda_unevaluated_operand;
14603       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14604         // C++1y [expr.const]p2:
14605         //   A conditional-expression e is a core constant expression unless the
14606         //   evaluation of e, following the rules of the abstract machine, would
14607         //   evaluate [...] a lambda-expression.
14608         D = diag::err_lambda_in_constant_expression;
14609       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14610         // C++17 [expr.prim.lamda]p2:
14611         // A lambda-expression shall not appear [...] in a template-argument.
14612         D = diag::err_lambda_in_invalid_context;
14613       } else
14614         llvm_unreachable("Couldn't infer lambda error message.");
14615 
14616       for (const auto *L : Rec.Lambdas)
14617         Diag(L->getBeginLoc(), D);
14618     } else {
14619       // Mark the capture expressions odr-used. This was deferred
14620       // during lambda expression creation.
14621       for (auto *Lambda : Rec.Lambdas) {
14622         for (auto *C : Lambda->capture_inits())
14623           MarkDeclarationsReferencedInExpr(C);
14624       }
14625     }
14626   }
14627 
14628   WarnOnPendingNoDerefs(Rec);
14629 
14630   // When are coming out of an unevaluated context, clear out any
14631   // temporaries that we may have created as part of the evaluation of
14632   // the expression in that context: they aren't relevant because they
14633   // will never be constructed.
14634   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14635     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14636                              ExprCleanupObjects.end());
14637     Cleanup = Rec.ParentCleanup;
14638     CleanupVarDeclMarking();
14639     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14640   // Otherwise, merge the contexts together.
14641   } else {
14642     Cleanup.mergeFrom(Rec.ParentCleanup);
14643     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14644                             Rec.SavedMaybeODRUseExprs.end());
14645   }
14646 
14647   // Pop the current expression evaluation context off the stack.
14648   ExprEvalContexts.pop_back();
14649 
14650   // The global expression evaluation context record is never popped.
14651   ExprEvalContexts.back().NumTypos += NumTypos;
14652 }
14653 
14654 void Sema::DiscardCleanupsInEvaluationContext() {
14655   ExprCleanupObjects.erase(
14656          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14657          ExprCleanupObjects.end());
14658   Cleanup.reset();
14659   MaybeODRUseExprs.clear();
14660 }
14661 
14662 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14663   ExprResult Result = CheckPlaceholderExpr(E);
14664   if (Result.isInvalid())
14665     return ExprError();
14666   E = Result.get();
14667   if (!E->getType()->isVariablyModifiedType())
14668     return E;
14669   return TransformToPotentiallyEvaluated(E);
14670 }
14671 
14672 /// Are we within a context in which some evaluation could be performed (be it
14673 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14674 /// captured by C++'s idea of an "unevaluated context".
14675 static bool isEvaluatableContext(Sema &SemaRef) {
14676   switch (SemaRef.ExprEvalContexts.back().Context) {
14677     case Sema::ExpressionEvaluationContext::Unevaluated:
14678     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14679       // Expressions in this context are never evaluated.
14680       return false;
14681 
14682     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14683     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14684     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14685     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14686       // Expressions in this context could be evaluated.
14687       return true;
14688 
14689     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14690       // Referenced declarations will only be used if the construct in the
14691       // containing expression is used, at which point we'll be given another
14692       // turn to mark them.
14693       return false;
14694   }
14695   llvm_unreachable("Invalid context");
14696 }
14697 
14698 /// Are we within a context in which references to resolved functions or to
14699 /// variables result in odr-use?
14700 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14701   // An expression in a template is not really an expression until it's been
14702   // instantiated, so it doesn't trigger odr-use.
14703   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14704     return false;
14705 
14706   switch (SemaRef.ExprEvalContexts.back().Context) {
14707     case Sema::ExpressionEvaluationContext::Unevaluated:
14708     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14709     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14710     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14711       return false;
14712 
14713     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14714     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14715       return true;
14716 
14717     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14718       return false;
14719   }
14720   llvm_unreachable("Invalid context");
14721 }
14722 
14723 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14724   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14725   return Func->isConstexpr() &&
14726          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14727 }
14728 
14729 /// Mark a function referenced, and check whether it is odr-used
14730 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14731 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14732                                   bool MightBeOdrUse) {
14733   assert(Func && "No function?");
14734 
14735   Func->setReferenced();
14736 
14737   // C++11 [basic.def.odr]p3:
14738   //   A function whose name appears as a potentially-evaluated expression is
14739   //   odr-used if it is the unique lookup result or the selected member of a
14740   //   set of overloaded functions [...].
14741   //
14742   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14743   // can just check that here.
14744   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14745 
14746   // Determine whether we require a function definition to exist, per
14747   // C++11 [temp.inst]p3:
14748   //   Unless a function template specialization has been explicitly
14749   //   instantiated or explicitly specialized, the function template
14750   //   specialization is implicitly instantiated when the specialization is
14751   //   referenced in a context that requires a function definition to exist.
14752   //
14753   // That is either when this is an odr-use, or when a usage of a constexpr
14754   // function occurs within an evaluatable context.
14755   bool NeedDefinition =
14756       OdrUse || (isEvaluatableContext(*this) &&
14757                  isImplicitlyDefinableConstexprFunction(Func));
14758 
14759   // C++14 [temp.expl.spec]p6:
14760   //   If a template [...] is explicitly specialized then that specialization
14761   //   shall be declared before the first use of that specialization that would
14762   //   cause an implicit instantiation to take place, in every translation unit
14763   //   in which such a use occurs
14764   if (NeedDefinition &&
14765       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14766        Func->getMemberSpecializationInfo()))
14767     checkSpecializationVisibility(Loc, Func);
14768 
14769   // C++14 [except.spec]p17:
14770   //   An exception-specification is considered to be needed when:
14771   //   - the function is odr-used or, if it appears in an unevaluated operand,
14772   //     would be odr-used if the expression were potentially-evaluated;
14773   //
14774   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14775   // function is a pure virtual function we're calling, and in that case the
14776   // function was selected by overload resolution and we need to resolve its
14777   // exception specification for a different reason.
14778   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14779   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14780     ResolveExceptionSpec(Loc, FPT);
14781 
14782   // If we don't need to mark the function as used, and we don't need to
14783   // try to provide a definition, there's nothing more to do.
14784   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14785       (!NeedDefinition || Func->getBody()))
14786     return;
14787 
14788   // Note that this declaration has been used.
14789   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14790     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14791     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14792       if (Constructor->isDefaultConstructor()) {
14793         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14794           return;
14795         DefineImplicitDefaultConstructor(Loc, Constructor);
14796       } else if (Constructor->isCopyConstructor()) {
14797         DefineImplicitCopyConstructor(Loc, Constructor);
14798       } else if (Constructor->isMoveConstructor()) {
14799         DefineImplicitMoveConstructor(Loc, Constructor);
14800       }
14801     } else if (Constructor->getInheritedConstructor()) {
14802       DefineInheritingConstructor(Loc, Constructor);
14803     }
14804   } else if (CXXDestructorDecl *Destructor =
14805                  dyn_cast<CXXDestructorDecl>(Func)) {
14806     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14807     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14808       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14809         return;
14810       DefineImplicitDestructor(Loc, Destructor);
14811     }
14812     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14813       MarkVTableUsed(Loc, Destructor->getParent());
14814   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14815     if (MethodDecl->isOverloadedOperator() &&
14816         MethodDecl->getOverloadedOperator() == OO_Equal) {
14817       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14818       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14819         if (MethodDecl->isCopyAssignmentOperator())
14820           DefineImplicitCopyAssignment(Loc, MethodDecl);
14821         else if (MethodDecl->isMoveAssignmentOperator())
14822           DefineImplicitMoveAssignment(Loc, MethodDecl);
14823       }
14824     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14825                MethodDecl->getParent()->isLambda()) {
14826       CXXConversionDecl *Conversion =
14827           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14828       if (Conversion->isLambdaToBlockPointerConversion())
14829         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14830       else
14831         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14832     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14833       MarkVTableUsed(Loc, MethodDecl->getParent());
14834   }
14835 
14836   // Recursive functions should be marked when used from another function.
14837   // FIXME: Is this really right?
14838   if (CurContext == Func) return;
14839 
14840   // Implicit instantiation of function templates and member functions of
14841   // class templates.
14842   if (Func->isImplicitlyInstantiable()) {
14843     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14844     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14845     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14846     if (FirstInstantiation) {
14847       PointOfInstantiation = Loc;
14848       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14849     } else if (TSK != TSK_ImplicitInstantiation) {
14850       // Use the point of use as the point of instantiation, instead of the
14851       // point of explicit instantiation (which we track as the actual point of
14852       // instantiation). This gives better backtraces in diagnostics.
14853       PointOfInstantiation = Loc;
14854     }
14855 
14856     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14857         Func->isConstexpr()) {
14858       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14859           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14860           CodeSynthesisContexts.size())
14861         PendingLocalImplicitInstantiations.push_back(
14862             std::make_pair(Func, PointOfInstantiation));
14863       else if (Func->isConstexpr())
14864         // Do not defer instantiations of constexpr functions, to avoid the
14865         // expression evaluator needing to call back into Sema if it sees a
14866         // call to such a function.
14867         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14868       else {
14869         Func->setInstantiationIsPending(true);
14870         PendingInstantiations.push_back(std::make_pair(Func,
14871                                                        PointOfInstantiation));
14872         // Notify the consumer that a function was implicitly instantiated.
14873         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14874       }
14875     }
14876   } else {
14877     // Walk redefinitions, as some of them may be instantiable.
14878     for (auto i : Func->redecls()) {
14879       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14880         MarkFunctionReferenced(Loc, i, OdrUse);
14881     }
14882   }
14883 
14884   if (!OdrUse) return;
14885 
14886   // Keep track of used but undefined functions.
14887   if (!Func->isDefined()) {
14888     if (mightHaveNonExternalLinkage(Func))
14889       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14890     else if (Func->getMostRecentDecl()->isInlined() &&
14891              !LangOpts.GNUInline &&
14892              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14893       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14894     else if (isExternalWithNoLinkageType(Func))
14895       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14896   }
14897 
14898   Func->markUsed(Context);
14899 }
14900 
14901 static void
14902 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14903                                    ValueDecl *var, DeclContext *DC) {
14904   DeclContext *VarDC = var->getDeclContext();
14905 
14906   //  If the parameter still belongs to the translation unit, then
14907   //  we're actually just using one parameter in the declaration of
14908   //  the next.
14909   if (isa<ParmVarDecl>(var) &&
14910       isa<TranslationUnitDecl>(VarDC))
14911     return;
14912 
14913   // For C code, don't diagnose about capture if we're not actually in code
14914   // right now; it's impossible to write a non-constant expression outside of
14915   // function context, so we'll get other (more useful) diagnostics later.
14916   //
14917   // For C++, things get a bit more nasty... it would be nice to suppress this
14918   // diagnostic for certain cases like using a local variable in an array bound
14919   // for a member of a local class, but the correct predicate is not obvious.
14920   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14921     return;
14922 
14923   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14924   unsigned ContextKind = 3; // unknown
14925   if (isa<CXXMethodDecl>(VarDC) &&
14926       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14927     ContextKind = 2;
14928   } else if (isa<FunctionDecl>(VarDC)) {
14929     ContextKind = 0;
14930   } else if (isa<BlockDecl>(VarDC)) {
14931     ContextKind = 1;
14932   }
14933 
14934   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14935     << var << ValueKind << ContextKind << VarDC;
14936   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14937       << var;
14938 
14939   // FIXME: Add additional diagnostic info about class etc. which prevents
14940   // capture.
14941 }
14942 
14943 
14944 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14945                                       bool &SubCapturesAreNested,
14946                                       QualType &CaptureType,
14947                                       QualType &DeclRefType) {
14948    // Check whether we've already captured it.
14949   if (CSI->CaptureMap.count(Var)) {
14950     // If we found a capture, any subcaptures are nested.
14951     SubCapturesAreNested = true;
14952 
14953     // Retrieve the capture type for this variable.
14954     CaptureType = CSI->getCapture(Var).getCaptureType();
14955 
14956     // Compute the type of an expression that refers to this variable.
14957     DeclRefType = CaptureType.getNonReferenceType();
14958 
14959     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14960     // are mutable in the sense that user can change their value - they are
14961     // private instances of the captured declarations.
14962     const Capture &Cap = CSI->getCapture(Var);
14963     if (Cap.isCopyCapture() &&
14964         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14965         !(isa<CapturedRegionScopeInfo>(CSI) &&
14966           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14967       DeclRefType.addConst();
14968     return true;
14969   }
14970   return false;
14971 }
14972 
14973 // Only block literals, captured statements, and lambda expressions can
14974 // capture; other scopes don't work.
14975 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14976                                  SourceLocation Loc,
14977                                  const bool Diagnose, Sema &S) {
14978   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14979     return getLambdaAwareParentOfDeclContext(DC);
14980   else if (Var->hasLocalStorage()) {
14981     if (Diagnose)
14982        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14983   }
14984   return nullptr;
14985 }
14986 
14987 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14988 // certain types of variables (unnamed, variably modified types etc.)
14989 // so check for eligibility.
14990 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14991                                  SourceLocation Loc,
14992                                  const bool Diagnose, Sema &S) {
14993 
14994   bool IsBlock = isa<BlockScopeInfo>(CSI);
14995   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14996 
14997   // Lambdas are not allowed to capture unnamed variables
14998   // (e.g. anonymous unions).
14999   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15000   // assuming that's the intent.
15001   if (IsLambda && !Var->getDeclName()) {
15002     if (Diagnose) {
15003       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15004       S.Diag(Var->getLocation(), diag::note_declared_at);
15005     }
15006     return false;
15007   }
15008 
15009   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15010   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15011     if (Diagnose) {
15012       S.Diag(Loc, diag::err_ref_vm_type);
15013       S.Diag(Var->getLocation(), diag::note_previous_decl)
15014         << Var->getDeclName();
15015     }
15016     return false;
15017   }
15018   // Prohibit structs with flexible array members too.
15019   // We cannot capture what is in the tail end of the struct.
15020   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15021     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15022       if (Diagnose) {
15023         if (IsBlock)
15024           S.Diag(Loc, diag::err_ref_flexarray_type);
15025         else
15026           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15027             << Var->getDeclName();
15028         S.Diag(Var->getLocation(), diag::note_previous_decl)
15029           << Var->getDeclName();
15030       }
15031       return false;
15032     }
15033   }
15034   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15035   // Lambdas and captured statements are not allowed to capture __block
15036   // variables; they don't support the expected semantics.
15037   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15038     if (Diagnose) {
15039       S.Diag(Loc, diag::err_capture_block_variable)
15040         << Var->getDeclName() << !IsLambda;
15041       S.Diag(Var->getLocation(), diag::note_previous_decl)
15042         << Var->getDeclName();
15043     }
15044     return false;
15045   }
15046   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15047   if (S.getLangOpts().OpenCL && IsBlock &&
15048       Var->getType()->isBlockPointerType()) {
15049     if (Diagnose)
15050       S.Diag(Loc, diag::err_opencl_block_ref_block);
15051     return false;
15052   }
15053 
15054   return true;
15055 }
15056 
15057 // Returns true if the capture by block was successful.
15058 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15059                                  SourceLocation Loc,
15060                                  const bool BuildAndDiagnose,
15061                                  QualType &CaptureType,
15062                                  QualType &DeclRefType,
15063                                  const bool Nested,
15064                                  Sema &S) {
15065   Expr *CopyExpr = nullptr;
15066   bool ByRef = false;
15067 
15068   // Blocks are not allowed to capture arrays, excepting OpenCL.
15069   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15070   // (decayed to pointers).
15071   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15072     if (BuildAndDiagnose) {
15073       S.Diag(Loc, diag::err_ref_array_type);
15074       S.Diag(Var->getLocation(), diag::note_previous_decl)
15075       << Var->getDeclName();
15076     }
15077     return false;
15078   }
15079 
15080   // Forbid the block-capture of autoreleasing variables.
15081   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15082     if (BuildAndDiagnose) {
15083       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15084         << /*block*/ 0;
15085       S.Diag(Var->getLocation(), diag::note_previous_decl)
15086         << Var->getDeclName();
15087     }
15088     return false;
15089   }
15090 
15091   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15092   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15093     // This function finds out whether there is an AttributedType of kind
15094     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15095     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15096     // rather than being added implicitly by the compiler.
15097     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15098       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15099         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15100           return true;
15101 
15102         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15103         Ty = AttrTy->getModifiedType();
15104       }
15105 
15106       return false;
15107     };
15108 
15109     QualType PointeeTy = PT->getPointeeType();
15110 
15111     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
15112         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15113         !IsObjCOwnershipAttributedType(PointeeTy)) {
15114       if (BuildAndDiagnose) {
15115         SourceLocation VarLoc = Var->getLocation();
15116         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15117         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15118       }
15119     }
15120   }
15121 
15122   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15123   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15124       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15125     // Block capture by reference does not change the capture or
15126     // declaration reference types.
15127     ByRef = true;
15128   } else {
15129     // Block capture by copy introduces 'const'.
15130     CaptureType = CaptureType.getNonReferenceType().withConst();
15131     DeclRefType = CaptureType;
15132 
15133     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15134       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15135         // The capture logic needs the destructor, so make sure we mark it.
15136         // Usually this is unnecessary because most local variables have
15137         // their destructors marked at declaration time, but parameters are
15138         // an exception because it's technically only the call site that
15139         // actually requires the destructor.
15140         if (isa<ParmVarDecl>(Var))
15141           S.FinalizeVarWithDestructor(Var, Record);
15142 
15143         // Enter a new evaluation context to insulate the copy
15144         // full-expression.
15145         EnterExpressionEvaluationContext scope(
15146             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
15147 
15148         // According to the blocks spec, the capture of a variable from
15149         // the stack requires a const copy constructor.  This is not true
15150         // of the copy/move done to move a __block variable to the heap.
15151         Expr *DeclRef = new (S.Context) DeclRefExpr(
15152             S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15153 
15154         ExprResult Result
15155           = S.PerformCopyInitialization(
15156               InitializedEntity::InitializeBlock(Var->getLocation(),
15157                                                   CaptureType, false),
15158               Loc, DeclRef);
15159 
15160         // Build a full-expression copy expression if initialization
15161         // succeeded and used a non-trivial constructor.  Recover from
15162         // errors by pretending that the copy isn't necessary.
15163         if (!Result.isInvalid() &&
15164             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15165                 ->isTrivial()) {
15166           Result = S.MaybeCreateExprWithCleanups(Result);
15167           CopyExpr = Result.get();
15168         }
15169       }
15170     }
15171   }
15172 
15173   // Actually capture the variable.
15174   if (BuildAndDiagnose)
15175     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15176                     SourceLocation(), CaptureType, CopyExpr);
15177 
15178   return true;
15179 
15180 }
15181 
15182 
15183 /// Capture the given variable in the captured region.
15184 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15185                                     VarDecl *Var,
15186                                     SourceLocation Loc,
15187                                     const bool BuildAndDiagnose,
15188                                     QualType &CaptureType,
15189                                     QualType &DeclRefType,
15190                                     const bool RefersToCapturedVariable,
15191                                     Sema &S) {
15192   // By default, capture variables by reference.
15193   bool ByRef = true;
15194   // Using an LValue reference type is consistent with Lambdas (see below).
15195   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15196     if (S.isOpenMPCapturedDecl(Var)) {
15197       bool HasConst = DeclRefType.isConstQualified();
15198       DeclRefType = DeclRefType.getUnqualifiedType();
15199       // Don't lose diagnostics about assignments to const.
15200       if (HasConst)
15201         DeclRefType.addConst();
15202     }
15203     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15204   }
15205 
15206   if (ByRef)
15207     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15208   else
15209     CaptureType = DeclRefType;
15210 
15211   Expr *CopyExpr = nullptr;
15212   if (BuildAndDiagnose) {
15213     // The current implementation assumes that all variables are captured
15214     // by references. Since there is no capture by copy, no expression
15215     // evaluation will be needed.
15216     RecordDecl *RD = RSI->TheRecordDecl;
15217 
15218     FieldDecl *Field
15219       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15220                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15221                           nullptr, false, ICIS_NoInit);
15222     Field->setImplicit(true);
15223     Field->setAccess(AS_private);
15224     RD->addDecl(Field);
15225     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15226       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15227 
15228     CopyExpr = new (S.Context) DeclRefExpr(
15229         S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15230     Var->setReferenced(true);
15231     Var->markUsed(S.Context);
15232   }
15233 
15234   // Actually capture the variable.
15235   if (BuildAndDiagnose)
15236     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15237                     SourceLocation(), CaptureType, CopyExpr);
15238 
15239 
15240   return true;
15241 }
15242 
15243 /// Create a field within the lambda class for the variable
15244 /// being captured.
15245 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
15246                                     QualType FieldType, QualType DeclRefType,
15247                                     SourceLocation Loc,
15248                                     bool RefersToCapturedVariable) {
15249   CXXRecordDecl *Lambda = LSI->Lambda;
15250 
15251   // Build the non-static data member.
15252   FieldDecl *Field
15253     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15254                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15255                         nullptr, false, ICIS_NoInit);
15256   // If the variable being captured has an invalid type, mark the lambda class
15257   // as invalid as well.
15258   if (!FieldType->isDependentType()) {
15259     if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15260       Lambda->setInvalidDecl();
15261       Field->setInvalidDecl();
15262     } else {
15263       NamedDecl *Def;
15264       FieldType->isIncompleteType(&Def);
15265       if (Def && Def->isInvalidDecl()) {
15266         Lambda->setInvalidDecl();
15267         Field->setInvalidDecl();
15268       }
15269     }
15270   }
15271   Field->setImplicit(true);
15272   Field->setAccess(AS_private);
15273   Lambda->addDecl(Field);
15274 }
15275 
15276 /// Capture the given variable in the lambda.
15277 static bool captureInLambda(LambdaScopeInfo *LSI,
15278                             VarDecl *Var,
15279                             SourceLocation Loc,
15280                             const bool BuildAndDiagnose,
15281                             QualType &CaptureType,
15282                             QualType &DeclRefType,
15283                             const bool RefersToCapturedVariable,
15284                             const Sema::TryCaptureKind Kind,
15285                             SourceLocation EllipsisLoc,
15286                             const bool IsTopScope,
15287                             Sema &S) {
15288 
15289   // Determine whether we are capturing by reference or by value.
15290   bool ByRef = false;
15291   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15292     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15293   } else {
15294     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15295   }
15296 
15297   // Compute the type of the field that will capture this variable.
15298   if (ByRef) {
15299     // C++11 [expr.prim.lambda]p15:
15300     //   An entity is captured by reference if it is implicitly or
15301     //   explicitly captured but not captured by copy. It is
15302     //   unspecified whether additional unnamed non-static data
15303     //   members are declared in the closure type for entities
15304     //   captured by reference.
15305     //
15306     // FIXME: It is not clear whether we want to build an lvalue reference
15307     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15308     // to do the former, while EDG does the latter. Core issue 1249 will
15309     // clarify, but for now we follow GCC because it's a more permissive and
15310     // easily defensible position.
15311     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15312   } else {
15313     // C++11 [expr.prim.lambda]p14:
15314     //   For each entity captured by copy, an unnamed non-static
15315     //   data member is declared in the closure type. The
15316     //   declaration order of these members is unspecified. The type
15317     //   of such a data member is the type of the corresponding
15318     //   captured entity if the entity is not a reference to an
15319     //   object, or the referenced type otherwise. [Note: If the
15320     //   captured entity is a reference to a function, the
15321     //   corresponding data member is also a reference to a
15322     //   function. - end note ]
15323     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15324       if (!RefType->getPointeeType()->isFunctionType())
15325         CaptureType = RefType->getPointeeType();
15326     }
15327 
15328     // Forbid the lambda copy-capture of autoreleasing variables.
15329     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15330       if (BuildAndDiagnose) {
15331         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15332         S.Diag(Var->getLocation(), diag::note_previous_decl)
15333           << Var->getDeclName();
15334       }
15335       return false;
15336     }
15337 
15338     // Make sure that by-copy captures are of a complete and non-abstract type.
15339     if (BuildAndDiagnose) {
15340       if (!CaptureType->isDependentType() &&
15341           S.RequireCompleteType(Loc, CaptureType,
15342                                 diag::err_capture_of_incomplete_type,
15343                                 Var->getDeclName()))
15344         return false;
15345 
15346       if (S.RequireNonAbstractType(Loc, CaptureType,
15347                                    diag::err_capture_of_abstract_type))
15348         return false;
15349     }
15350   }
15351 
15352   // Capture this variable in the lambda.
15353   if (BuildAndDiagnose)
15354     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15355                             RefersToCapturedVariable);
15356 
15357   // Compute the type of a reference to this captured variable.
15358   if (ByRef)
15359     DeclRefType = CaptureType.getNonReferenceType();
15360   else {
15361     // C++ [expr.prim.lambda]p5:
15362     //   The closure type for a lambda-expression has a public inline
15363     //   function call operator [...]. This function call operator is
15364     //   declared const (9.3.1) if and only if the lambda-expression's
15365     //   parameter-declaration-clause is not followed by mutable.
15366     DeclRefType = CaptureType.getNonReferenceType();
15367     if (!LSI->Mutable && !CaptureType->isReferenceType())
15368       DeclRefType.addConst();
15369   }
15370 
15371   // Add the capture.
15372   if (BuildAndDiagnose)
15373     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15374                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15375 
15376   return true;
15377 }
15378 
15379 bool Sema::tryCaptureVariable(
15380     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15381     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15382     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15383   // An init-capture is notionally from the context surrounding its
15384   // declaration, but its parent DC is the lambda class.
15385   DeclContext *VarDC = Var->getDeclContext();
15386   if (Var->isInitCapture())
15387     VarDC = VarDC->getParent();
15388 
15389   DeclContext *DC = CurContext;
15390   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15391       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15392   // We need to sync up the Declaration Context with the
15393   // FunctionScopeIndexToStopAt
15394   if (FunctionScopeIndexToStopAt) {
15395     unsigned FSIndex = FunctionScopes.size() - 1;
15396     while (FSIndex != MaxFunctionScopesIndex) {
15397       DC = getLambdaAwareParentOfDeclContext(DC);
15398       --FSIndex;
15399     }
15400   }
15401 
15402 
15403   // If the variable is declared in the current context, there is no need to
15404   // capture it.
15405   if (VarDC == DC) return true;
15406 
15407   // Capture global variables if it is required to use private copy of this
15408   // variable.
15409   bool IsGlobal = !Var->hasLocalStorage();
15410   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15411     return true;
15412   Var = Var->getCanonicalDecl();
15413 
15414   // Walk up the stack to determine whether we can capture the variable,
15415   // performing the "simple" checks that don't depend on type. We stop when
15416   // we've either hit the declared scope of the variable or find an existing
15417   // capture of that variable.  We start from the innermost capturing-entity
15418   // (the DC) and ensure that all intervening capturing-entities
15419   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15420   // declcontext can either capture the variable or have already captured
15421   // the variable.
15422   CaptureType = Var->getType();
15423   DeclRefType = CaptureType.getNonReferenceType();
15424   bool Nested = false;
15425   bool Explicit = (Kind != TryCapture_Implicit);
15426   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15427   do {
15428     // Only block literals, captured statements, and lambda expressions can
15429     // capture; other scopes don't work.
15430     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15431                                                               ExprLoc,
15432                                                               BuildAndDiagnose,
15433                                                               *this);
15434     // We need to check for the parent *first* because, if we *have*
15435     // private-captured a global variable, we need to recursively capture it in
15436     // intermediate blocks, lambdas, etc.
15437     if (!ParentDC) {
15438       if (IsGlobal) {
15439         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15440         break;
15441       }
15442       return true;
15443     }
15444 
15445     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15446     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15447 
15448 
15449     // Check whether we've already captured it.
15450     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15451                                              DeclRefType)) {
15452       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15453       break;
15454     }
15455     // If we are instantiating a generic lambda call operator body,
15456     // we do not want to capture new variables.  What was captured
15457     // during either a lambdas transformation or initial parsing
15458     // should be used.
15459     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15460       if (BuildAndDiagnose) {
15461         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15462         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15463           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15464           Diag(Var->getLocation(), diag::note_previous_decl)
15465              << Var->getDeclName();
15466           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15467         } else
15468           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15469       }
15470       return true;
15471     }
15472     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15473     // certain types of variables (unnamed, variably modified types etc.)
15474     // so check for eligibility.
15475     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15476        return true;
15477 
15478     // Try to capture variable-length arrays types.
15479     if (Var->getType()->isVariablyModifiedType()) {
15480       // We're going to walk down into the type and look for VLA
15481       // expressions.
15482       QualType QTy = Var->getType();
15483       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15484         QTy = PVD->getOriginalType();
15485       captureVariablyModifiedType(Context, QTy, CSI);
15486     }
15487 
15488     if (getLangOpts().OpenMP) {
15489       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15490         // OpenMP private variables should not be captured in outer scope, so
15491         // just break here. Similarly, global variables that are captured in a
15492         // target region should not be captured outside the scope of the region.
15493         if (RSI->CapRegionKind == CR_OpenMP) {
15494           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15495           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15496                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15497           // When we detect target captures we are looking from inside the
15498           // target region, therefore we need to propagate the capture from the
15499           // enclosing region. Therefore, the capture is not initially nested.
15500           if (IsTargetCap)
15501             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15502 
15503           if (IsTargetCap || IsOpenMPPrivateDecl) {
15504             Nested = !IsTargetCap;
15505             DeclRefType = DeclRefType.getUnqualifiedType();
15506             CaptureType = Context.getLValueReferenceType(DeclRefType);
15507             break;
15508           }
15509         }
15510       }
15511     }
15512     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15513       // No capture-default, and this is not an explicit capture
15514       // so cannot capture this variable.
15515       if (BuildAndDiagnose) {
15516         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15517         Diag(Var->getLocation(), diag::note_previous_decl)
15518           << Var->getDeclName();
15519         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15520           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15521                diag::note_lambda_decl);
15522         // FIXME: If we error out because an outer lambda can not implicitly
15523         // capture a variable that an inner lambda explicitly captures, we
15524         // should have the inner lambda do the explicit capture - because
15525         // it makes for cleaner diagnostics later.  This would purely be done
15526         // so that the diagnostic does not misleadingly claim that a variable
15527         // can not be captured by a lambda implicitly even though it is captured
15528         // explicitly.  Suggestion:
15529         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15530         //    at the function head
15531         //  - cache the StartingDeclContext - this must be a lambda
15532         //  - captureInLambda in the innermost lambda the variable.
15533       }
15534       return true;
15535     }
15536 
15537     FunctionScopesIndex--;
15538     DC = ParentDC;
15539     Explicit = false;
15540   } while (!VarDC->Equals(DC));
15541 
15542   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15543   // computing the type of the capture at each step, checking type-specific
15544   // requirements, and adding captures if requested.
15545   // If the variable had already been captured previously, we start capturing
15546   // at the lambda nested within that one.
15547   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15548        ++I) {
15549     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15550 
15551     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15552       if (!captureInBlock(BSI, Var, ExprLoc,
15553                           BuildAndDiagnose, CaptureType,
15554                           DeclRefType, Nested, *this))
15555         return true;
15556       Nested = true;
15557     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15558       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15559                                    BuildAndDiagnose, CaptureType,
15560                                    DeclRefType, Nested, *this))
15561         return true;
15562       Nested = true;
15563     } else {
15564       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15565       if (!captureInLambda(LSI, Var, ExprLoc,
15566                            BuildAndDiagnose, CaptureType,
15567                            DeclRefType, Nested, Kind, EllipsisLoc,
15568                             /*IsTopScope*/I == N - 1, *this))
15569         return true;
15570       Nested = true;
15571     }
15572   }
15573   return false;
15574 }
15575 
15576 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15577                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15578   QualType CaptureType;
15579   QualType DeclRefType;
15580   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15581                             /*BuildAndDiagnose=*/true, CaptureType,
15582                             DeclRefType, nullptr);
15583 }
15584 
15585 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15586   QualType CaptureType;
15587   QualType DeclRefType;
15588   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15589                              /*BuildAndDiagnose=*/false, CaptureType,
15590                              DeclRefType, nullptr);
15591 }
15592 
15593 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15594   QualType CaptureType;
15595   QualType DeclRefType;
15596 
15597   // Determine whether we can capture this variable.
15598   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15599                          /*BuildAndDiagnose=*/false, CaptureType,
15600                          DeclRefType, nullptr))
15601     return QualType();
15602 
15603   return DeclRefType;
15604 }
15605 
15606 
15607 
15608 // If either the type of the variable or the initializer is dependent,
15609 // return false. Otherwise, determine whether the variable is a constant
15610 // expression. Use this if you need to know if a variable that might or
15611 // might not be dependent is truly a constant expression.
15612 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15613     ASTContext &Context) {
15614 
15615   if (Var->getType()->isDependentType())
15616     return false;
15617   const VarDecl *DefVD = nullptr;
15618   Var->getAnyInitializer(DefVD);
15619   if (!DefVD)
15620     return false;
15621   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15622   Expr *Init = cast<Expr>(Eval->Value);
15623   if (Init->isValueDependent())
15624     return false;
15625   return IsVariableAConstantExpression(Var, Context);
15626 }
15627 
15628 
15629 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15630   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15631   // an object that satisfies the requirements for appearing in a
15632   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15633   // is immediately applied."  This function handles the lvalue-to-rvalue
15634   // conversion part.
15635   MaybeODRUseExprs.erase(E->IgnoreParens());
15636 
15637   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15638   // to a variable that is a constant expression, and if so, identify it as
15639   // a reference to a variable that does not involve an odr-use of that
15640   // variable.
15641   if (LambdaScopeInfo *LSI = getCurLambda()) {
15642     Expr *SansParensExpr = E->IgnoreParens();
15643     VarDecl *Var = nullptr;
15644     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15645       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15646     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15647       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15648 
15649     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15650       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15651   }
15652 }
15653 
15654 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15655   Res = CorrectDelayedTyposInExpr(Res);
15656 
15657   if (!Res.isUsable())
15658     return Res;
15659 
15660   // If a constant-expression is a reference to a variable where we delay
15661   // deciding whether it is an odr-use, just assume we will apply the
15662   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15663   // (a non-type template argument), we have special handling anyway.
15664   UpdateMarkingForLValueToRValue(Res.get());
15665   return Res;
15666 }
15667 
15668 void Sema::CleanupVarDeclMarking() {
15669   for (Expr *E : MaybeODRUseExprs) {
15670     VarDecl *Var;
15671     SourceLocation Loc;
15672     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15673       Var = cast<VarDecl>(DRE->getDecl());
15674       Loc = DRE->getLocation();
15675     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15676       Var = cast<VarDecl>(ME->getMemberDecl());
15677       Loc = ME->getMemberLoc();
15678     } else {
15679       llvm_unreachable("Unexpected expression");
15680     }
15681 
15682     MarkVarDeclODRUsed(Var, Loc, *this,
15683                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15684   }
15685 
15686   MaybeODRUseExprs.clear();
15687 }
15688 
15689 
15690 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15691                                     VarDecl *Var, Expr *E) {
15692   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15693          "Invalid Expr argument to DoMarkVarDeclReferenced");
15694   Var->setReferenced();
15695 
15696   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15697 
15698   bool OdrUseContext = isOdrUseContext(SemaRef);
15699   bool UsableInConstantExpr =
15700       Var->isUsableInConstantExpressions(SemaRef.Context);
15701   bool NeedDefinition =
15702       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15703 
15704   VarTemplateSpecializationDecl *VarSpec =
15705       dyn_cast<VarTemplateSpecializationDecl>(Var);
15706   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15707          "Can't instantiate a partial template specialization.");
15708 
15709   // If this might be a member specialization of a static data member, check
15710   // the specialization is visible. We already did the checks for variable
15711   // template specializations when we created them.
15712   if (NeedDefinition && TSK != TSK_Undeclared &&
15713       !isa<VarTemplateSpecializationDecl>(Var))
15714     SemaRef.checkSpecializationVisibility(Loc, Var);
15715 
15716   // Perform implicit instantiation of static data members, static data member
15717   // templates of class templates, and variable template specializations. Delay
15718   // instantiations of variable templates, except for those that could be used
15719   // in a constant expression.
15720   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15721     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15722     // instantiation declaration if a variable is usable in a constant
15723     // expression (among other cases).
15724     bool TryInstantiating =
15725         TSK == TSK_ImplicitInstantiation ||
15726         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15727 
15728     if (TryInstantiating) {
15729       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15730       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15731       if (FirstInstantiation) {
15732         PointOfInstantiation = Loc;
15733         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15734       }
15735 
15736       bool InstantiationDependent = false;
15737       bool IsNonDependent =
15738           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15739                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15740                   : true;
15741 
15742       // Do not instantiate specializations that are still type-dependent.
15743       if (IsNonDependent) {
15744         if (UsableInConstantExpr) {
15745           // Do not defer instantiations of variables that could be used in a
15746           // constant expression.
15747           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15748         } else if (FirstInstantiation ||
15749                    isa<VarTemplateSpecializationDecl>(Var)) {
15750           // FIXME: For a specialization of a variable template, we don't
15751           // distinguish between "declaration and type implicitly instantiated"
15752           // and "implicit instantiation of definition requested", so we have
15753           // no direct way to avoid enqueueing the pending instantiation
15754           // multiple times.
15755           SemaRef.PendingInstantiations
15756               .push_back(std::make_pair(Var, PointOfInstantiation));
15757         }
15758       }
15759     }
15760   }
15761 
15762   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15763   // the requirements for appearing in a constant expression (5.19) and, if
15764   // it is an object, the lvalue-to-rvalue conversion (4.1)
15765   // is immediately applied."  We check the first part here, and
15766   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15767   // Note that we use the C++11 definition everywhere because nothing in
15768   // C++03 depends on whether we get the C++03 version correct. The second
15769   // part does not apply to references, since they are not objects.
15770   if (OdrUseContext && E &&
15771       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15772     // A reference initialized by a constant expression can never be
15773     // odr-used, so simply ignore it.
15774     if (!Var->getType()->isReferenceType() ||
15775         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15776       SemaRef.MaybeODRUseExprs.insert(E);
15777   } else if (OdrUseContext) {
15778     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15779                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15780   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15781     // If this is a dependent context, we don't need to mark variables as
15782     // odr-used, but we may still need to track them for lambda capture.
15783     // FIXME: Do we also need to do this inside dependent typeid expressions
15784     // (which are modeled as unevaluated at this point)?
15785     const bool RefersToEnclosingScope =
15786         (SemaRef.CurContext != Var->getDeclContext() &&
15787          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15788     if (RefersToEnclosingScope) {
15789       LambdaScopeInfo *const LSI =
15790           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15791       if (LSI && (!LSI->CallOperator ||
15792                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15793         // If a variable could potentially be odr-used, defer marking it so
15794         // until we finish analyzing the full expression for any
15795         // lvalue-to-rvalue
15796         // or discarded value conversions that would obviate odr-use.
15797         // Add it to the list of potential captures that will be analyzed
15798         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15799         // unless the variable is a reference that was initialized by a constant
15800         // expression (this will never need to be captured or odr-used).
15801         assert(E && "Capture variable should be used in an expression.");
15802         if (!Var->getType()->isReferenceType() ||
15803             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15804           LSI->addPotentialCapture(E->IgnoreParens());
15805       }
15806     }
15807   }
15808 }
15809 
15810 /// Mark a variable referenced, and check whether it is odr-used
15811 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15812 /// used directly for normal expressions referring to VarDecl.
15813 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15814   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15815 }
15816 
15817 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15818                                Decl *D, Expr *E, bool MightBeOdrUse) {
15819   if (SemaRef.isInOpenMPDeclareTargetContext())
15820     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15821 
15822   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15823     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15824     return;
15825   }
15826 
15827   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15828 
15829   // If this is a call to a method via a cast, also mark the method in the
15830   // derived class used in case codegen can devirtualize the call.
15831   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15832   if (!ME)
15833     return;
15834   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15835   if (!MD)
15836     return;
15837   // Only attempt to devirtualize if this is truly a virtual call.
15838   bool IsVirtualCall = MD->isVirtual() &&
15839                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15840   if (!IsVirtualCall)
15841     return;
15842 
15843   // If it's possible to devirtualize the call, mark the called function
15844   // referenced.
15845   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15846       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15847   if (DM)
15848     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15849 }
15850 
15851 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15852 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15853   // TODO: update this with DR# once a defect report is filed.
15854   // C++11 defect. The address of a pure member should not be an ODR use, even
15855   // if it's a qualified reference.
15856   bool OdrUse = true;
15857   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15858     if (Method->isVirtual() &&
15859         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15860       OdrUse = false;
15861   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15862 }
15863 
15864 /// Perform reference-marking and odr-use handling for a MemberExpr.
15865 void Sema::MarkMemberReferenced(MemberExpr *E) {
15866   // C++11 [basic.def.odr]p2:
15867   //   A non-overloaded function whose name appears as a potentially-evaluated
15868   //   expression or a member of a set of candidate functions, if selected by
15869   //   overload resolution when referred to from a potentially-evaluated
15870   //   expression, is odr-used, unless it is a pure virtual function and its
15871   //   name is not explicitly qualified.
15872   bool MightBeOdrUse = true;
15873   if (E->performsVirtualDispatch(getLangOpts())) {
15874     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15875       if (Method->isPure())
15876         MightBeOdrUse = false;
15877   }
15878   SourceLocation Loc =
15879       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15880   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15881 }
15882 
15883 /// Perform marking for a reference to an arbitrary declaration.  It
15884 /// marks the declaration referenced, and performs odr-use checking for
15885 /// functions and variables. This method should not be used when building a
15886 /// normal expression which refers to a variable.
15887 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15888                                  bool MightBeOdrUse) {
15889   if (MightBeOdrUse) {
15890     if (auto *VD = dyn_cast<VarDecl>(D)) {
15891       MarkVariableReferenced(Loc, VD);
15892       return;
15893     }
15894   }
15895   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15896     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15897     return;
15898   }
15899   D->setReferenced();
15900 }
15901 
15902 namespace {
15903   // Mark all of the declarations used by a type as referenced.
15904   // FIXME: Not fully implemented yet! We need to have a better understanding
15905   // of when we're entering a context we should not recurse into.
15906   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15907   // TreeTransforms rebuilding the type in a new context. Rather than
15908   // duplicating the TreeTransform logic, we should consider reusing it here.
15909   // Currently that causes problems when rebuilding LambdaExprs.
15910   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15911     Sema &S;
15912     SourceLocation Loc;
15913 
15914   public:
15915     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15916 
15917     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15918 
15919     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15920   };
15921 }
15922 
15923 bool MarkReferencedDecls::TraverseTemplateArgument(
15924     const TemplateArgument &Arg) {
15925   {
15926     // A non-type template argument is a constant-evaluated context.
15927     EnterExpressionEvaluationContext Evaluated(
15928         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15929     if (Arg.getKind() == TemplateArgument::Declaration) {
15930       if (Decl *D = Arg.getAsDecl())
15931         S.MarkAnyDeclReferenced(Loc, D, true);
15932     } else if (Arg.getKind() == TemplateArgument::Expression) {
15933       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15934     }
15935   }
15936 
15937   return Inherited::TraverseTemplateArgument(Arg);
15938 }
15939 
15940 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15941   MarkReferencedDecls Marker(*this, Loc);
15942   Marker.TraverseType(T);
15943 }
15944 
15945 namespace {
15946   /// Helper class that marks all of the declarations referenced by
15947   /// potentially-evaluated subexpressions as "referenced".
15948   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15949     Sema &S;
15950     bool SkipLocalVariables;
15951 
15952   public:
15953     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15954 
15955     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15956       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15957 
15958     void VisitDeclRefExpr(DeclRefExpr *E) {
15959       // If we were asked not to visit local variables, don't.
15960       if (SkipLocalVariables) {
15961         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15962           if (VD->hasLocalStorage())
15963             return;
15964       }
15965 
15966       S.MarkDeclRefReferenced(E);
15967     }
15968 
15969     void VisitMemberExpr(MemberExpr *E) {
15970       S.MarkMemberReferenced(E);
15971       Inherited::VisitMemberExpr(E);
15972     }
15973 
15974     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15975       S.MarkFunctionReferenced(
15976           E->getBeginLoc(),
15977           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
15978       Visit(E->getSubExpr());
15979     }
15980 
15981     void VisitCXXNewExpr(CXXNewExpr *E) {
15982       if (E->getOperatorNew())
15983         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
15984       if (E->getOperatorDelete())
15985         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15986       Inherited::VisitCXXNewExpr(E);
15987     }
15988 
15989     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15990       if (E->getOperatorDelete())
15991         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
15992       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15993       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15994         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15995         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
15996       }
15997 
15998       Inherited::VisitCXXDeleteExpr(E);
15999     }
16000 
16001     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16002       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16003       Inherited::VisitCXXConstructExpr(E);
16004     }
16005 
16006     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16007       Visit(E->getExpr());
16008     }
16009 
16010     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
16011       Inherited::VisitImplicitCastExpr(E);
16012 
16013       if (E->getCastKind() == CK_LValueToRValue)
16014         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
16015     }
16016   };
16017 }
16018 
16019 /// Mark any declarations that appear within this expression or any
16020 /// potentially-evaluated subexpressions as "referenced".
16021 ///
16022 /// \param SkipLocalVariables If true, don't mark local variables as
16023 /// 'referenced'.
16024 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16025                                             bool SkipLocalVariables) {
16026   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16027 }
16028 
16029 /// Emit a diagnostic that describes an effect on the run-time behavior
16030 /// of the program being compiled.
16031 ///
16032 /// This routine emits the given diagnostic when the code currently being
16033 /// type-checked is "potentially evaluated", meaning that there is a
16034 /// possibility that the code will actually be executable. Code in sizeof()
16035 /// expressions, code used only during overload resolution, etc., are not
16036 /// potentially evaluated. This routine will suppress such diagnostics or,
16037 /// in the absolutely nutty case of potentially potentially evaluated
16038 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16039 /// later.
16040 ///
16041 /// This routine should be used for all diagnostics that describe the run-time
16042 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16043 /// Failure to do so will likely result in spurious diagnostics or failures
16044 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16045 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16046                                const PartialDiagnostic &PD) {
16047   switch (ExprEvalContexts.back().Context) {
16048   case ExpressionEvaluationContext::Unevaluated:
16049   case ExpressionEvaluationContext::UnevaluatedList:
16050   case ExpressionEvaluationContext::UnevaluatedAbstract:
16051   case ExpressionEvaluationContext::DiscardedStatement:
16052     // The argument will never be evaluated, so don't complain.
16053     break;
16054 
16055   case ExpressionEvaluationContext::ConstantEvaluated:
16056     // Relevant diagnostics should be produced by constant evaluation.
16057     break;
16058 
16059   case ExpressionEvaluationContext::PotentiallyEvaluated:
16060   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16061     if (Statement && getCurFunctionOrMethodDecl()) {
16062       FunctionScopes.back()->PossiblyUnreachableDiags.
16063         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
16064       return true;
16065     }
16066 
16067     // The initializer of a constexpr variable or of the first declaration of a
16068     // static data member is not syntactically a constant evaluated constant,
16069     // but nonetheless is always required to be a constant expression, so we
16070     // can skip diagnosing.
16071     // FIXME: Using the mangling context here is a hack.
16072     if (auto *VD = dyn_cast_or_null<VarDecl>(
16073             ExprEvalContexts.back().ManglingContextDecl)) {
16074       if (VD->isConstexpr() ||
16075           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16076         break;
16077       // FIXME: For any other kind of variable, we should build a CFG for its
16078       // initializer and check whether the context in question is reachable.
16079     }
16080 
16081     Diag(Loc, PD);
16082     return true;
16083   }
16084 
16085   return false;
16086 }
16087 
16088 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16089                                CallExpr *CE, FunctionDecl *FD) {
16090   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16091     return false;
16092 
16093   // If we're inside a decltype's expression, don't check for a valid return
16094   // type or construct temporaries until we know whether this is the last call.
16095   if (ExprEvalContexts.back().ExprContext ==
16096       ExpressionEvaluationContextRecord::EK_Decltype) {
16097     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16098     return false;
16099   }
16100 
16101   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16102     FunctionDecl *FD;
16103     CallExpr *CE;
16104 
16105   public:
16106     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16107       : FD(FD), CE(CE) { }
16108 
16109     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16110       if (!FD) {
16111         S.Diag(Loc, diag::err_call_incomplete_return)
16112           << T << CE->getSourceRange();
16113         return;
16114       }
16115 
16116       S.Diag(Loc, diag::err_call_function_incomplete_return)
16117         << CE->getSourceRange() << FD->getDeclName() << T;
16118       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16119           << FD->getDeclName();
16120     }
16121   } Diagnoser(FD, CE);
16122 
16123   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16124     return true;
16125 
16126   return false;
16127 }
16128 
16129 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16130 // will prevent this condition from triggering, which is what we want.
16131 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16132   SourceLocation Loc;
16133 
16134   unsigned diagnostic = diag::warn_condition_is_assignment;
16135   bool IsOrAssign = false;
16136 
16137   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16138     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16139       return;
16140 
16141     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16142 
16143     // Greylist some idioms by putting them into a warning subcategory.
16144     if (ObjCMessageExpr *ME
16145           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16146       Selector Sel = ME->getSelector();
16147 
16148       // self = [<foo> init...]
16149       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16150         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16151 
16152       // <foo> = [<bar> nextObject]
16153       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16154         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16155     }
16156 
16157     Loc = Op->getOperatorLoc();
16158   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16159     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16160       return;
16161 
16162     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16163     Loc = Op->getOperatorLoc();
16164   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16165     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16166   else {
16167     // Not an assignment.
16168     return;
16169   }
16170 
16171   Diag(Loc, diagnostic) << E->getSourceRange();
16172 
16173   SourceLocation Open = E->getBeginLoc();
16174   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16175   Diag(Loc, diag::note_condition_assign_silence)
16176         << FixItHint::CreateInsertion(Open, "(")
16177         << FixItHint::CreateInsertion(Close, ")");
16178 
16179   if (IsOrAssign)
16180     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16181       << FixItHint::CreateReplacement(Loc, "!=");
16182   else
16183     Diag(Loc, diag::note_condition_assign_to_comparison)
16184       << FixItHint::CreateReplacement(Loc, "==");
16185 }
16186 
16187 /// Redundant parentheses over an equality comparison can indicate
16188 /// that the user intended an assignment used as condition.
16189 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16190   // Don't warn if the parens came from a macro.
16191   SourceLocation parenLoc = ParenE->getBeginLoc();
16192   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16193     return;
16194   // Don't warn for dependent expressions.
16195   if (ParenE->isTypeDependent())
16196     return;
16197 
16198   Expr *E = ParenE->IgnoreParens();
16199 
16200   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16201     if (opE->getOpcode() == BO_EQ &&
16202         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16203                                                            == Expr::MLV_Valid) {
16204       SourceLocation Loc = opE->getOperatorLoc();
16205 
16206       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16207       SourceRange ParenERange = ParenE->getSourceRange();
16208       Diag(Loc, diag::note_equality_comparison_silence)
16209         << FixItHint::CreateRemoval(ParenERange.getBegin())
16210         << FixItHint::CreateRemoval(ParenERange.getEnd());
16211       Diag(Loc, diag::note_equality_comparison_to_assign)
16212         << FixItHint::CreateReplacement(Loc, "=");
16213     }
16214 }
16215 
16216 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16217                                        bool IsConstexpr) {
16218   DiagnoseAssignmentAsCondition(E);
16219   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16220     DiagnoseEqualityWithExtraParens(parenE);
16221 
16222   ExprResult result = CheckPlaceholderExpr(E);
16223   if (result.isInvalid()) return ExprError();
16224   E = result.get();
16225 
16226   if (!E->isTypeDependent()) {
16227     if (getLangOpts().CPlusPlus)
16228       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16229 
16230     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16231     if (ERes.isInvalid())
16232       return ExprError();
16233     E = ERes.get();
16234 
16235     QualType T = E->getType();
16236     if (!T->isScalarType()) { // C99 6.8.4.1p1
16237       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16238         << T << E->getSourceRange();
16239       return ExprError();
16240     }
16241     CheckBoolLikeConversion(E, Loc);
16242   }
16243 
16244   return E;
16245 }
16246 
16247 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16248                                            Expr *SubExpr, ConditionKind CK) {
16249   // Empty conditions are valid in for-statements.
16250   if (!SubExpr)
16251     return ConditionResult();
16252 
16253   ExprResult Cond;
16254   switch (CK) {
16255   case ConditionKind::Boolean:
16256     Cond = CheckBooleanCondition(Loc, SubExpr);
16257     break;
16258 
16259   case ConditionKind::ConstexprIf:
16260     Cond = CheckBooleanCondition(Loc, SubExpr, true);
16261     break;
16262 
16263   case ConditionKind::Switch:
16264     Cond = CheckSwitchCondition(Loc, SubExpr);
16265     break;
16266   }
16267   if (Cond.isInvalid())
16268     return ConditionError();
16269 
16270   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16271   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16272   if (!FullExpr.get())
16273     return ConditionError();
16274 
16275   return ConditionResult(*this, nullptr, FullExpr,
16276                          CK == ConditionKind::ConstexprIf);
16277 }
16278 
16279 namespace {
16280   /// A visitor for rebuilding a call to an __unknown_any expression
16281   /// to have an appropriate type.
16282   struct RebuildUnknownAnyFunction
16283     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16284 
16285     Sema &S;
16286 
16287     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16288 
16289     ExprResult VisitStmt(Stmt *S) {
16290       llvm_unreachable("unexpected statement!");
16291     }
16292 
16293     ExprResult VisitExpr(Expr *E) {
16294       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16295         << E->getSourceRange();
16296       return ExprError();
16297     }
16298 
16299     /// Rebuild an expression which simply semantically wraps another
16300     /// expression which it shares the type and value kind of.
16301     template <class T> ExprResult rebuildSugarExpr(T *E) {
16302       ExprResult SubResult = Visit(E->getSubExpr());
16303       if (SubResult.isInvalid()) return ExprError();
16304 
16305       Expr *SubExpr = SubResult.get();
16306       E->setSubExpr(SubExpr);
16307       E->setType(SubExpr->getType());
16308       E->setValueKind(SubExpr->getValueKind());
16309       assert(E->getObjectKind() == OK_Ordinary);
16310       return E;
16311     }
16312 
16313     ExprResult VisitParenExpr(ParenExpr *E) {
16314       return rebuildSugarExpr(E);
16315     }
16316 
16317     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16318       return rebuildSugarExpr(E);
16319     }
16320 
16321     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16322       ExprResult SubResult = Visit(E->getSubExpr());
16323       if (SubResult.isInvalid()) return ExprError();
16324 
16325       Expr *SubExpr = SubResult.get();
16326       E->setSubExpr(SubExpr);
16327       E->setType(S.Context.getPointerType(SubExpr->getType()));
16328       assert(E->getValueKind() == VK_RValue);
16329       assert(E->getObjectKind() == OK_Ordinary);
16330       return E;
16331     }
16332 
16333     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16334       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16335 
16336       E->setType(VD->getType());
16337 
16338       assert(E->getValueKind() == VK_RValue);
16339       if (S.getLangOpts().CPlusPlus &&
16340           !(isa<CXXMethodDecl>(VD) &&
16341             cast<CXXMethodDecl>(VD)->isInstance()))
16342         E->setValueKind(VK_LValue);
16343 
16344       return E;
16345     }
16346 
16347     ExprResult VisitMemberExpr(MemberExpr *E) {
16348       return resolveDecl(E, E->getMemberDecl());
16349     }
16350 
16351     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16352       return resolveDecl(E, E->getDecl());
16353     }
16354   };
16355 }
16356 
16357 /// Given a function expression of unknown-any type, try to rebuild it
16358 /// to have a function type.
16359 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16360   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16361   if (Result.isInvalid()) return ExprError();
16362   return S.DefaultFunctionArrayConversion(Result.get());
16363 }
16364 
16365 namespace {
16366   /// A visitor for rebuilding an expression of type __unknown_anytype
16367   /// into one which resolves the type directly on the referring
16368   /// expression.  Strict preservation of the original source
16369   /// structure is not a goal.
16370   struct RebuildUnknownAnyExpr
16371     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16372 
16373     Sema &S;
16374 
16375     /// The current destination type.
16376     QualType DestType;
16377 
16378     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16379       : S(S), DestType(CastType) {}
16380 
16381     ExprResult VisitStmt(Stmt *S) {
16382       llvm_unreachable("unexpected statement!");
16383     }
16384 
16385     ExprResult VisitExpr(Expr *E) {
16386       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16387         << E->getSourceRange();
16388       return ExprError();
16389     }
16390 
16391     ExprResult VisitCallExpr(CallExpr *E);
16392     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16393 
16394     /// Rebuild an expression which simply semantically wraps another
16395     /// expression which it shares the type and value kind of.
16396     template <class T> ExprResult rebuildSugarExpr(T *E) {
16397       ExprResult SubResult = Visit(E->getSubExpr());
16398       if (SubResult.isInvalid()) return ExprError();
16399       Expr *SubExpr = SubResult.get();
16400       E->setSubExpr(SubExpr);
16401       E->setType(SubExpr->getType());
16402       E->setValueKind(SubExpr->getValueKind());
16403       assert(E->getObjectKind() == OK_Ordinary);
16404       return E;
16405     }
16406 
16407     ExprResult VisitParenExpr(ParenExpr *E) {
16408       return rebuildSugarExpr(E);
16409     }
16410 
16411     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16412       return rebuildSugarExpr(E);
16413     }
16414 
16415     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16416       const PointerType *Ptr = DestType->getAs<PointerType>();
16417       if (!Ptr) {
16418         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16419           << E->getSourceRange();
16420         return ExprError();
16421       }
16422 
16423       if (isa<CallExpr>(E->getSubExpr())) {
16424         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16425           << E->getSourceRange();
16426         return ExprError();
16427       }
16428 
16429       assert(E->getValueKind() == VK_RValue);
16430       assert(E->getObjectKind() == OK_Ordinary);
16431       E->setType(DestType);
16432 
16433       // Build the sub-expression as if it were an object of the pointee type.
16434       DestType = Ptr->getPointeeType();
16435       ExprResult SubResult = Visit(E->getSubExpr());
16436       if (SubResult.isInvalid()) return ExprError();
16437       E->setSubExpr(SubResult.get());
16438       return E;
16439     }
16440 
16441     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16442 
16443     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16444 
16445     ExprResult VisitMemberExpr(MemberExpr *E) {
16446       return resolveDecl(E, E->getMemberDecl());
16447     }
16448 
16449     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16450       return resolveDecl(E, E->getDecl());
16451     }
16452   };
16453 }
16454 
16455 /// Rebuilds a call expression which yielded __unknown_anytype.
16456 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16457   Expr *CalleeExpr = E->getCallee();
16458 
16459   enum FnKind {
16460     FK_MemberFunction,
16461     FK_FunctionPointer,
16462     FK_BlockPointer
16463   };
16464 
16465   FnKind Kind;
16466   QualType CalleeType = CalleeExpr->getType();
16467   if (CalleeType == S.Context.BoundMemberTy) {
16468     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16469     Kind = FK_MemberFunction;
16470     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16471   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16472     CalleeType = Ptr->getPointeeType();
16473     Kind = FK_FunctionPointer;
16474   } else {
16475     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16476     Kind = FK_BlockPointer;
16477   }
16478   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16479 
16480   // Verify that this is a legal result type of a function.
16481   if (DestType->isArrayType() || DestType->isFunctionType()) {
16482     unsigned diagID = diag::err_func_returning_array_function;
16483     if (Kind == FK_BlockPointer)
16484       diagID = diag::err_block_returning_array_function;
16485 
16486     S.Diag(E->getExprLoc(), diagID)
16487       << DestType->isFunctionType() << DestType;
16488     return ExprError();
16489   }
16490 
16491   // Otherwise, go ahead and set DestType as the call's result.
16492   E->setType(DestType.getNonLValueExprType(S.Context));
16493   E->setValueKind(Expr::getValueKindForType(DestType));
16494   assert(E->getObjectKind() == OK_Ordinary);
16495 
16496   // Rebuild the function type, replacing the result type with DestType.
16497   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16498   if (Proto) {
16499     // __unknown_anytype(...) is a special case used by the debugger when
16500     // it has no idea what a function's signature is.
16501     //
16502     // We want to build this call essentially under the K&R
16503     // unprototyped rules, but making a FunctionNoProtoType in C++
16504     // would foul up all sorts of assumptions.  However, we cannot
16505     // simply pass all arguments as variadic arguments, nor can we
16506     // portably just call the function under a non-variadic type; see
16507     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16508     // However, it turns out that in practice it is generally safe to
16509     // call a function declared as "A foo(B,C,D);" under the prototype
16510     // "A foo(B,C,D,...);".  The only known exception is with the
16511     // Windows ABI, where any variadic function is implicitly cdecl
16512     // regardless of its normal CC.  Therefore we change the parameter
16513     // types to match the types of the arguments.
16514     //
16515     // This is a hack, but it is far superior to moving the
16516     // corresponding target-specific code from IR-gen to Sema/AST.
16517 
16518     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16519     SmallVector<QualType, 8> ArgTypes;
16520     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16521       ArgTypes.reserve(E->getNumArgs());
16522       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16523         Expr *Arg = E->getArg(i);
16524         QualType ArgType = Arg->getType();
16525         if (E->isLValue()) {
16526           ArgType = S.Context.getLValueReferenceType(ArgType);
16527         } else if (E->isXValue()) {
16528           ArgType = S.Context.getRValueReferenceType(ArgType);
16529         }
16530         ArgTypes.push_back(ArgType);
16531       }
16532       ParamTypes = ArgTypes;
16533     }
16534     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16535                                          Proto->getExtProtoInfo());
16536   } else {
16537     DestType = S.Context.getFunctionNoProtoType(DestType,
16538                                                 FnType->getExtInfo());
16539   }
16540 
16541   // Rebuild the appropriate pointer-to-function type.
16542   switch (Kind) {
16543   case FK_MemberFunction:
16544     // Nothing to do.
16545     break;
16546 
16547   case FK_FunctionPointer:
16548     DestType = S.Context.getPointerType(DestType);
16549     break;
16550 
16551   case FK_BlockPointer:
16552     DestType = S.Context.getBlockPointerType(DestType);
16553     break;
16554   }
16555 
16556   // Finally, we can recurse.
16557   ExprResult CalleeResult = Visit(CalleeExpr);
16558   if (!CalleeResult.isUsable()) return ExprError();
16559   E->setCallee(CalleeResult.get());
16560 
16561   // Bind a temporary if necessary.
16562   return S.MaybeBindToTemporary(E);
16563 }
16564 
16565 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16566   // Verify that this is a legal result type of a call.
16567   if (DestType->isArrayType() || DestType->isFunctionType()) {
16568     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16569       << DestType->isFunctionType() << DestType;
16570     return ExprError();
16571   }
16572 
16573   // Rewrite the method result type if available.
16574   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16575     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16576     Method->setReturnType(DestType);
16577   }
16578 
16579   // Change the type of the message.
16580   E->setType(DestType.getNonReferenceType());
16581   E->setValueKind(Expr::getValueKindForType(DestType));
16582 
16583   return S.MaybeBindToTemporary(E);
16584 }
16585 
16586 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16587   // The only case we should ever see here is a function-to-pointer decay.
16588   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16589     assert(E->getValueKind() == VK_RValue);
16590     assert(E->getObjectKind() == OK_Ordinary);
16591 
16592     E->setType(DestType);
16593 
16594     // Rebuild the sub-expression as the pointee (function) type.
16595     DestType = DestType->castAs<PointerType>()->getPointeeType();
16596 
16597     ExprResult Result = Visit(E->getSubExpr());
16598     if (!Result.isUsable()) return ExprError();
16599 
16600     E->setSubExpr(Result.get());
16601     return E;
16602   } else if (E->getCastKind() == CK_LValueToRValue) {
16603     assert(E->getValueKind() == VK_RValue);
16604     assert(E->getObjectKind() == OK_Ordinary);
16605 
16606     assert(isa<BlockPointerType>(E->getType()));
16607 
16608     E->setType(DestType);
16609 
16610     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16611     DestType = S.Context.getLValueReferenceType(DestType);
16612 
16613     ExprResult Result = Visit(E->getSubExpr());
16614     if (!Result.isUsable()) return ExprError();
16615 
16616     E->setSubExpr(Result.get());
16617     return E;
16618   } else {
16619     llvm_unreachable("Unhandled cast type!");
16620   }
16621 }
16622 
16623 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16624   ExprValueKind ValueKind = VK_LValue;
16625   QualType Type = DestType;
16626 
16627   // We know how to make this work for certain kinds of decls:
16628 
16629   //  - functions
16630   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16631     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16632       DestType = Ptr->getPointeeType();
16633       ExprResult Result = resolveDecl(E, VD);
16634       if (Result.isInvalid()) return ExprError();
16635       return S.ImpCastExprToType(Result.get(), Type,
16636                                  CK_FunctionToPointerDecay, VK_RValue);
16637     }
16638 
16639     if (!Type->isFunctionType()) {
16640       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16641         << VD << E->getSourceRange();
16642       return ExprError();
16643     }
16644     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16645       // We must match the FunctionDecl's type to the hack introduced in
16646       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16647       // type. See the lengthy commentary in that routine.
16648       QualType FDT = FD->getType();
16649       const FunctionType *FnType = FDT->castAs<FunctionType>();
16650       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16651       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16652       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16653         SourceLocation Loc = FD->getLocation();
16654         FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
16655                                       FD->getDeclContext(),
16656                                       Loc, Loc, FD->getNameInfo().getName(),
16657                                       DestType, FD->getTypeSourceInfo(),
16658                                       SC_None, false/*isInlineSpecified*/,
16659                                       FD->hasPrototype(),
16660                                       false/*isConstexprSpecified*/);
16661 
16662         if (FD->getQualifier())
16663           NewFD->setQualifierInfo(FD->getQualifierLoc());
16664 
16665         SmallVector<ParmVarDecl*, 16> Params;
16666         for (const auto &AI : FT->param_types()) {
16667           ParmVarDecl *Param =
16668             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16669           Param->setScopeInfo(0, Params.size());
16670           Params.push_back(Param);
16671         }
16672         NewFD->setParams(Params);
16673         DRE->setDecl(NewFD);
16674         VD = DRE->getDecl();
16675       }
16676     }
16677 
16678     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16679       if (MD->isInstance()) {
16680         ValueKind = VK_RValue;
16681         Type = S.Context.BoundMemberTy;
16682       }
16683 
16684     // Function references aren't l-values in C.
16685     if (!S.getLangOpts().CPlusPlus)
16686       ValueKind = VK_RValue;
16687 
16688   //  - variables
16689   } else if (isa<VarDecl>(VD)) {
16690     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16691       Type = RefTy->getPointeeType();
16692     } else if (Type->isFunctionType()) {
16693       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16694         << VD << E->getSourceRange();
16695       return ExprError();
16696     }
16697 
16698   //  - nothing else
16699   } else {
16700     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16701       << VD << E->getSourceRange();
16702     return ExprError();
16703   }
16704 
16705   // Modifying the declaration like this is friendly to IR-gen but
16706   // also really dangerous.
16707   VD->setType(DestType);
16708   E->setType(Type);
16709   E->setValueKind(ValueKind);
16710   return E;
16711 }
16712 
16713 /// Check a cast of an unknown-any type.  We intentionally only
16714 /// trigger this for C-style casts.
16715 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16716                                      Expr *CastExpr, CastKind &CastKind,
16717                                      ExprValueKind &VK, CXXCastPath &Path) {
16718   // The type we're casting to must be either void or complete.
16719   if (!CastType->isVoidType() &&
16720       RequireCompleteType(TypeRange.getBegin(), CastType,
16721                           diag::err_typecheck_cast_to_incomplete))
16722     return ExprError();
16723 
16724   // Rewrite the casted expression from scratch.
16725   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16726   if (!result.isUsable()) return ExprError();
16727 
16728   CastExpr = result.get();
16729   VK = CastExpr->getValueKind();
16730   CastKind = CK_NoOp;
16731 
16732   return CastExpr;
16733 }
16734 
16735 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16736   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16737 }
16738 
16739 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16740                                     Expr *arg, QualType &paramType) {
16741   // If the syntactic form of the argument is not an explicit cast of
16742   // any sort, just do default argument promotion.
16743   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16744   if (!castArg) {
16745     ExprResult result = DefaultArgumentPromotion(arg);
16746     if (result.isInvalid()) return ExprError();
16747     paramType = result.get()->getType();
16748     return result;
16749   }
16750 
16751   // Otherwise, use the type that was written in the explicit cast.
16752   assert(!arg->hasPlaceholderType());
16753   paramType = castArg->getTypeAsWritten();
16754 
16755   // Copy-initialize a parameter of that type.
16756   InitializedEntity entity =
16757     InitializedEntity::InitializeParameter(Context, paramType,
16758                                            /*consumed*/ false);
16759   return PerformCopyInitialization(entity, callLoc, arg);
16760 }
16761 
16762 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16763   Expr *orig = E;
16764   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16765   while (true) {
16766     E = E->IgnoreParenImpCasts();
16767     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16768       E = call->getCallee();
16769       diagID = diag::err_uncasted_call_of_unknown_any;
16770     } else {
16771       break;
16772     }
16773   }
16774 
16775   SourceLocation loc;
16776   NamedDecl *d;
16777   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16778     loc = ref->getLocation();
16779     d = ref->getDecl();
16780   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16781     loc = mem->getMemberLoc();
16782     d = mem->getMemberDecl();
16783   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16784     diagID = diag::err_uncasted_call_of_unknown_any;
16785     loc = msg->getSelectorStartLoc();
16786     d = msg->getMethodDecl();
16787     if (!d) {
16788       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16789         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16790         << orig->getSourceRange();
16791       return ExprError();
16792     }
16793   } else {
16794     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16795       << E->getSourceRange();
16796     return ExprError();
16797   }
16798 
16799   S.Diag(loc, diagID) << d << orig->getSourceRange();
16800 
16801   // Never recoverable.
16802   return ExprError();
16803 }
16804 
16805 /// Check for operands with placeholder types and complain if found.
16806 /// Returns ExprError() if there was an error and no recovery was possible.
16807 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16808   if (!getLangOpts().CPlusPlus) {
16809     // C cannot handle TypoExpr nodes on either side of a binop because it
16810     // doesn't handle dependent types properly, so make sure any TypoExprs have
16811     // been dealt with before checking the operands.
16812     ExprResult Result = CorrectDelayedTyposInExpr(E);
16813     if (!Result.isUsable()) return ExprError();
16814     E = Result.get();
16815   }
16816 
16817   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16818   if (!placeholderType) return E;
16819 
16820   switch (placeholderType->getKind()) {
16821 
16822   // Overloaded expressions.
16823   case BuiltinType::Overload: {
16824     // Try to resolve a single function template specialization.
16825     // This is obligatory.
16826     ExprResult Result = E;
16827     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16828       return Result;
16829 
16830     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16831     // leaves Result unchanged on failure.
16832     Result = E;
16833     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16834       return Result;
16835 
16836     // If that failed, try to recover with a call.
16837     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16838                          /*complain*/ true);
16839     return Result;
16840   }
16841 
16842   // Bound member functions.
16843   case BuiltinType::BoundMember: {
16844     ExprResult result = E;
16845     const Expr *BME = E->IgnoreParens();
16846     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16847     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16848     if (isa<CXXPseudoDestructorExpr>(BME)) {
16849       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16850     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16851       if (ME->getMemberNameInfo().getName().getNameKind() ==
16852           DeclarationName::CXXDestructorName)
16853         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16854     }
16855     tryToRecoverWithCall(result, PD,
16856                          /*complain*/ true);
16857     return result;
16858   }
16859 
16860   // ARC unbridged casts.
16861   case BuiltinType::ARCUnbridgedCast: {
16862     Expr *realCast = stripARCUnbridgedCast(E);
16863     diagnoseARCUnbridgedCast(realCast);
16864     return realCast;
16865   }
16866 
16867   // Expressions of unknown type.
16868   case BuiltinType::UnknownAny:
16869     return diagnoseUnknownAnyExpr(*this, E);
16870 
16871   // Pseudo-objects.
16872   case BuiltinType::PseudoObject:
16873     return checkPseudoObjectRValue(E);
16874 
16875   case BuiltinType::BuiltinFn: {
16876     // Accept __noop without parens by implicitly converting it to a call expr.
16877     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16878     if (DRE) {
16879       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16880       if (FD->getBuiltinID() == Builtin::BI__noop) {
16881         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16882                               CK_BuiltinFnToFnPtr)
16883                 .get();
16884         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16885                                 VK_RValue, SourceLocation());
16886       }
16887     }
16888 
16889     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16890     return ExprError();
16891   }
16892 
16893   // Expressions of unknown type.
16894   case BuiltinType::OMPArraySection:
16895     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16896     return ExprError();
16897 
16898   // Everything else should be impossible.
16899 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16900   case BuiltinType::Id:
16901 #include "clang/Basic/OpenCLImageTypes.def"
16902 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16903   case BuiltinType::Id:
16904 #include "clang/Basic/OpenCLExtensionTypes.def"
16905 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16906 #define PLACEHOLDER_TYPE(Id, SingletonId)
16907 #include "clang/AST/BuiltinTypes.def"
16908     break;
16909   }
16910 
16911   llvm_unreachable("invalid placeholder type!");
16912 }
16913 
16914 bool Sema::CheckCaseExpression(Expr *E) {
16915   if (E->isTypeDependent())
16916     return true;
16917   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16918     return E->getType()->isIntegralOrEnumerationType();
16919   return false;
16920 }
16921 
16922 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16923 ExprResult
16924 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16925   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16926          "Unknown Objective-C Boolean value!");
16927   QualType BoolT = Context.ObjCBuiltinBoolTy;
16928   if (!Context.getBOOLDecl()) {
16929     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16930                         Sema::LookupOrdinaryName);
16931     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16932       NamedDecl *ND = Result.getFoundDecl();
16933       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16934         Context.setBOOLDecl(TD);
16935     }
16936   }
16937   if (Context.getBOOLDecl())
16938     BoolT = Context.getBOOLType();
16939   return new (Context)
16940       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16941 }
16942 
16943 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16944     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16945     SourceLocation RParen) {
16946 
16947   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16948 
16949   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16950                            [&](const AvailabilitySpec &Spec) {
16951                              return Spec.getPlatform() == Platform;
16952                            });
16953 
16954   VersionTuple Version;
16955   if (Spec != AvailSpecs.end())
16956     Version = Spec->getVersion();
16957 
16958   // The use of `@available` in the enclosing function should be analyzed to
16959   // warn when it's used inappropriately (i.e. not if(@available)).
16960   if (getCurFunctionOrMethodDecl())
16961     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16962   else if (getCurBlock() || getCurLambda())
16963     getCurFunction()->HasPotentialAvailabilityViolations = true;
16964 
16965   return new (Context)
16966       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16967 }
16968